index-DlWXszIh.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739
  1. function mde(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var k_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var QM={exports:{}},ov={};var f8;function hde(){if(f8)return ov;f8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ov.Fragment=e,ov.jsx=n,ov.jsxs=n,ov}var g8;function pde(){return g8||(g8=1,QM.exports=hde()),QM.exports}var a=pde(),ZM={exports:{}},$n={};var b8;function fde(){if(b8)return $n;b8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),m=Symbol.for("react.activity"),p=Symbol.iterator;function f(K){return K===null||typeof K!="object"?null:(K=p&&K[p]||K["@@iterator"],typeof K=="function"?K:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function g(K,ne,oe){this.props=K,this.context=ne,this.refs=b,this.updater=oe||y}g.prototype.isReactComponent={},g.prototype.setState=function(K,ne){if(typeof K!="object"&&typeof K!="function"&&K!=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,K,ne,"setState")},g.prototype.forceUpdate=function(K){this.updater.enqueueForceUpdate(this,K,"forceUpdate")};function _(){}_.prototype=g.prototype;function k(K,ne,oe){this.props=K,this.context=ne,this.refs=b,this.updater=oe||y}var P=k.prototype=new _;P.constructor=k,v(P,g.prototype),P.isPureReactComponent=!0;var N=Array.isArray;function M(){}var A={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function C(K,ne,oe){var be=oe.ref;return{$$typeof:t,type:K,key:ne,ref:be!==void 0?be:null,props:oe}}function F(K,ne){return C(K.type,ne,K.props)}function $(K){return typeof K=="object"&&K!==null&&K.$$typeof===t}function I(K){var ne={"=":"=0",":":"=2"};return"$"+K.replace(/[=:]/g,function(oe){return ne[oe]})}var X=/\/+/g;function L(K,ne){return typeof K=="object"&&K!==null&&K.key!=null?I(""+K.key):ne.toString(36)}function te(K){switch(K.status){case"fulfilled":return K.value;case"rejected":throw K.reason;default:switch(typeof K.status=="string"?K.then(M,M):(K.status="pending",K.then(function(ne){K.status==="pending"&&(K.status="fulfilled",K.value=ne)},function(ne){K.status==="pending"&&(K.status="rejected",K.reason=ne)})),K.status){case"fulfilled":return K.value;case"rejected":throw K.reason}}throw K}function ae(K,ne,oe,be,_e){var B=typeof K;(B==="undefined"||B==="boolean")&&(K=null);var Y=!1;if(K===null)Y=!0;else switch(B){case"bigint":case"string":case"number":Y=!0;break;case"object":switch(K.$$typeof){case t:case e:Y=!0;break;case u:return Y=K._init,ae(Y(K._payload),ne,oe,be,_e)}}if(Y)return _e=_e(K),Y=be===""?"."+L(K,0):be,N(_e)?(oe="",Y!=null&&(oe=Y.replace(X,"$&/")+"/"),ae(_e,ne,oe,"",function(z){return z})):_e!=null&&($(_e)&&(_e=F(_e,oe+(_e.key==null||K&&K.key===_e.key?"":(""+_e.key).replace(X,"$&/")+"/")+Y)),ne.push(_e)),1;Y=0;var D=be===""?".":be+":";if(N(K))for(var j=0;j<K.length;j++)be=K[j],B=D+L(be,j),Y+=ae(be,ne,oe,B,_e);else if(j=f(K),typeof j=="function")for(K=j.call(K),j=0;!(be=K.next()).done;)be=be.value,B=D+L(be,j++),Y+=ae(be,ne,oe,B,_e);else if(B==="object"){if(typeof K.then=="function")return ae(te(K),ne,oe,be,_e);throw ne=String(K),Error("Objects are not valid as a React child (found: "+(ne==="[object Object]"?"object with keys {"+Object.keys(K).join(", ")+"}":ne)+"). If you meant to render a collection of children, use an array instead.")}return Y}function ee(K,ne,oe){if(K==null)return K;var be=[],_e=0;return ae(K,be,"","",function(B){return ne.call(oe,B,_e++)}),be}function me(K){if(K._status===-1){var ne=K._result;ne=ne(),ne.then(function(oe){(K._status===0||K._status===-1)&&(K._status=1,K._result=oe)},function(oe){(K._status===0||K._status===-1)&&(K._status=2,K._result=oe)}),K._status===-1&&(K._status=0,K._result=ne)}if(K._status===1)return K._result.default;throw K._result}var le=typeof reportError=="function"?reportError:function(K){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ne=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof K=="object"&&K!==null&&typeof K.message=="string"?String(K.message):String(K),error:K});if(!window.dispatchEvent(ne))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",K);return}console.error(K)},ue={map:ee,forEach:function(K,ne,oe){ee(K,function(){ne.apply(this,arguments)},oe)},count:function(K){var ne=0;return ee(K,function(){ne++}),ne},toArray:function(K){return ee(K,function(ne){return ne})||[]},only:function(K){if(!$(K))throw Error("React.Children.only expected to receive a single React element child.");return K}};return $n.Activity=m,$n.Children=ue,$n.Component=g,$n.Fragment=n,$n.Profiler=i,$n.PureComponent=k,$n.StrictMode=r,$n.Suspense=c,$n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,$n.__COMPILER_RUNTIME={__proto__:null,c:function(K){return A.H.useMemoCache(K)}},$n.cache=function(K){return function(){return K.apply(null,arguments)}},$n.cacheSignal=function(){return null},$n.cloneElement=function(K,ne,oe){if(K==null)throw Error("The argument must be a React element, but you passed "+K+".");var be=v({},K.props),_e=K.key;if(ne!=null)for(B in ne.key!==void 0&&(_e=""+ne.key),ne)!T.call(ne,B)||B==="key"||B==="__self"||B==="__source"||B==="ref"&&ne.ref===void 0||(be[B]=ne[B]);var B=arguments.length-2;if(B===1)be.children=oe;else if(1<B){for(var Y=Array(B),D=0;D<B;D++)Y[D]=arguments[D+2];be.children=Y}return C(K.type,_e,be)},$n.createContext=function(K){return K={$$typeof:o,_currentValue:K,_currentValue2:K,_threadCount:0,Provider:null,Consumer:null},K.Provider=K,K.Consumer={$$typeof:s,_context:K},K},$n.createElement=function(K,ne,oe){var be,_e={},B=null;if(ne!=null)for(be in ne.key!==void 0&&(B=""+ne.key),ne)T.call(ne,be)&&be!=="key"&&be!=="__self"&&be!=="__source"&&(_e[be]=ne[be]);var Y=arguments.length-2;if(Y===1)_e.children=oe;else if(1<Y){for(var D=Array(Y),j=0;j<Y;j++)D[j]=arguments[j+2];_e.children=D}if(K&&K.defaultProps)for(be in Y=K.defaultProps,Y)_e[be]===void 0&&(_e[be]=Y[be]);return C(K,B,_e)},$n.createRef=function(){return{current:null}},$n.forwardRef=function(K){return{$$typeof:l,render:K}},$n.isValidElement=$,$n.lazy=function(K){return{$$typeof:u,_payload:{_status:-1,_result:K},_init:me}},$n.memo=function(K,ne){return{$$typeof:d,type:K,compare:ne===void 0?null:ne}},$n.startTransition=function(K){var ne=A.T,oe={};A.T=oe;try{var be=K(),_e=A.S;_e!==null&&_e(oe,be),typeof be=="object"&&be!==null&&typeof be.then=="function"&&be.then(M,le)}catch(B){le(B)}finally{ne!==null&&oe.types!==null&&(ne.types=oe.types),A.T=ne}},$n.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},$n.use=function(K){return A.H.use(K)},$n.useActionState=function(K,ne,oe){return A.H.useActionState(K,ne,oe)},$n.useCallback=function(K,ne){return A.H.useCallback(K,ne)},$n.useContext=function(K){return A.H.useContext(K)},$n.useDebugValue=function(){},$n.useDeferredValue=function(K,ne){return A.H.useDeferredValue(K,ne)},$n.useEffect=function(K,ne){return A.H.useEffect(K,ne)},$n.useEffectEvent=function(K){return A.H.useEffectEvent(K)},$n.useId=function(){return A.H.useId()},$n.useImperativeHandle=function(K,ne,oe){return A.H.useImperativeHandle(K,ne,oe)},$n.useInsertionEffect=function(K,ne){return A.H.useInsertionEffect(K,ne)},$n.useLayoutEffect=function(K,ne){return A.H.useLayoutEffect(K,ne)},$n.useMemo=function(K,ne){return A.H.useMemo(K,ne)},$n.useOptimistic=function(K,ne){return A.H.useOptimistic(K,ne)},$n.useReducer=function(K,ne,oe){return A.H.useReducer(K,ne,oe)},$n.useRef=function(K){return A.H.useRef(K)},$n.useState=function(K){return A.H.useState(K)},$n.useSyncExternalStore=function(K,ne,oe){return A.H.useSyncExternalStore(K,ne,oe)},$n.useTransition=function(){return A.H.useTransition()},$n.version="19.2.4",$n}var x8;function og(){return x8||(x8=1,ZM.exports=fde()),ZM.exports}var w=og();const Qr=rc(w),gde=mde({__proto__:null,default:Qr},[w]);var JM={exports:{}},lv={},ej={exports:{}},tj={};var y8;function bde(){return y8||(y8=1,(function(t){function e(ae,ee){var me=ae.length;ae.push(ee);e:for(;0<me;){var le=me-1>>>1,ue=ae[le];if(0<i(ue,ee))ae[le]=ee,ae[me]=ue,me=le;else break e}}function n(ae){return ae.length===0?null:ae[0]}function r(ae){if(ae.length===0)return null;var ee=ae[0],me=ae.pop();if(me!==ee){ae[0]=me;e:for(var le=0,ue=ae.length,K=ue>>>1;le<K;){var ne=2*(le+1)-1,oe=ae[ne],be=ne+1,_e=ae[be];if(0>i(oe,me))be<ue&&0>i(_e,oe)?(ae[le]=_e,ae[be]=me,le=be):(ae[le]=oe,ae[ne]=me,le=ne);else if(be<ue&&0>i(_e,me))ae[le]=_e,ae[be]=me,le=be;else break e}}return ee}function i(ae,ee){var me=ae.sortIndex-ee.sortIndex;return me!==0?me:ae.id-ee.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],d=[],u=1,m=null,p=3,f=!1,y=!1,v=!1,b=!1,g=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function P(ae){for(var ee=n(d);ee!==null;){if(ee.callback===null)r(d);else if(ee.startTime<=ae)r(d),ee.sortIndex=ee.expirationTime,e(c,ee);else break;ee=n(d)}}function N(ae){if(v=!1,P(ae),!y)if(n(c)!==null)y=!0,M||(M=!0,I());else{var ee=n(d);ee!==null&&te(N,ee.startTime-ae)}}var M=!1,A=-1,T=5,C=-1;function F(){return b?!0:!(t.unstable_now()-C<T)}function $(){if(b=!1,M){var ae=t.unstable_now();C=ae;var ee=!0;try{e:{y=!1,v&&(v=!1,_(A),A=-1),f=!0;var me=p;try{t:{for(P(ae),m=n(c);m!==null&&!(m.expirationTime>ae&&F());){var le=m.callback;if(typeof le=="function"){m.callback=null,p=m.priorityLevel;var ue=le(m.expirationTime<=ae);if(ae=t.unstable_now(),typeof ue=="function"){m.callback=ue,P(ae),ee=!0;break t}m===n(c)&&r(c),P(ae)}else r(c);m=n(c)}if(m!==null)ee=!0;else{var K=n(d);K!==null&&te(N,K.startTime-ae),ee=!1}}break e}finally{m=null,p=me,f=!1}ee=void 0}}finally{ee?I():M=!1}}}var I;if(typeof k=="function")I=function(){k($)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,L=X.port2;X.port1.onmessage=$,I=function(){L.postMessage(null)}}else I=function(){g($,0)};function te(ae,ee){A=g(function(){ae(t.unstable_now())},ee)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(ae){ae.callback=null},t.unstable_forceFrameRate=function(ae){0>ae||125<ae?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<ae?Math.floor(1e3/ae):5},t.unstable_getCurrentPriorityLevel=function(){return p},t.unstable_next=function(ae){switch(p){case 1:case 2:case 3:var ee=3;break;default:ee=p}var me=p;p=ee;try{return ae()}finally{p=me}},t.unstable_requestPaint=function(){b=!0},t.unstable_runWithPriority=function(ae,ee){switch(ae){case 1:case 2:case 3:case 4:case 5:break;default:ae=3}var me=p;p=ae;try{return ee()}finally{p=me}},t.unstable_scheduleCallback=function(ae,ee,me){var le=t.unstable_now();switch(typeof me=="object"&&me!==null?(me=me.delay,me=typeof me=="number"&&0<me?le+me:le):me=le,ae){case 1:var ue=-1;break;case 2:ue=250;break;case 5:ue=1073741823;break;case 4:ue=1e4;break;default:ue=5e3}return ue=me+ue,ae={id:u++,callback:ee,priorityLevel:ae,startTime:me,expirationTime:ue,sortIndex:-1},me>le?(ae.sortIndex=me,e(d,ae),n(c)===null&&ae===n(d)&&(v?(_(A),A=-1):v=!0,te(N,me-le))):(ae.sortIndex=ue,e(c,ae),y||f||(y=!0,M||(M=!0,I()))),ae},t.unstable_shouldYield=F,t.unstable_wrapCallback=function(ae){var ee=p;return function(){var me=p;p=ee;try{return ae.apply(this,arguments)}finally{p=me}}}})(tj)),tj}var v8;function xde(){return v8||(v8=1,ej.exports=bde()),ej.exports}var nj={exports:{}},vs={};var w8;function yde(){if(w8)return vs;w8=1;var t=og();function e(c){var d="https://react.dev/errors/"+c;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var u=2;u<arguments.length;u++)d+="&args[]="+encodeURIComponent(arguments[u])}return"Minified React error #"+c+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(e(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},i=Symbol.for("react.portal");function s(c,d,u){var m=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:m==null?null:""+m,children:c,containerInfo:d,implementation:u}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,d){if(c==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return vs.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vs.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)},vs.flushSync=function(c){var d=o.T,u=r.p;try{if(o.T=null,r.p=2,c)return c()}finally{o.T=d,r.p=u,r.d.f()}},vs.preconnect=function(c,d){typeof c=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,r.d.C(c,d))},vs.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},vs.preinit=function(c,d){if(typeof c=="string"&&d&&typeof d.as=="string"){var u=d.as,m=l(u,d.crossOrigin),p=typeof d.integrity=="string"?d.integrity:void 0,f=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;u==="style"?r.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:m,integrity:p,fetchPriority:f}):u==="script"&&r.d.X(c,{crossOrigin:m,integrity:p,fetchPriority:f,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},vs.preinitModule=function(c,d){if(typeof c=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var u=l(d.as,d.crossOrigin);r.d.M(c,{crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&r.d.M(c)},vs.preload=function(c,d){if(typeof c=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var u=d.as,m=l(u,d.crossOrigin);r.d.L(c,u,{crossOrigin:m,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},vs.preloadModule=function(c,d){if(typeof c=="string")if(d){var u=l(d.as,d.crossOrigin);r.d.m(c,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else r.d.m(c)},vs.requestFormReset=function(c){r.d.r(c)},vs.unstable_batchedUpdates=function(c,d){return c(d)},vs.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},vs.useFormStatus=function(){return o.H.useHostTransitionStatus()},vs.version="19.2.4",vs}var S8;function xX(){if(S8)return nj.exports;S8=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(),nj.exports=yde(),nj.exports}var _8;function vde(){if(_8)return lv;_8=1;var t=xde(),e=og(),n=xX();function r(h){var x="https://react.dev/errors/"+h;if(1<arguments.length){x+="?args[]="+encodeURIComponent(arguments[1]);for(var S=2;S<arguments.length;S++)x+="&args[]="+encodeURIComponent(arguments[S])}return"Minified React error #"+h+"; visit "+x+" 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 x=h,S=h;if(h.alternate)for(;x.return;)x=x.return;else{h=x;do x=h,(x.flags&4098)!==0&&(S=x.return),h=x.return;while(h)}return x.tag===3?S:null}function o(h){if(h.tag===13){var x=h.memoizedState;if(x===null&&(h=h.alternate,h!==null&&(x=h.memoizedState)),x!==null)return x.dehydrated}return null}function l(h){if(h.tag===31){var x=h.memoizedState;if(x===null&&(h=h.alternate,h!==null&&(x=h.memoizedState)),x!==null)return x.dehydrated}return null}function c(h){if(s(h)!==h)throw Error(r(188))}function d(h){var x=h.alternate;if(!x){if(x=s(h),x===null)throw Error(r(188));return x!==h?null:h}for(var S=h,E=x;;){var H=S.return;if(H===null)break;var Z=H.alternate;if(Z===null){if(E=H.return,E!==null){S=E;continue}break}if(H.child===Z.child){for(Z=H.child;Z;){if(Z===S)return c(H),h;if(Z===E)return c(H),x;Z=Z.sibling}throw Error(r(188))}if(S.return!==E.return)S=H,E=Z;else{for(var ke=!1,Be=H.child;Be;){if(Be===S){ke=!0,S=H,E=Z;break}if(Be===E){ke=!0,E=H,S=Z;break}Be=Be.sibling}if(!ke){for(Be=Z.child;Be;){if(Be===S){ke=!0,S=Z,E=H;break}if(Be===E){ke=!0,E=Z,S=H;break}Be=Be.sibling}if(!ke)throw Error(r(189))}}if(S.alternate!==E)throw Error(r(190))}if(S.tag!==3)throw Error(r(188));return S.stateNode.current===S?h:x}function u(h){var x=h.tag;if(x===5||x===26||x===27||x===6)return h;for(h=h.child;h!==null;){if(x=u(h),x!==null)return x;h=h.sibling}return null}var m=Object.assign,p=Symbol.for("react.element"),f=Symbol.for("react.transitional.element"),y=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),g=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),k=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),A=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),F=Symbol.for("react.memo_cache_sentinel"),$=Symbol.iterator;function I(h){return h===null||typeof h!="object"?null:(h=$&&h[$]||h["@@iterator"],typeof h=="function"?h:null)}var X=Symbol.for("react.client.reference");function L(h){if(h==null)return null;if(typeof h=="function")return h.$$typeof===X?null:h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case v:return"Fragment";case g:return"Profiler";case b:return"StrictMode";case N:return"Suspense";case M:return"SuspenseList";case C:return"Activity"}if(typeof h=="object")switch(h.$$typeof){case y:return"Portal";case k:return h.displayName||"Context";case _:return(h._context.displayName||"Context")+".Consumer";case P:var x=h.render;return h=h.displayName,h||(h=x.displayName||x.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case A:return x=h.displayName||null,x!==null?x:L(h.type)||"Memo";case T:x=h._payload,h=h._init;try{return L(h(x))}catch{}}return null}var te=Array.isArray,ae=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,me={pending:!1,data:null,method:null,action:null},le=[],ue=-1;function K(h){return{current:h}}function ne(h){0>ue||(h.current=le[ue],le[ue]=null,ue--)}function oe(h,x){ue++,le[ue]=h.current,h.current=x}var be=K(null),_e=K(null),B=K(null),Y=K(null);function D(h,x){switch(oe(B,x),oe(_e,h),oe(be,null),x.nodeType){case 9:case 11:h=(h=x.documentElement)&&(h=h.namespaceURI)?IB(h):0;break;default:if(h=x.tagName,x=x.namespaceURI)x=IB(x),h=zB(x,h);else switch(h){case"svg":h=1;break;case"math":h=2;break;default:h=0}}ne(be),oe(be,h)}function j(){ne(be),ne(_e),ne(B)}function z(h){h.memoizedState!==null&&oe(Y,h);var x=be.current,S=zB(x,h.type);x!==S&&(oe(_e,h),oe(be,S))}function W(h){_e.current===h&&(ne(be),ne(_e)),Y.current===h&&(ne(Y),rv._currentValue=me)}var q,de;function O(h){if(q===void 0)try{throw Error()}catch(S){var x=S.stack.trim().match(/\n( *(at )?)/);q=x&&x[1]||"",de=-1<S.stack.indexOf(`
  2. at`)?" (<anonymous>)":-1<S.stack.indexOf("@")?"@unknown:0:0":""}return`
  3. `+q+h+de}var G=!1;function Q(h,x){if(!h||G)return"";G=!0;var S=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var E={DetermineComponentFrameRoot:function(){try{if(x){var zt=function(){throw Error()};if(Object.defineProperty(zt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(zt,[])}catch(Et){var Tt=Et}Reflect.construct(h,[],zt)}else{try{zt.call()}catch(Et){Tt=Et}h.call(zt.prototype)}}else{try{throw Error()}catch(Et){Tt=Et}(zt=h())&&typeof zt.catch=="function"&&zt.catch(function(){})}}catch(Et){if(Et&&Tt&&typeof Et.stack=="string")return[Et.stack,Tt.stack]}return[null,null]}};E.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(E.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(E.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Z=E.DetermineComponentFrameRoot(),ke=Z[0],Be=Z[1];if(ke&&Be){var nt=ke.split(`
  4. `),kt=Be.split(`
  5. `);for(H=E=0;E<nt.length&&!nt[E].includes("DetermineComponentFrameRoot");)E++;for(;H<kt.length&&!kt[H].includes("DetermineComponentFrameRoot");)H++;if(E===nt.length||H===kt.length)for(E=nt.length-1,H=kt.length-1;1<=E&&0<=H&&nt[E]!==kt[H];)H--;for(;1<=E&&0<=H;E--,H--)if(nt[E]!==kt[H]){if(E!==1||H!==1)do if(E--,H--,0>H||nt[E]!==kt[H]){var Ot=`
  6. `+nt[E].replace(" at new "," at ");return h.displayName&&Ot.includes("<anonymous>")&&(Ot=Ot.replace("<anonymous>",h.displayName)),Ot}while(1<=E&&0<=H);break}}}finally{G=!1,Error.prepareStackTrace=S}return(S=h?h.displayName||h.name:"")?O(S):""}function V(h,x){switch(h.tag){case 26:case 27:case 5:return O(h.type);case 16:return O("Lazy");case 13:return h.child!==x&&x!==null?O("Suspense Fallback"):O("Suspense");case 19:return O("SuspenseList");case 0:case 15:return Q(h.type,!1);case 11:return Q(h.type.render,!1);case 1:return Q(h.type,!0);case 31:return O("Activity");default:return""}}function J(h){try{var x="",S=null;do x+=V(h,S),S=h,h=h.return;while(h);return x}catch(E){return`
  7. Error generating stack: `+E.message+`
  8. `+E.stack}}var ie=Object.prototype.hasOwnProperty,he=t.unstable_scheduleCallback,fe=t.unstable_cancelCallback,se=t.unstable_shouldYield,U=t.unstable_requestPaint,R=t.unstable_now,re=t.unstable_getCurrentPriorityLevel,xe=t.unstable_ImmediatePriority,we=t.unstable_UserBlockingPriority,ye=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,ve=t.unstable_IdlePriority,Te=t.log,Fe=t.unstable_setDisableYieldValue,Ee=null,Se=null;function je(h){if(typeof Te=="function"&&Fe(h),Se&&typeof Se.setStrictMode=="function")try{Se.setStrictMode(Ee,h)}catch{}}var qe=Math.clz32?Math.clz32:ce,Re=Math.log,Ye=Math.LN2;function ce(h){return h>>>=0,h===0?32:31-(Re(h)/Ye|0)|0}var ze=256,Ne=262144,Ge=4194304;function $e(h){var x=h&42;if(x!==0)return x;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 Pe(h,x,S){var E=h.pendingLanes;if(E===0)return 0;var H=0,Z=h.suspendedLanes,ke=h.pingedLanes;h=h.warmLanes;var Be=E&134217727;return Be!==0?(E=Be&~Z,E!==0?H=$e(E):(ke&=Be,ke!==0?H=$e(ke):S||(S=Be&~h,S!==0&&(H=$e(S))))):(Be=E&~Z,Be!==0?H=$e(Be):ke!==0?H=$e(ke):S||(S=E&~h,S!==0&&(H=$e(S)))),H===0?0:x!==0&&x!==H&&(x&Z)===0&&(Z=H&-H,S=x&-x,Z>=S||Z===32&&(S&4194048)!==0)?x:H}function Me(h,x){return(h.pendingLanes&~(h.suspendedLanes&~h.pingedLanes)&x)===0}function Ve(h,x){switch(h){case 1:case 2:case 4:case 8:case 64:return x+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 x+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 tt(){var h=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),h}function ut(h){for(var x=[],S=0;31>S;S++)x.push(h);return x}function xt(h,x){h.pendingLanes|=x,x!==268435456&&(h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0)}function wt(h,x,S,E,H,Z){var ke=h.pendingLanes;h.pendingLanes=S,h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0,h.expiredLanes&=S,h.entangledLanes&=S,h.errorRecoveryDisabledLanes&=S,h.shellSuspendCounter=0;var Be=h.entanglements,nt=h.expirationTimes,kt=h.hiddenUpdates;for(S=ke&~S;0<S;){var Ot=31-qe(S),zt=1<<Ot;Be[Ot]=0,nt[Ot]=-1;var Tt=kt[Ot];if(Tt!==null)for(kt[Ot]=null,Ot=0;Ot<Tt.length;Ot++){var Et=Tt[Ot];Et!==null&&(Et.lane&=-536870913)}S&=~zt}E!==0&&Ht(h,E,0),Z!==0&&H===0&&h.tag!==0&&(h.suspendedLanes|=Z&~(ke&~x))}function Ht(h,x,S){h.pendingLanes|=x,h.suspendedLanes&=~x;var E=31-qe(x);h.entangledLanes|=x,h.entanglements[E]=h.entanglements[E]|1073741824|S&261930}function Xt(h,x){var S=h.entangledLanes|=x;for(h=h.entanglements;S;){var E=31-qe(S),H=1<<E;H&x|h[E]&x&&(h[E]|=x),S&=~H}}function Kt(h,x){var S=x&-x;return S=(S&42)!==0?1:Ut(S),(S&(h.suspendedLanes|x))!==0?0:S}function Ut(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 en(h){return h&=-h,2<h?8<h?(h&134217727)!==0?32:268435456:8:2}function Ke(){var h=ee.p;return h!==0?h:(h=window.event,h===void 0?32:l8(h.type))}function Ft(h,x){var S=ee.p;try{return ee.p=h,x()}finally{ee.p=S}}var Nt=Math.random().toString(36).slice(2),ht="__reactFiber$"+Nt,Mt="__reactProps$"+Nt,Qt="__reactContainer$"+Nt,Wt="__reactEvents$"+Nt,Ue="__reactListeners$"+Nt,dt="__reactHandles$"+Nt,pt="__reactResources$"+Nt,De="__reactMarker$"+Nt;function Le(h){delete h[ht],delete h[Mt],delete h[Wt],delete h[Ue],delete h[dt]}function at(h){var x=h[ht];if(x)return x;for(var S=h.parentNode;S;){if(x=S[Qt]||S[ht]){if(S=x.alternate,x.child!==null||S!==null&&S.child!==null)for(h=GB(h);h!==null;){if(S=h[ht])return S;h=GB(h)}return x}h=S,S=h.parentNode}return null}function Ce(h){if(h=h[ht]||h[Qt]){var x=h.tag;if(x===5||x===6||x===13||x===31||x===26||x===27||x===3)return h}return null}function We(h){var x=h.tag;if(x===5||x===26||x===27||x===6)return h.stateNode;throw Error(r(33))}function Xe(h){var x=h[pt];return x||(x=h[pt]={hoistableStyles:new Map,hoistableScripts:new Map}),x}function Qe(h){h[De]=!0}var Ze=new Set,rt={};function bt(h,x){Pt(h,x),Pt(h+"Capture",x)}function Pt(h,x){for(rt[h]=x,h=0;h<x.length;h++)Ze.add(x[h])}var vt=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]*$"),He={},St={};function Ct(h){return ie.call(St,h)?!0:ie.call(He,h)?!1:vt.test(h)?St[h]=!0:(He[h]=!0,!1)}function Zt(h,x,S){if(Ct(x))if(S===null)h.removeAttribute(x);else{switch(typeof S){case"undefined":case"function":case"symbol":h.removeAttribute(x);return;case"boolean":var E=x.toLowerCase().slice(0,5);if(E!=="data-"&&E!=="aria-"){h.removeAttribute(x);return}}h.setAttribute(x,""+S)}}function Jt(h,x,S){if(S===null)h.removeAttribute(x);else{switch(typeof S){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(x);return}h.setAttribute(x,""+S)}}function Nn(h,x,S,E){if(E===null)h.removeAttribute(S);else{switch(typeof E){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(S);return}h.setAttributeNS(x,S,""+E)}}function vn(h){switch(typeof h){case"bigint":case"boolean":case"number":case"string":case"undefined":return h;case"object":return h;default:return""}}function yn(h){var x=h.type;return(h=h.nodeName)&&h.toLowerCase()==="input"&&(x==="checkbox"||x==="radio")}function an(h,x,S){var E=Object.getOwnPropertyDescriptor(h.constructor.prototype,x);if(!h.hasOwnProperty(x)&&typeof E<"u"&&typeof E.get=="function"&&typeof E.set=="function"){var H=E.get,Z=E.set;return Object.defineProperty(h,x,{configurable:!0,get:function(){return H.call(this)},set:function(ke){S=""+ke,Z.call(this,ke)}}),Object.defineProperty(h,x,{enumerable:E.enumerable}),{getValue:function(){return S},setValue:function(ke){S=""+ke},stopTracking:function(){h._valueTracker=null,delete h[x]}}}}function rn(h){if(!h._valueTracker){var x=yn(h)?"checked":"value";h._valueTracker=an(h,x,""+h[x])}}function bn(h){if(!h)return!1;var x=h._valueTracker;if(!x)return!0;var S=x.getValue(),E="";return h&&(E=yn(h)?h.checked?"true":"false":h.value),h=E,h!==S?(x.setValue(h),!0):!1}function Gn(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 ar=/[\n"\\]/g;function On(h){return h.replace(ar,function(x){return"\\"+x.charCodeAt(0).toString(16)+" "})}function mi(h,x,S,E,H,Z,ke,Be){h.name="",ke!=null&&typeof ke!="function"&&typeof ke!="symbol"&&typeof ke!="boolean"?h.type=ke:h.removeAttribute("type"),x!=null?ke==="number"?(x===0&&h.value===""||h.value!=x)&&(h.value=""+vn(x)):h.value!==""+vn(x)&&(h.value=""+vn(x)):ke!=="submit"&&ke!=="reset"||h.removeAttribute("value"),x!=null?na(h,ke,vn(x)):S!=null?na(h,ke,vn(S)):E!=null&&h.removeAttribute("value"),H==null&&Z!=null&&(h.defaultChecked=!!Z),H!=null&&(h.checked=H&&typeof H!="function"&&typeof H!="symbol"),Be!=null&&typeof Be!="function"&&typeof Be!="symbol"&&typeof Be!="boolean"?h.name=""+vn(Be):h.removeAttribute("name")}function Rn(h,x,S,E,H,Z,ke,Be){if(Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"&&(h.type=Z),x!=null||S!=null){if(!(Z!=="submit"&&Z!=="reset"||x!=null)){rn(h);return}S=S!=null?""+vn(S):"",x=x!=null?""+vn(x):S,Be||x===h.value||(h.value=x),h.defaultValue=x}E=E??H,E=typeof E!="function"&&typeof E!="symbol"&&!!E,h.checked=Be?h.checked:!!E,h.defaultChecked=!!E,ke!=null&&typeof ke!="function"&&typeof ke!="symbol"&&typeof ke!="boolean"&&(h.name=ke),rn(h)}function na(h,x,S){x==="number"&&Gn(h.ownerDocument)===h||h.defaultValue===""+S||(h.defaultValue=""+S)}function ra(h,x,S,E){if(h=h.options,x){x={};for(var H=0;H<S.length;H++)x["$"+S[H]]=!0;for(S=0;S<h.length;S++)H=x.hasOwnProperty("$"+h[S].value),h[S].selected!==H&&(h[S].selected=H),H&&E&&(h[S].defaultSelected=!0)}else{for(S=""+vn(S),x=null,H=0;H<h.length;H++){if(h[H].value===S){h[H].selected=!0,E&&(h[H].defaultSelected=!0);return}x!==null||h[H].disabled||(x=h[H])}x!==null&&(x.selected=!0)}}function jr(h,x,S){if(x!=null&&(x=""+vn(x),x!==h.value&&(h.value=x),S==null)){h.defaultValue!==x&&(h.defaultValue=x);return}h.defaultValue=S!=null?""+vn(S):""}function In(h,x,S,E){if(x==null){if(E!=null){if(S!=null)throw Error(r(92));if(te(E)){if(1<E.length)throw Error(r(93));E=E[0]}S=E}S==null&&(S=""),x=S}S=vn(x),h.defaultValue=S,E=h.textContent,E===S&&E!==""&&E!==null&&(h.value=E),rn(h)}function Bi(h,x){if(x){var S=h.firstChild;if(S&&S===h.lastChild&&S.nodeType===3){S.nodeValue=x;return}}h.textContent=x}var Hi=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 Ci(h,x,S){var E=x.indexOf("--")===0;S==null||typeof S=="boolean"||S===""?E?h.setProperty(x,""):x==="float"?h.cssFloat="":h[x]="":E?h.setProperty(x,S):typeof S!="number"||S===0||Hi.has(x)?x==="float"?h.cssFloat=S:h[x]=(""+S).trim():h[x]=S+"px"}function Hc(h,x,S){if(x!=null&&typeof x!="object")throw Error(r(62));if(h=h.style,S!=null){for(var E in S)!S.hasOwnProperty(E)||x!=null&&x.hasOwnProperty(E)||(E.indexOf("--")===0?h.setProperty(E,""):E==="float"?h.cssFloat="":h[E]="");for(var H in x)E=x[H],x.hasOwnProperty(H)&&S[H]!==E&&Ci(h,H,E)}else for(var Z in x)x.hasOwnProperty(Z)&&Ci(h,Z,x[Z])}function pa(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 jt=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"]]),Wn=/^[\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 En(h){return Wn.test(""+h)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":h}function Vt(){}var sc=null;function mm(h){return h=h.target||h.srcElement||window,h.correspondingUseElement&&(h=h.correspondingUseElement),h.nodeType===3?h.parentNode:h}var hs=null,qc=null;function Lo(h){var x=Ce(h);if(x&&(h=x.stateNode)){var S=h[Mt]||null;e:switch(h=x.stateNode,x.type){case"input":if(mi(h,S.value,S.defaultValue,S.defaultValue,S.checked,S.defaultChecked,S.type,S.name),x=S.name,S.type==="radio"&&x!=null){for(S=h;S.parentNode;)S=S.parentNode;for(S=S.querySelectorAll('input[name="'+On(""+x)+'"][type="radio"]'),x=0;x<S.length;x++){var E=S[x];if(E!==h&&E.form===h.form){var H=E[Mt]||null;if(!H)throw Error(r(90));mi(E,H.value,H.defaultValue,H.defaultValue,H.checked,H.defaultChecked,H.type,H.name)}}for(x=0;x<S.length;x++)E=S[x],E.form===h.form&&bn(E)}break e;case"textarea":jr(h,S.value,S.defaultValue);break e;case"select":x=S.value,x!=null&&ra(h,!!S.multiple,x,!1)}}}var $c=!1;function Is(h,x,S){if($c)return h(x,S);$c=!0;try{var E=h(x);return E}finally{if($c=!1,(hs!==null||qc!==null)&&(n_(),hs&&(x=hs,h=qc,qc=hs=null,Lo(x),h)))for(x=0;x<h.length;x++)Lo(h[x])}}function ps(h,x){var S=h.stateNode;if(S===null)return null;var E=S[Mt]||null;if(E===null)return null;S=E[x];e:switch(x){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(E=!E.disabled)||(h=h.type,E=!(h==="button"||h==="input"||h==="select"||h==="textarea")),h=!E;break e;default:h=!1}if(h)return null;if(S&&typeof S!="function")throw Error(r(231,x,typeof S));return S}var qi=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Id=!1;if(qi)try{var Pi={};Object.defineProperty(Pi,"passive",{get:function(){Id=!0}}),window.addEventListener("test",Pi,Pi),window.removeEventListener("test",Pi,Pi)}catch{Id=!1}var lo=null,hm=null,zs=null;function pm(){if(zs)return zs;var h,x=hm,S=x.length,E,H="value"in lo?lo.value:lo.textContent,Z=H.length;for(h=0;h<S&&x[h]===H[h];h++);var ke=S-h;for(E=1;E<=ke&&x[S-E]===H[Z-E];E++);return zs=H.slice(h,1<E?1-E:void 0)}function $i(h){var x=h.keyCode;return"charCode"in h?(h=h.charCode,h===0&&x===13&&(h=13)):h=x,h===10&&(h=13),32<=h||h===13?h:0}function Oo(){return!0}function oc(){return!1}function ja(h){function x(S,E,H,Z,ke){this._reactName=S,this._targetInst=H,this.type=E,this.nativeEvent=Z,this.target=ke,this.currentTarget=null;for(var Be in h)h.hasOwnProperty(Be)&&(S=h[Be],this[Be]=S?S(Z):Z[Be]);return this.isDefaultPrevented=(Z.defaultPrevented!=null?Z.defaultPrevented:Z.returnValue===!1)?Oo:oc,this.isPropagationStopped=oc,this}return m(x.prototype,{preventDefault:function(){this.defaultPrevented=!0;var S=this.nativeEvent;S&&(S.preventDefault?S.preventDefault():typeof S.returnValue!="unknown"&&(S.returnValue=!1),this.isDefaultPrevented=Oo)},stopPropagation:function(){var S=this.nativeEvent;S&&(S.stopPropagation?S.stopPropagation():typeof S.cancelBubble!="unknown"&&(S.cancelBubble=!0),this.isPropagationStopped=Oo)},persist:function(){},isPersistent:Oo}),x}var Us={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(h){return h.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},fs=ja(Us),Io=m({},Us,{view:0,detail:0}),up=ja(Io),zd,fm,cn,gs=m({},Io,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:fn,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!==cn&&(cn&&h.type==="mousemove"?(zd=h.screenX-cn.screenX,fm=h.screenY-cn.screenY):fm=zd=0,cn=h),zd)},movementY:function(h){return"movementY"in h?h.movementY:fm}}),ul=ja(gs),gg=m({},gs,{dataTransfer:0}),mp=ja(gg),bg=m({},Io,{relatedTarget:0}),Vc=ja(bg),hp=m({},Us,{animationName:0,elapsedTime:0,pseudoElement:0}),_y=ja(hp),gm=m({},Us,{clipboardData:function(h){return"clipboardData"in h?h.clipboardData:window.clipboardData}}),pp=ja(gm),gt=m({},Us,{data:0}),ge=ja(gt),mt={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Je={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"},$t={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function tn(h){var x=this.nativeEvent;return x.getModifierState?x.getModifierState(h):(h=$t[h])?!!x[h]:!1}function fn(){return tn}var gr=m({},Io,{key:function(h){if(h.key){var x=mt[h.key]||h.key;if(x!=="Unidentified")return x}return h.type==="keypress"?(h=$i(h),h===13?"Enter":String.fromCharCode(h)):h.type==="keydown"||h.type==="keyup"?Je[h.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:fn,charCode:function(h){return h.type==="keypress"?$i(h):0},keyCode:function(h){return h.type==="keydown"||h.type==="keyup"?h.keyCode:0},which:function(h){return h.type==="keypress"?$i(h):h.type==="keydown"||h.type==="keyup"?h.keyCode:0}}),Kn=ja(gr),sn=m({},gs,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Mn=ja(sn),bs=m({},Io,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:fn}),xs=ja(bs),ml=m({},Us,{propertyName:0,elapsedTime:0,pseudoElement:0}),lc=ja(ml),hl=m({},gs,{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}),_a=ja(hl),Vi=m({},Us,{newState:0,oldState:0}),cc=ja(Vi),ys=[9,13,27,32],Bs=qi&&"CompositionEvent"in window,co=null;qi&&"documentMode"in document&&(co=document.documentMode);var la=qi&&"TextEvent"in window&&!co,uo=qi&&(!Bs||co&&8<co&&11>=co),xg=" ",aa=!1;function Gc(h,x){switch(h){case"keyup":return ys.indexOf(x.keyCode)!==-1;case"keydown":return x.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function bm(h){return h=h.detail,typeof h=="object"&&"data"in h?h.data:null}var Cn=!1;function Xz(h,x){switch(h){case"compositionend":return bm(x);case"keypress":return x.which!==32?null:(aa=!0,xg);case"textInput":return h=x.data,h===xg&&aa?null:h;default:return null}}function vS(h,x){if(Cn)return h==="compositionend"||!Bs&&Gc(h,x)?(h=pm(),zs=hm=lo=null,Cn=!1,h):null;switch(h){case"paste":return null;case"keypress":if(!(x.ctrlKey||x.altKey||x.metaKey)||x.ctrlKey&&x.altKey){if(x.char&&1<x.char.length)return x.char;if(x.which)return String.fromCharCode(x.which)}return null;case"compositionend":return uo&&x.locale!=="ko"?null:x.data;default:return null}}var yg={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 ky(h){var x=h&&h.nodeName&&h.nodeName.toLowerCase();return x==="input"?!!yg[h.type]:x==="textarea"}function Ny(h,x,S,E){hs?qc?qc.push(E):qc=[E]:hs=E,x=c_(x,"onChange"),0<x.length&&(S=new fs("onChange","change",null,S,E),h.push({event:S,listeners:x}))}var fp=null,Cy=null;function zle(h){EB(h,0)}function wS(h){var x=We(h);if(bn(x))return h}function Qz(h,x){if(h==="change")return x}var Zz=!1;if(qi){var aA;if(qi){var iA="oninput"in document;if(!iA){var Jz=document.createElement("div");Jz.setAttribute("oninput","return;"),iA=typeof Jz.oninput=="function"}aA=iA}else aA=!1;Zz=aA&&(!document.documentMode||9<document.documentMode)}function e5(){fp&&(fp.detachEvent("onpropertychange",t5),Cy=fp=null)}function t5(h){if(h.propertyName==="value"&&wS(Cy)){var x=[];Ny(x,Cy,h,mm(h)),Is(zle,x)}}function Ule(h,x,S){h==="focusin"?(e5(),fp=x,Cy=S,fp.attachEvent("onpropertychange",t5)):h==="focusout"&&e5()}function Ble(h){if(h==="selectionchange"||h==="keyup"||h==="keydown")return wS(Cy)}function Hle(h,x){if(h==="click")return wS(x)}function qle(h,x){if(h==="input"||h==="change")return wS(x)}function $le(h,x){return h===x&&(h!==0||1/h===1/x)||h!==h&&x!==x}var zo=typeof Object.is=="function"?Object.is:$le;function Py(h,x){if(zo(h,x))return!0;if(typeof h!="object"||h===null||typeof x!="object"||x===null)return!1;var S=Object.keys(h),E=Object.keys(x);if(S.length!==E.length)return!1;for(E=0;E<S.length;E++){var H=S[E];if(!ie.call(x,H)||!zo(h[H],x[H]))return!1}return!0}function n5(h){for(;h&&h.firstChild;)h=h.firstChild;return h}function r5(h,x){var S=n5(h);h=0;for(var E;S;){if(S.nodeType===3){if(E=h+S.textContent.length,h<=x&&E>=x)return{node:S,offset:x-h};h=E}e:{for(;S;){if(S.nextSibling){S=S.nextSibling;break e}S=S.parentNode}S=void 0}S=n5(S)}}function a5(h,x){return h&&x?h===x?!0:h&&h.nodeType===3?!1:x&&x.nodeType===3?a5(h,x.parentNode):"contains"in h?h.contains(x):h.compareDocumentPosition?!!(h.compareDocumentPosition(x)&16):!1:!1}function i5(h){h=h!=null&&h.ownerDocument!=null&&h.ownerDocument.defaultView!=null?h.ownerDocument.defaultView:window;for(var x=Gn(h.document);x instanceof h.HTMLIFrameElement;){try{var S=typeof x.contentWindow.location.href=="string"}catch{S=!1}if(S)h=x.contentWindow;else break;x=Gn(h.document)}return x}function sA(h){var x=h&&h.nodeName&&h.nodeName.toLowerCase();return x&&(x==="input"&&(h.type==="text"||h.type==="search"||h.type==="tel"||h.type==="url"||h.type==="password")||x==="textarea"||h.contentEditable==="true")}var Vle=qi&&"documentMode"in document&&11>=document.documentMode,vg=null,oA=null,Ty=null,lA=!1;function s5(h,x,S){var E=S.window===S?S.document:S.nodeType===9?S:S.ownerDocument;lA||vg==null||vg!==Gn(E)||(E=vg,"selectionStart"in E&&sA(E)?E={start:E.selectionStart,end:E.selectionEnd}:(E=(E.ownerDocument&&E.ownerDocument.defaultView||window).getSelection(),E={anchorNode:E.anchorNode,anchorOffset:E.anchorOffset,focusNode:E.focusNode,focusOffset:E.focusOffset}),Ty&&Py(Ty,E)||(Ty=E,E=c_(oA,"onSelect"),0<E.length&&(x=new fs("onSelect","select",null,x,S),h.push({event:x,listeners:E}),x.target=vg)))}function gp(h,x){var S={};return S[h.toLowerCase()]=x.toLowerCase(),S["Webkit"+h]="webkit"+x,S["Moz"+h]="moz"+x,S}var wg={animationend:gp("Animation","AnimationEnd"),animationiteration:gp("Animation","AnimationIteration"),animationstart:gp("Animation","AnimationStart"),transitionrun:gp("Transition","TransitionRun"),transitionstart:gp("Transition","TransitionStart"),transitioncancel:gp("Transition","TransitionCancel"),transitionend:gp("Transition","TransitionEnd")},cA={},o5={};qi&&(o5=document.createElement("div").style,"AnimationEvent"in window||(delete wg.animationend.animation,delete wg.animationiteration.animation,delete wg.animationstart.animation),"TransitionEvent"in window||delete wg.transitionend.transition);function bp(h){if(cA[h])return cA[h];if(!wg[h])return h;var x=wg[h],S;for(S in x)if(x.hasOwnProperty(S)&&S in o5)return cA[h]=x[S];return h}var l5=bp("animationend"),c5=bp("animationiteration"),d5=bp("animationstart"),Gle=bp("transitionrun"),Wle=bp("transitionstart"),Kle=bp("transitioncancel"),u5=bp("transitionend"),m5=new Map,dA="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(" ");dA.push("scrollEnd");function dc(h,x){m5.set(h,x),bt(x,[h])}var SS=typeof reportError=="function"?reportError:function(h){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var x=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(x))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",h);return}console.error(h)},pl=[],Sg=0,uA=0;function _S(){for(var h=Sg,x=uA=Sg=0;x<h;){var S=pl[x];pl[x++]=null;var E=pl[x];pl[x++]=null;var H=pl[x];pl[x++]=null;var Z=pl[x];if(pl[x++]=null,E!==null&&H!==null){var ke=E.pending;ke===null?H.next=H:(H.next=ke.next,ke.next=H),E.pending=H}Z!==0&&h5(S,H,Z)}}function kS(h,x,S,E){pl[Sg++]=h,pl[Sg++]=x,pl[Sg++]=S,pl[Sg++]=E,uA|=E,h.lanes|=E,h=h.alternate,h!==null&&(h.lanes|=E)}function mA(h,x,S,E){return kS(h,x,S,E),NS(h)}function xp(h,x){return kS(h,null,null,x),NS(h)}function h5(h,x,S){h.lanes|=S;var E=h.alternate;E!==null&&(E.lanes|=S);for(var H=!1,Z=h.return;Z!==null;)Z.childLanes|=S,E=Z.alternate,E!==null&&(E.childLanes|=S),Z.tag===22&&(h=Z.stateNode,h===null||h._visibility&1||(H=!0)),h=Z,Z=Z.return;return h.tag===3?(Z=h.stateNode,H&&x!==null&&(H=31-qe(S),h=Z.hiddenUpdates,E=h[H],E===null?h[H]=[x]:E.push(x),x.lane=S|536870912),Z):null}function NS(h){if(50<Xy)throw Xy=0,wM=null,Error(r(185));for(var x=h.return;x!==null;)h=x,x=h.return;return h.tag===3?h.stateNode:null}var _g={};function Yle(h,x,S,E){this.tag=h,this.key=S,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=x,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=E,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Uo(h,x,S,E){return new Yle(h,x,S,E)}function hA(h){return h=h.prototype,!(!h||!h.isReactComponent)}function Ud(h,x){var S=h.alternate;return S===null?(S=Uo(h.tag,x,h.key,h.mode),S.elementType=h.elementType,S.type=h.type,S.stateNode=h.stateNode,S.alternate=h,h.alternate=S):(S.pendingProps=x,S.type=h.type,S.flags=0,S.subtreeFlags=0,S.deletions=null),S.flags=h.flags&65011712,S.childLanes=h.childLanes,S.lanes=h.lanes,S.child=h.child,S.memoizedProps=h.memoizedProps,S.memoizedState=h.memoizedState,S.updateQueue=h.updateQueue,x=h.dependencies,S.dependencies=x===null?null:{lanes:x.lanes,firstContext:x.firstContext},S.sibling=h.sibling,S.index=h.index,S.ref=h.ref,S.refCleanup=h.refCleanup,S}function p5(h,x){h.flags&=65011714;var S=h.alternate;return S===null?(h.childLanes=0,h.lanes=x,h.child=null,h.subtreeFlags=0,h.memoizedProps=null,h.memoizedState=null,h.updateQueue=null,h.dependencies=null,h.stateNode=null):(h.childLanes=S.childLanes,h.lanes=S.lanes,h.child=S.child,h.subtreeFlags=0,h.deletions=null,h.memoizedProps=S.memoizedProps,h.memoizedState=S.memoizedState,h.updateQueue=S.updateQueue,h.type=S.type,x=S.dependencies,h.dependencies=x===null?null:{lanes:x.lanes,firstContext:x.firstContext}),h}function CS(h,x,S,E,H,Z){var ke=0;if(E=h,typeof h=="function")hA(h)&&(ke=1);else if(typeof h=="string")ke=ede(h,S,be.current)?26:h==="html"||h==="head"||h==="body"?27:5;else e:switch(h){case C:return h=Uo(31,S,x,H),h.elementType=C,h.lanes=Z,h;case v:return yp(S.children,H,Z,x);case b:ke=8,H|=24;break;case g:return h=Uo(12,S,x,H|2),h.elementType=g,h.lanes=Z,h;case N:return h=Uo(13,S,x,H),h.elementType=N,h.lanes=Z,h;case M:return h=Uo(19,S,x,H),h.elementType=M,h.lanes=Z,h;default:if(typeof h=="object"&&h!==null)switch(h.$$typeof){case k:ke=10;break e;case _:ke=9;break e;case P:ke=11;break e;case A:ke=14;break e;case T:ke=16,E=null;break e}ke=29,S=Error(r(130,h===null?"null":typeof h,"")),E=null}return x=Uo(ke,S,x,H),x.elementType=h,x.type=E,x.lanes=Z,x}function yp(h,x,S,E){return h=Uo(7,h,E,x),h.lanes=S,h}function pA(h,x,S){return h=Uo(6,h,null,x),h.lanes=S,h}function f5(h){var x=Uo(18,null,null,0);return x.stateNode=h,x}function fA(h,x,S){return x=Uo(4,h.children!==null?h.children:[],h.key,x),x.lanes=S,x.stateNode={containerInfo:h.containerInfo,pendingChildren:null,implementation:h.implementation},x}var g5=new WeakMap;function fl(h,x){if(typeof h=="object"&&h!==null){var S=g5.get(h);return S!==void 0?S:(x={value:h,source:x,stack:J(x)},g5.set(h,x),x)}return{value:h,source:x,stack:J(x)}}var kg=[],Ng=0,PS=null,Ay=0,gl=[],bl=0,xm=null,Wc=1,Kc="";function Bd(h,x){kg[Ng++]=Ay,kg[Ng++]=PS,PS=h,Ay=x}function b5(h,x,S){gl[bl++]=Wc,gl[bl++]=Kc,gl[bl++]=xm,xm=h;var E=Wc;h=Kc;var H=32-qe(E)-1;E&=~(1<<H),S+=1;var Z=32-qe(x)+H;if(30<Z){var ke=H-H%5;Z=(E&(1<<ke)-1).toString(32),E>>=ke,H-=ke,Wc=1<<32-qe(x)+H|S<<H|E,Kc=Z+h}else Wc=1<<Z|S<<H|E,Kc=h}function gA(h){h.return!==null&&(Bd(h,1),b5(h,1,0))}function bA(h){for(;h===PS;)PS=kg[--Ng],kg[Ng]=null,Ay=kg[--Ng],kg[Ng]=null;for(;h===xm;)xm=gl[--bl],gl[bl]=null,Kc=gl[--bl],gl[bl]=null,Wc=gl[--bl],gl[bl]=null}function x5(h,x){gl[bl++]=Wc,gl[bl++]=Kc,gl[bl++]=xm,Wc=x.id,Kc=x.overflow,xm=h}var Gi=null,ca=null,br=!1,ym=null,xl=!1,xA=Error(r(519));function vm(h){var x=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw My(fl(x,h)),xA}function y5(h){var x=h.stateNode,S=h.type,E=h.memoizedProps;switch(x[ht]=h,x[Mt]=E,S){case"dialog":dr("cancel",x),dr("close",x);break;case"iframe":case"object":case"embed":dr("load",x);break;case"video":case"audio":for(S=0;S<Zy.length;S++)dr(Zy[S],x);break;case"source":dr("error",x);break;case"img":case"image":case"link":dr("error",x),dr("load",x);break;case"details":dr("toggle",x);break;case"input":dr("invalid",x),Rn(x,E.value,E.defaultValue,E.checked,E.defaultChecked,E.type,E.name,!0);break;case"select":dr("invalid",x);break;case"textarea":dr("invalid",x),In(x,E.value,E.defaultValue,E.children)}S=E.children,typeof S!="string"&&typeof S!="number"&&typeof S!="bigint"||x.textContent===""+S||E.suppressHydrationWarning===!0||LB(x.textContent,S)?(E.popover!=null&&(dr("beforetoggle",x),dr("toggle",x)),E.onScroll!=null&&dr("scroll",x),E.onScrollEnd!=null&&dr("scrollend",x),E.onClick!=null&&(x.onclick=Vt),x=!0):x=!1,x||vm(h,!0)}function v5(h){for(Gi=h.return;Gi;)switch(Gi.tag){case 5:case 31:case 13:xl=!1;return;case 27:case 3:xl=!0;return;default:Gi=Gi.return}}function Cg(h){if(h!==Gi)return!1;if(!br)return v5(h),br=!0,!1;var x=h.tag,S;if((S=x!==3&&x!==27)&&((S=x===5)&&(S=h.type,S=!(S!=="form"&&S!=="button")||LM(h.type,h.memoizedProps)),S=!S),S&&ca&&vm(h),v5(h),x===13){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));ca=VB(h)}else if(x===31){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));ca=VB(h)}else x===27?(x=ca,Fm(h.type)?(h=BM,BM=null,ca=h):ca=x):ca=Gi?vl(h.stateNode.nextSibling):null;return!0}function vp(){ca=Gi=null,br=!1}function yA(){var h=ym;return h!==null&&(fo===null?fo=h:fo.push.apply(fo,h),ym=null),h}function My(h){ym===null?ym=[h]:ym.push(h)}var vA=K(null),wp=null,Hd=null;function wm(h,x,S){oe(vA,x._currentValue),x._currentValue=S}function qd(h){h._currentValue=vA.current,ne(vA)}function wA(h,x,S){for(;h!==null;){var E=h.alternate;if((h.childLanes&x)!==x?(h.childLanes|=x,E!==null&&(E.childLanes|=x)):E!==null&&(E.childLanes&x)!==x&&(E.childLanes|=x),h===S)break;h=h.return}}function SA(h,x,S,E){var H=h.child;for(H!==null&&(H.return=h);H!==null;){var Z=H.dependencies;if(Z!==null){var ke=H.child;Z=Z.firstContext;e:for(;Z!==null;){var Be=Z;Z=H;for(var nt=0;nt<x.length;nt++)if(Be.context===x[nt]){Z.lanes|=S,Be=Z.alternate,Be!==null&&(Be.lanes|=S),wA(Z.return,S,h),E||(ke=null);break e}Z=Be.next}}else if(H.tag===18){if(ke=H.return,ke===null)throw Error(r(341));ke.lanes|=S,Z=ke.alternate,Z!==null&&(Z.lanes|=S),wA(ke,S,h),ke=null}else ke=H.child;if(ke!==null)ke.return=H;else for(ke=H;ke!==null;){if(ke===h){ke=null;break}if(H=ke.sibling,H!==null){H.return=ke.return,ke=H;break}ke=ke.return}H=ke}}function Pg(h,x,S,E){h=null;for(var H=x,Z=!1;H!==null;){if(!Z){if((H.flags&524288)!==0)Z=!0;else if((H.flags&262144)!==0)break}if(H.tag===10){var ke=H.alternate;if(ke===null)throw Error(r(387));if(ke=ke.memoizedProps,ke!==null){var Be=H.type;zo(H.pendingProps.value,ke.value)||(h!==null?h.push(Be):h=[Be])}}else if(H===Y.current){if(ke=H.alternate,ke===null)throw Error(r(387));ke.memoizedState.memoizedState!==H.memoizedState.memoizedState&&(h!==null?h.push(rv):h=[rv])}H=H.return}h!==null&&SA(x,h,S,E),x.flags|=262144}function TS(h){for(h=h.firstContext;h!==null;){if(!zo(h.context._currentValue,h.memoizedValue))return!0;h=h.next}return!1}function Sp(h){wp=h,Hd=null,h=h.dependencies,h!==null&&(h.firstContext=null)}function Wi(h){return w5(wp,h)}function AS(h,x){return wp===null&&Sp(h),w5(h,x)}function w5(h,x){var S=x._currentValue;if(x={context:x,memoizedValue:S,next:null},Hd===null){if(h===null)throw Error(r(308));Hd=x,h.dependencies={lanes:0,firstContext:x},h.flags|=524288}else Hd=Hd.next=x;return S}var Xle=typeof AbortController<"u"?AbortController:function(){var h=[],x=this.signal={aborted:!1,addEventListener:function(S,E){h.push(E)}};this.abort=function(){x.aborted=!0,h.forEach(function(S){return S()})}},Qle=t.unstable_scheduleCallback,Zle=t.unstable_NormalPriority,Ja={$$typeof:k,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function _A(){return{controller:new Xle,data:new Map,refCount:0}}function jy(h){h.refCount--,h.refCount===0&&Qle(Zle,function(){h.controller.abort()})}var Ey=null,kA=0,Tg=0,Ag=null;function Jle(h,x){if(Ey===null){var S=Ey=[];kA=0,Tg=PM(),Ag={status:"pending",value:void 0,then:function(E){S.push(E)}}}return kA++,x.then(S5,S5),x}function S5(){if(--kA===0&&Ey!==null){Ag!==null&&(Ag.status="fulfilled");var h=Ey;Ey=null,Tg=0,Ag=null;for(var x=0;x<h.length;x++)(0,h[x])()}}function ece(h,x){var S=[],E={status:"pending",value:null,reason:null,then:function(H){S.push(H)}};return h.then(function(){E.status="fulfilled",E.value=x;for(var H=0;H<S.length;H++)(0,S[H])(x)},function(H){for(E.status="rejected",E.reason=H,H=0;H<S.length;H++)(0,S[H])(void 0)}),E}var _5=ae.S;ae.S=function(h,x){sB=R(),typeof x=="object"&&x!==null&&typeof x.then=="function"&&Jle(h,x),_5!==null&&_5(h,x)};var _p=K(null);function NA(){var h=_p.current;return h!==null?h:Xr.pooledCache}function MS(h,x){x===null?oe(_p,_p.current):oe(_p,x.pool)}function k5(){var h=NA();return h===null?null:{parent:Ja._currentValue,pool:h}}var Mg=Error(r(460)),CA=Error(r(474)),jS=Error(r(542)),ES={then:function(){}};function N5(h){return h=h.status,h==="fulfilled"||h==="rejected"}function C5(h,x,S){switch(S=h[S],S===void 0?h.push(x):S!==x&&(x.then(Vt,Vt),x=S),x.status){case"fulfilled":return x.value;case"rejected":throw h=x.reason,T5(h),h;default:if(typeof x.status=="string")x.then(Vt,Vt);else{if(h=Xr,h!==null&&100<h.shellSuspendCounter)throw Error(r(482));h=x,h.status="pending",h.then(function(E){if(x.status==="pending"){var H=x;H.status="fulfilled",H.value=E}},function(E){if(x.status==="pending"){var H=x;H.status="rejected",H.reason=E}})}switch(x.status){case"fulfilled":return x.value;case"rejected":throw h=x.reason,T5(h),h}throw Np=x,Mg}}function kp(h){try{var x=h._init;return x(h._payload)}catch(S){throw S!==null&&typeof S=="object"&&typeof S.then=="function"?(Np=S,Mg):S}}var Np=null;function P5(){if(Np===null)throw Error(r(459));var h=Np;return Np=null,h}function T5(h){if(h===Mg||h===jS)throw Error(r(483))}var jg=null,Dy=0;function DS(h){var x=Dy;return Dy+=1,jg===null&&(jg=[]),C5(jg,h,x)}function Fy(h,x){x=x.props.ref,h.ref=x!==void 0?x:null}function FS(h,x){throw x.$$typeof===p?Error(r(525)):(h=Object.prototype.toString.call(x),Error(r(31,h==="[object Object]"?"object with keys {"+Object.keys(x).join(", ")+"}":h)))}function A5(h){function x(ft,st){if(h){var _t=ft.deletions;_t===null?(ft.deletions=[st],ft.flags|=16):_t.push(st)}}function S(ft,st){if(!h)return null;for(;st!==null;)x(ft,st),st=st.sibling;return null}function E(ft){for(var st=new Map;ft!==null;)ft.key!==null?st.set(ft.key,ft):st.set(ft.index,ft),ft=ft.sibling;return st}function H(ft,st){return ft=Ud(ft,st),ft.index=0,ft.sibling=null,ft}function Z(ft,st,_t){return ft.index=_t,h?(_t=ft.alternate,_t!==null?(_t=_t.index,_t<st?(ft.flags|=67108866,st):_t):(ft.flags|=67108866,st)):(ft.flags|=1048576,st)}function ke(ft){return h&&ft.alternate===null&&(ft.flags|=67108866),ft}function Be(ft,st,_t,It){return st===null||st.tag!==6?(st=pA(_t,ft.mode,It),st.return=ft,st):(st=H(st,_t),st.return=ft,st)}function nt(ft,st,_t,It){var _n=_t.type;return _n===v?Ot(ft,st,_t.props.children,It,_t.key):st!==null&&(st.elementType===_n||typeof _n=="object"&&_n!==null&&_n.$$typeof===T&&kp(_n)===st.type)?(st=H(st,_t.props),Fy(st,_t),st.return=ft,st):(st=CS(_t.type,_t.key,_t.props,null,ft.mode,It),Fy(st,_t),st.return=ft,st)}function kt(ft,st,_t,It){return st===null||st.tag!==4||st.stateNode.containerInfo!==_t.containerInfo||st.stateNode.implementation!==_t.implementation?(st=fA(_t,ft.mode,It),st.return=ft,st):(st=H(st,_t.children||[]),st.return=ft,st)}function Ot(ft,st,_t,It,_n){return st===null||st.tag!==7?(st=yp(_t,ft.mode,It,_n),st.return=ft,st):(st=H(st,_t),st.return=ft,st)}function zt(ft,st,_t){if(typeof st=="string"&&st!==""||typeof st=="number"||typeof st=="bigint")return st=pA(""+st,ft.mode,_t),st.return=ft,st;if(typeof st=="object"&&st!==null){switch(st.$$typeof){case f:return _t=CS(st.type,st.key,st.props,null,ft.mode,_t),Fy(_t,st),_t.return=ft,_t;case y:return st=fA(st,ft.mode,_t),st.return=ft,st;case T:return st=kp(st),zt(ft,st,_t)}if(te(st)||I(st))return st=yp(st,ft.mode,_t,null),st.return=ft,st;if(typeof st.then=="function")return zt(ft,DS(st),_t);if(st.$$typeof===k)return zt(ft,AS(ft,st),_t);FS(ft,st)}return null}function Tt(ft,st,_t,It){var _n=st!==null?st.key:null;if(typeof _t=="string"&&_t!==""||typeof _t=="number"||typeof _t=="bigint")return _n!==null?null:Be(ft,st,""+_t,It);if(typeof _t=="object"&&_t!==null){switch(_t.$$typeof){case f:return _t.key===_n?nt(ft,st,_t,It):null;case y:return _t.key===_n?kt(ft,st,_t,It):null;case T:return _t=kp(_t),Tt(ft,st,_t,It)}if(te(_t)||I(_t))return _n!==null?null:Ot(ft,st,_t,It,null);if(typeof _t.then=="function")return Tt(ft,st,DS(_t),It);if(_t.$$typeof===k)return Tt(ft,st,AS(ft,_t),It);FS(ft,_t)}return null}function Et(ft,st,_t,It,_n){if(typeof It=="string"&&It!==""||typeof It=="number"||typeof It=="bigint")return ft=ft.get(_t)||null,Be(st,ft,""+It,_n);if(typeof It=="object"&&It!==null){switch(It.$$typeof){case f:return ft=ft.get(It.key===null?_t:It.key)||null,nt(st,ft,It,_n);case y:return ft=ft.get(It.key===null?_t:It.key)||null,kt(st,ft,It,_n);case T:return It=kp(It),Et(ft,st,_t,It,_n)}if(te(It)||I(It))return ft=ft.get(_t)||null,Ot(st,ft,It,_n,null);if(typeof It.then=="function")return Et(ft,st,_t,DS(It),_n);if(It.$$typeof===k)return Et(ft,st,_t,AS(st,It),_n);FS(st,It)}return null}function pn(ft,st,_t,It){for(var _n=null,kr=null,gn=st,Xn=st=0,pr=null;gn!==null&&Xn<_t.length;Xn++){gn.index>Xn?(pr=gn,gn=null):pr=gn.sibling;var Nr=Tt(ft,gn,_t[Xn],It);if(Nr===null){gn===null&&(gn=pr);break}h&&gn&&Nr.alternate===null&&x(ft,gn),st=Z(Nr,st,Xn),kr===null?_n=Nr:kr.sibling=Nr,kr=Nr,gn=pr}if(Xn===_t.length)return S(ft,gn),br&&Bd(ft,Xn),_n;if(gn===null){for(;Xn<_t.length;Xn++)gn=zt(ft,_t[Xn],It),gn!==null&&(st=Z(gn,st,Xn),kr===null?_n=gn:kr.sibling=gn,kr=gn);return br&&Bd(ft,Xn),_n}for(gn=E(gn);Xn<_t.length;Xn++)pr=Et(gn,ft,Xn,_t[Xn],It),pr!==null&&(h&&pr.alternate!==null&&gn.delete(pr.key===null?Xn:pr.key),st=Z(pr,st,Xn),kr===null?_n=pr:kr.sibling=pr,kr=pr);return h&&gn.forEach(function(zm){return x(ft,zm)}),br&&Bd(ft,Xn),_n}function jn(ft,st,_t,It){if(_t==null)throw Error(r(151));for(var _n=null,kr=null,gn=st,Xn=st=0,pr=null,Nr=_t.next();gn!==null&&!Nr.done;Xn++,Nr=_t.next()){gn.index>Xn?(pr=gn,gn=null):pr=gn.sibling;var zm=Tt(ft,gn,Nr.value,It);if(zm===null){gn===null&&(gn=pr);break}h&&gn&&zm.alternate===null&&x(ft,gn),st=Z(zm,st,Xn),kr===null?_n=zm:kr.sibling=zm,kr=zm,gn=pr}if(Nr.done)return S(ft,gn),br&&Bd(ft,Xn),_n;if(gn===null){for(;!Nr.done;Xn++,Nr=_t.next())Nr=zt(ft,Nr.value,It),Nr!==null&&(st=Z(Nr,st,Xn),kr===null?_n=Nr:kr.sibling=Nr,kr=Nr);return br&&Bd(ft,Xn),_n}for(gn=E(gn);!Nr.done;Xn++,Nr=_t.next())Nr=Et(gn,ft,Xn,Nr.value,It),Nr!==null&&(h&&Nr.alternate!==null&&gn.delete(Nr.key===null?Xn:Nr.key),st=Z(Nr,st,Xn),kr===null?_n=Nr:kr.sibling=Nr,kr=Nr);return h&&gn.forEach(function(ude){return x(ft,ude)}),br&&Bd(ft,Xn),_n}function Ur(ft,st,_t,It){if(typeof _t=="object"&&_t!==null&&_t.type===v&&_t.key===null&&(_t=_t.props.children),typeof _t=="object"&&_t!==null){switch(_t.$$typeof){case f:e:{for(var _n=_t.key;st!==null;){if(st.key===_n){if(_n=_t.type,_n===v){if(st.tag===7){S(ft,st.sibling),It=H(st,_t.props.children),It.return=ft,ft=It;break e}}else if(st.elementType===_n||typeof _n=="object"&&_n!==null&&_n.$$typeof===T&&kp(_n)===st.type){S(ft,st.sibling),It=H(st,_t.props),Fy(It,_t),It.return=ft,ft=It;break e}S(ft,st);break}else x(ft,st);st=st.sibling}_t.type===v?(It=yp(_t.props.children,ft.mode,It,_t.key),It.return=ft,ft=It):(It=CS(_t.type,_t.key,_t.props,null,ft.mode,It),Fy(It,_t),It.return=ft,ft=It)}return ke(ft);case y:e:{for(_n=_t.key;st!==null;){if(st.key===_n)if(st.tag===4&&st.stateNode.containerInfo===_t.containerInfo&&st.stateNode.implementation===_t.implementation){S(ft,st.sibling),It=H(st,_t.children||[]),It.return=ft,ft=It;break e}else{S(ft,st);break}else x(ft,st);st=st.sibling}It=fA(_t,ft.mode,It),It.return=ft,ft=It}return ke(ft);case T:return _t=kp(_t),Ur(ft,st,_t,It)}if(te(_t))return pn(ft,st,_t,It);if(I(_t)){if(_n=I(_t),typeof _n!="function")throw Error(r(150));return _t=_n.call(_t),jn(ft,st,_t,It)}if(typeof _t.then=="function")return Ur(ft,st,DS(_t),It);if(_t.$$typeof===k)return Ur(ft,st,AS(ft,_t),It);FS(ft,_t)}return typeof _t=="string"&&_t!==""||typeof _t=="number"||typeof _t=="bigint"?(_t=""+_t,st!==null&&st.tag===6?(S(ft,st.sibling),It=H(st,_t),It.return=ft,ft=It):(S(ft,st),It=pA(_t,ft.mode,It),It.return=ft,ft=It),ke(ft)):S(ft,st)}return function(ft,st,_t,It){try{Dy=0;var _n=Ur(ft,st,_t,It);return jg=null,_n}catch(gn){if(gn===Mg||gn===jS)throw gn;var kr=Uo(29,gn,null,ft.mode);return kr.lanes=It,kr.return=ft,kr}}}var Cp=A5(!0),M5=A5(!1),Sm=!1;function PA(h){h.updateQueue={baseState:h.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function TA(h,x){h=h.updateQueue,x.updateQueue===h&&(x.updateQueue={baseState:h.baseState,firstBaseUpdate:h.firstBaseUpdate,lastBaseUpdate:h.lastBaseUpdate,shared:h.shared,callbacks:null})}function _m(h){return{lane:h,tag:0,payload:null,callback:null,next:null}}function km(h,x,S){var E=h.updateQueue;if(E===null)return null;if(E=E.shared,(Ar&2)!==0){var H=E.pending;return H===null?x.next=x:(x.next=H.next,H.next=x),E.pending=x,x=NS(h),h5(h,null,S),x}return kS(h,E,x,S),NS(h)}function Ry(h,x,S){if(x=x.updateQueue,x!==null&&(x=x.shared,(S&4194048)!==0)){var E=x.lanes;E&=h.pendingLanes,S|=E,x.lanes=S,Xt(h,S)}}function AA(h,x){var S=h.updateQueue,E=h.alternate;if(E!==null&&(E=E.updateQueue,S===E)){var H=null,Z=null;if(S=S.firstBaseUpdate,S!==null){do{var ke={lane:S.lane,tag:S.tag,payload:S.payload,callback:null,next:null};Z===null?H=Z=ke:Z=Z.next=ke,S=S.next}while(S!==null);Z===null?H=Z=x:Z=Z.next=x}else H=Z=x;S={baseState:E.baseState,firstBaseUpdate:H,lastBaseUpdate:Z,shared:E.shared,callbacks:E.callbacks},h.updateQueue=S;return}h=S.lastBaseUpdate,h===null?S.firstBaseUpdate=x:h.next=x,S.lastBaseUpdate=x}var MA=!1;function Ly(){if(MA){var h=Ag;if(h!==null)throw h}}function Oy(h,x,S,E){MA=!1;var H=h.updateQueue;Sm=!1;var Z=H.firstBaseUpdate,ke=H.lastBaseUpdate,Be=H.shared.pending;if(Be!==null){H.shared.pending=null;var nt=Be,kt=nt.next;nt.next=null,ke===null?Z=kt:ke.next=kt,ke=nt;var Ot=h.alternate;Ot!==null&&(Ot=Ot.updateQueue,Be=Ot.lastBaseUpdate,Be!==ke&&(Be===null?Ot.firstBaseUpdate=kt:Be.next=kt,Ot.lastBaseUpdate=nt))}if(Z!==null){var zt=H.baseState;ke=0,Ot=kt=nt=null,Be=Z;do{var Tt=Be.lane&-536870913,Et=Tt!==Be.lane;if(Et?(hr&Tt)===Tt:(E&Tt)===Tt){Tt!==0&&Tt===Tg&&(MA=!0),Ot!==null&&(Ot=Ot.next={lane:0,tag:Be.tag,payload:Be.payload,callback:null,next:null});e:{var pn=h,jn=Be;Tt=x;var Ur=S;switch(jn.tag){case 1:if(pn=jn.payload,typeof pn=="function"){zt=pn.call(Ur,zt,Tt);break e}zt=pn;break e;case 3:pn.flags=pn.flags&-65537|128;case 0:if(pn=jn.payload,Tt=typeof pn=="function"?pn.call(Ur,zt,Tt):pn,Tt==null)break e;zt=m({},zt,Tt);break e;case 2:Sm=!0}}Tt=Be.callback,Tt!==null&&(h.flags|=64,Et&&(h.flags|=8192),Et=H.callbacks,Et===null?H.callbacks=[Tt]:Et.push(Tt))}else Et={lane:Tt,tag:Be.tag,payload:Be.payload,callback:Be.callback,next:null},Ot===null?(kt=Ot=Et,nt=zt):Ot=Ot.next=Et,ke|=Tt;if(Be=Be.next,Be===null){if(Be=H.shared.pending,Be===null)break;Et=Be,Be=Et.next,Et.next=null,H.lastBaseUpdate=Et,H.shared.pending=null}}while(!0);Ot===null&&(nt=zt),H.baseState=nt,H.firstBaseUpdate=kt,H.lastBaseUpdate=Ot,Z===null&&(H.shared.lanes=0),Am|=ke,h.lanes=ke,h.memoizedState=zt}}function j5(h,x){if(typeof h!="function")throw Error(r(191,h));h.call(x)}function E5(h,x){var S=h.callbacks;if(S!==null)for(h.callbacks=null,h=0;h<S.length;h++)j5(S[h],x)}var Eg=K(null),RS=K(0);function D5(h,x){h=Zd,oe(RS,h),oe(Eg,x),Zd=h|x.baseLanes}function jA(){oe(RS,Zd),oe(Eg,Eg.current)}function EA(){Zd=RS.current,ne(Eg),ne(RS)}var Bo=K(null),yl=null;function Nm(h){var x=h.alternate;oe(Ka,Ka.current&1),oe(Bo,h),yl===null&&(x===null||Eg.current!==null||x.memoizedState!==null)&&(yl=h)}function DA(h){oe(Ka,Ka.current),oe(Bo,h),yl===null&&(yl=h)}function F5(h){h.tag===22?(oe(Ka,Ka.current),oe(Bo,h),yl===null&&(yl=h)):Cm()}function Cm(){oe(Ka,Ka.current),oe(Bo,Bo.current)}function Ho(h){ne(Bo),yl===h&&(yl=null),ne(Ka)}var Ka=K(0);function LS(h){for(var x=h;x!==null;){if(x.tag===13){var S=x.memoizedState;if(S!==null&&(S=S.dehydrated,S===null||zM(S)||UM(S)))return x}else if(x.tag===19&&(x.memoizedProps.revealOrder==="forwards"||x.memoizedProps.revealOrder==="backwards"||x.memoizedProps.revealOrder==="unstable_legacy-backwards"||x.memoizedProps.revealOrder==="together")){if((x.flags&128)!==0)return x}else if(x.child!==null){x.child.return=x,x=x.child;continue}if(x===h)break;for(;x.sibling===null;){if(x.return===null||x.return===h)return null;x=x.return}x.sibling.return=x.return,x=x.sibling}return null}var $d=0,Yn=null,Ir=null,ei=null,OS=!1,Dg=!1,Pp=!1,IS=0,Iy=0,Fg=null,tce=0;function Ea(){throw Error(r(321))}function FA(h,x){if(x===null)return!1;for(var S=0;S<x.length&&S<h.length;S++)if(!zo(h[S],x[S]))return!1;return!0}function RA(h,x,S,E,H,Z){return $d=Z,Yn=x,x.memoizedState=null,x.updateQueue=null,x.lanes=0,ae.H=h===null||h.memoizedState===null?bU:XA,Pp=!1,Z=S(E,H),Pp=!1,Dg&&(Z=L5(x,S,E,H)),R5(h),Z}function R5(h){ae.H=By;var x=Ir!==null&&Ir.next!==null;if($d=0,ei=Ir=Yn=null,OS=!1,Iy=0,Fg=null,x)throw Error(r(300));h===null||ti||(h=h.dependencies,h!==null&&TS(h)&&(ti=!0))}function L5(h,x,S,E){Yn=h;var H=0;do{if(Dg&&(Fg=null),Iy=0,Dg=!1,25<=H)throw Error(r(301));if(H+=1,ei=Ir=null,h.updateQueue!=null){var Z=h.updateQueue;Z.lastEffect=null,Z.events=null,Z.stores=null,Z.memoCache!=null&&(Z.memoCache.index=0)}ae.H=xU,Z=x(S,E)}while(Dg);return Z}function nce(){var h=ae.H,x=h.useState()[0];return x=typeof x.then=="function"?zy(x):x,h=h.useState()[0],(Ir!==null?Ir.memoizedState:null)!==h&&(Yn.flags|=1024),x}function LA(){var h=IS!==0;return IS=0,h}function OA(h,x,S){x.updateQueue=h.updateQueue,x.flags&=-2053,h.lanes&=~S}function IA(h){if(OS){for(h=h.memoizedState;h!==null;){var x=h.queue;x!==null&&(x.pending=null),h=h.next}OS=!1}$d=0,ei=Ir=Yn=null,Dg=!1,Iy=IS=0,Fg=null}function Hs(){var h={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ei===null?Yn.memoizedState=ei=h:ei=ei.next=h,ei}function Ya(){if(Ir===null){var h=Yn.alternate;h=h!==null?h.memoizedState:null}else h=Ir.next;var x=ei===null?Yn.memoizedState:ei.next;if(x!==null)ei=x,Ir=h;else{if(h===null)throw Yn.alternate===null?Error(r(467)):Error(r(310));Ir=h,h={memoizedState:Ir.memoizedState,baseState:Ir.baseState,baseQueue:Ir.baseQueue,queue:Ir.queue,next:null},ei===null?Yn.memoizedState=ei=h:ei=ei.next=h}return ei}function zS(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function zy(h){var x=Iy;return Iy+=1,Fg===null&&(Fg=[]),h=C5(Fg,h,x),x=Yn,(ei===null?x.memoizedState:ei.next)===null&&(x=x.alternate,ae.H=x===null||x.memoizedState===null?bU:XA),h}function US(h){if(h!==null&&typeof h=="object"){if(typeof h.then=="function")return zy(h);if(h.$$typeof===k)return Wi(h)}throw Error(r(438,String(h)))}function zA(h){var x=null,S=Yn.updateQueue;if(S!==null&&(x=S.memoCache),x==null){var E=Yn.alternate;E!==null&&(E=E.updateQueue,E!==null&&(E=E.memoCache,E!=null&&(x={data:E.data.map(function(H){return H.slice()}),index:0})))}if(x==null&&(x={data:[],index:0}),S===null&&(S=zS(),Yn.updateQueue=S),S.memoCache=x,S=x.data[x.index],S===void 0)for(S=x.data[x.index]=Array(h),E=0;E<h;E++)S[E]=F;return x.index++,S}function Vd(h,x){return typeof x=="function"?x(h):x}function BS(h){var x=Ya();return UA(x,Ir,h)}function UA(h,x,S){var E=h.queue;if(E===null)throw Error(r(311));E.lastRenderedReducer=S;var H=h.baseQueue,Z=E.pending;if(Z!==null){if(H!==null){var ke=H.next;H.next=Z.next,Z.next=ke}x.baseQueue=H=Z,E.pending=null}if(Z=h.baseState,H===null)h.memoizedState=Z;else{x=H.next;var Be=ke=null,nt=null,kt=x,Ot=!1;do{var zt=kt.lane&-536870913;if(zt!==kt.lane?(hr&zt)===zt:($d&zt)===zt){var Tt=kt.revertLane;if(Tt===0)nt!==null&&(nt=nt.next={lane:0,revertLane:0,gesture:null,action:kt.action,hasEagerState:kt.hasEagerState,eagerState:kt.eagerState,next:null}),zt===Tg&&(Ot=!0);else if(($d&Tt)===Tt){kt=kt.next,Tt===Tg&&(Ot=!0);continue}else zt={lane:0,revertLane:kt.revertLane,gesture:null,action:kt.action,hasEagerState:kt.hasEagerState,eagerState:kt.eagerState,next:null},nt===null?(Be=nt=zt,ke=Z):nt=nt.next=zt,Yn.lanes|=Tt,Am|=Tt;zt=kt.action,Pp&&S(Z,zt),Z=kt.hasEagerState?kt.eagerState:S(Z,zt)}else Tt={lane:zt,revertLane:kt.revertLane,gesture:kt.gesture,action:kt.action,hasEagerState:kt.hasEagerState,eagerState:kt.eagerState,next:null},nt===null?(Be=nt=Tt,ke=Z):nt=nt.next=Tt,Yn.lanes|=zt,Am|=zt;kt=kt.next}while(kt!==null&&kt!==x);if(nt===null?ke=Z:nt.next=Be,!zo(Z,h.memoizedState)&&(ti=!0,Ot&&(S=Ag,S!==null)))throw S;h.memoizedState=Z,h.baseState=ke,h.baseQueue=nt,E.lastRenderedState=Z}return H===null&&(E.lanes=0),[h.memoizedState,E.dispatch]}function BA(h){var x=Ya(),S=x.queue;if(S===null)throw Error(r(311));S.lastRenderedReducer=h;var E=S.dispatch,H=S.pending,Z=x.memoizedState;if(H!==null){S.pending=null;var ke=H=H.next;do Z=h(Z,ke.action),ke=ke.next;while(ke!==H);zo(Z,x.memoizedState)||(ti=!0),x.memoizedState=Z,x.baseQueue===null&&(x.baseState=Z),S.lastRenderedState=Z}return[Z,E]}function O5(h,x,S){var E=Yn,H=Ya(),Z=br;if(Z){if(S===void 0)throw Error(r(407));S=S()}else S=x();var ke=!zo((Ir||H).memoizedState,S);if(ke&&(H.memoizedState=S,ti=!0),H=H.queue,$A(U5.bind(null,E,H,h),[h]),H.getSnapshot!==x||ke||ei!==null&&ei.memoizedState.tag&1){if(E.flags|=2048,Rg(9,{destroy:void 0},z5.bind(null,E,H,S,x),null),Xr===null)throw Error(r(349));Z||($d&127)!==0||I5(E,x,S)}return S}function I5(h,x,S){h.flags|=16384,h={getSnapshot:x,value:S},x=Yn.updateQueue,x===null?(x=zS(),Yn.updateQueue=x,x.stores=[h]):(S=x.stores,S===null?x.stores=[h]:S.push(h))}function z5(h,x,S,E){x.value=S,x.getSnapshot=E,B5(x)&&H5(h)}function U5(h,x,S){return S(function(){B5(x)&&H5(h)})}function B5(h){var x=h.getSnapshot;h=h.value;try{var S=x();return!zo(h,S)}catch{return!0}}function H5(h){var x=xp(h,2);x!==null&&go(x,h,2)}function HA(h){var x=Hs();if(typeof h=="function"){var S=h;if(h=S(),Pp){je(!0);try{S()}finally{je(!1)}}}return x.memoizedState=x.baseState=h,x.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vd,lastRenderedState:h},x}function q5(h,x,S,E){return h.baseState=S,UA(h,Ir,typeof E=="function"?E:Vd)}function rce(h,x,S,E,H){if($S(h))throw Error(r(485));if(h=x.action,h!==null){var Z={payload:H,action:h,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(ke){Z.listeners.push(ke)}};ae.T!==null?S(!0):Z.isTransition=!1,E(Z),S=x.pending,S===null?(Z.next=x.pending=Z,$5(x,Z)):(Z.next=S.next,x.pending=S.next=Z)}}function $5(h,x){var S=x.action,E=x.payload,H=h.state;if(x.isTransition){var Z=ae.T,ke={};ae.T=ke;try{var Be=S(H,E),nt=ae.S;nt!==null&&nt(ke,Be),V5(h,x,Be)}catch(kt){qA(h,x,kt)}finally{Z!==null&&ke.types!==null&&(Z.types=ke.types),ae.T=Z}}else try{Z=S(H,E),V5(h,x,Z)}catch(kt){qA(h,x,kt)}}function V5(h,x,S){S!==null&&typeof S=="object"&&typeof S.then=="function"?S.then(function(E){G5(h,x,E)},function(E){return qA(h,x,E)}):G5(h,x,S)}function G5(h,x,S){x.status="fulfilled",x.value=S,W5(x),h.state=S,x=h.pending,x!==null&&(S=x.next,S===x?h.pending=null:(S=S.next,x.next=S,$5(h,S)))}function qA(h,x,S){var E=h.pending;if(h.pending=null,E!==null){E=E.next;do x.status="rejected",x.reason=S,W5(x),x=x.next;while(x!==E)}h.action=null}function W5(h){h=h.listeners;for(var x=0;x<h.length;x++)(0,h[x])()}function K5(h,x){return x}function Y5(h,x){if(br){var S=Xr.formState;if(S!==null){e:{var E=Yn;if(br){if(ca){t:{for(var H=ca,Z=xl;H.nodeType!==8;){if(!Z){H=null;break t}if(H=vl(H.nextSibling),H===null){H=null;break t}}Z=H.data,H=Z==="F!"||Z==="F"?H:null}if(H){ca=vl(H.nextSibling),E=H.data==="F!";break e}}vm(E)}E=!1}E&&(x=S[0])}}return S=Hs(),S.memoizedState=S.baseState=x,E={pending:null,lanes:0,dispatch:null,lastRenderedReducer:K5,lastRenderedState:x},S.queue=E,S=pU.bind(null,Yn,E),E.dispatch=S,E=HA(!1),Z=YA.bind(null,Yn,!1,E.queue),E=Hs(),H={state:x,dispatch:null,action:h,pending:null},E.queue=H,S=rce.bind(null,Yn,H,Z,S),H.dispatch=S,E.memoizedState=h,[x,S,!1]}function X5(h){var x=Ya();return Q5(x,Ir,h)}function Q5(h,x,S){if(x=UA(h,x,K5)[0],h=BS(Vd)[0],typeof x=="object"&&x!==null&&typeof x.then=="function")try{var E=zy(x)}catch(ke){throw ke===Mg?jS:ke}else E=x;x=Ya();var H=x.queue,Z=H.dispatch;return S!==x.memoizedState&&(Yn.flags|=2048,Rg(9,{destroy:void 0},ace.bind(null,H,S),null)),[E,Z,h]}function ace(h,x){h.action=x}function Z5(h){var x=Ya(),S=Ir;if(S!==null)return Q5(x,S,h);Ya(),x=x.memoizedState,S=Ya();var E=S.queue.dispatch;return S.memoizedState=h,[x,E,!1]}function Rg(h,x,S,E){return h={tag:h,create:S,deps:E,inst:x,next:null},x=Yn.updateQueue,x===null&&(x=zS(),Yn.updateQueue=x),S=x.lastEffect,S===null?x.lastEffect=h.next=h:(E=S.next,S.next=h,h.next=E,x.lastEffect=h),h}function J5(){return Ya().memoizedState}function HS(h,x,S,E){var H=Hs();Yn.flags|=h,H.memoizedState=Rg(1|x,{destroy:void 0},S,E===void 0?null:E)}function qS(h,x,S,E){var H=Ya();E=E===void 0?null:E;var Z=H.memoizedState.inst;Ir!==null&&E!==null&&FA(E,Ir.memoizedState.deps)?H.memoizedState=Rg(x,Z,S,E):(Yn.flags|=h,H.memoizedState=Rg(1|x,Z,S,E))}function eU(h,x){HS(8390656,8,h,x)}function $A(h,x){qS(2048,8,h,x)}function ice(h){Yn.flags|=4;var x=Yn.updateQueue;if(x===null)x=zS(),Yn.updateQueue=x,x.events=[h];else{var S=x.events;S===null?x.events=[h]:S.push(h)}}function tU(h){var x=Ya().memoizedState;return ice({ref:x,nextImpl:h}),function(){if((Ar&2)!==0)throw Error(r(440));return x.impl.apply(void 0,arguments)}}function nU(h,x){return qS(4,2,h,x)}function rU(h,x){return qS(4,4,h,x)}function aU(h,x){if(typeof x=="function"){h=h();var S=x(h);return function(){typeof S=="function"?S():x(null)}}if(x!=null)return h=h(),x.current=h,function(){x.current=null}}function iU(h,x,S){S=S!=null?S.concat([h]):null,qS(4,4,aU.bind(null,x,h),S)}function VA(){}function sU(h,x){var S=Ya();x=x===void 0?null:x;var E=S.memoizedState;return x!==null&&FA(x,E[1])?E[0]:(S.memoizedState=[h,x],h)}function oU(h,x){var S=Ya();x=x===void 0?null:x;var E=S.memoizedState;if(x!==null&&FA(x,E[1]))return E[0];if(E=h(),Pp){je(!0);try{h()}finally{je(!1)}}return S.memoizedState=[E,x],E}function GA(h,x,S){return S===void 0||($d&1073741824)!==0&&(hr&261930)===0?h.memoizedState=x:(h.memoizedState=S,h=lB(),Yn.lanes|=h,Am|=h,S)}function lU(h,x,S,E){return zo(S,x)?S:Eg.current!==null?(h=GA(h,S,E),zo(h,x)||(ti=!0),h):($d&42)===0||($d&1073741824)!==0&&(hr&261930)===0?(ti=!0,h.memoizedState=S):(h=lB(),Yn.lanes|=h,Am|=h,x)}function cU(h,x,S,E,H){var Z=ee.p;ee.p=Z!==0&&8>Z?Z:8;var ke=ae.T,Be={};ae.T=Be,YA(h,!1,x,S);try{var nt=H(),kt=ae.S;if(kt!==null&&kt(Be,nt),nt!==null&&typeof nt=="object"&&typeof nt.then=="function"){var Ot=ece(nt,E);Uy(h,x,Ot,Vo(h))}else Uy(h,x,E,Vo(h))}catch(zt){Uy(h,x,{then:function(){},status:"rejected",reason:zt},Vo())}finally{ee.p=Z,ke!==null&&Be.types!==null&&(ke.types=Be.types),ae.T=ke}}function sce(){}function WA(h,x,S,E){if(h.tag!==5)throw Error(r(476));var H=dU(h).queue;cU(h,H,x,me,S===null?sce:function(){return uU(h),S(E)})}function dU(h){var x=h.memoizedState;if(x!==null)return x;x={memoizedState:me,baseState:me,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vd,lastRenderedState:me},next:null};var S={};return x.next={memoizedState:S,baseState:S,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vd,lastRenderedState:S},next:null},h.memoizedState=x,h=h.alternate,h!==null&&(h.memoizedState=x),x}function uU(h){var x=dU(h);x.next===null&&(x=h.alternate.memoizedState),Uy(h,x.next.queue,{},Vo())}function KA(){return Wi(rv)}function mU(){return Ya().memoizedState}function hU(){return Ya().memoizedState}function oce(h){for(var x=h.return;x!==null;){switch(x.tag){case 24:case 3:var S=Vo();h=_m(S);var E=km(x,h,S);E!==null&&(go(E,x,S),Ry(E,x,S)),x={cache:_A()},h.payload=x;return}x=x.return}}function lce(h,x,S){var E=Vo();S={lane:E,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null},$S(h)?fU(x,S):(S=mA(h,x,S,E),S!==null&&(go(S,h,E),gU(S,x,E)))}function pU(h,x,S){var E=Vo();Uy(h,x,S,E)}function Uy(h,x,S,E){var H={lane:E,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null};if($S(h))fU(x,H);else{var Z=h.alternate;if(h.lanes===0&&(Z===null||Z.lanes===0)&&(Z=x.lastRenderedReducer,Z!==null))try{var ke=x.lastRenderedState,Be=Z(ke,S);if(H.hasEagerState=!0,H.eagerState=Be,zo(Be,ke))return kS(h,x,H,0),Xr===null&&_S(),!1}catch{}if(S=mA(h,x,H,E),S!==null)return go(S,h,E),gU(S,x,E),!0}return!1}function YA(h,x,S,E){if(E={lane:2,revertLane:PM(),gesture:null,action:E,hasEagerState:!1,eagerState:null,next:null},$S(h)){if(x)throw Error(r(479))}else x=mA(h,S,E,2),x!==null&&go(x,h,2)}function $S(h){var x=h.alternate;return h===Yn||x!==null&&x===Yn}function fU(h,x){Dg=OS=!0;var S=h.pending;S===null?x.next=x:(x.next=S.next,S.next=x),h.pending=x}function gU(h,x,S){if((S&4194048)!==0){var E=x.lanes;E&=h.pendingLanes,S|=E,x.lanes=S,Xt(h,S)}}var By={readContext:Wi,use:US,useCallback:Ea,useContext:Ea,useEffect:Ea,useImperativeHandle:Ea,useLayoutEffect:Ea,useInsertionEffect:Ea,useMemo:Ea,useReducer:Ea,useRef:Ea,useState:Ea,useDebugValue:Ea,useDeferredValue:Ea,useTransition:Ea,useSyncExternalStore:Ea,useId:Ea,useHostTransitionStatus:Ea,useFormState:Ea,useActionState:Ea,useOptimistic:Ea,useMemoCache:Ea,useCacheRefresh:Ea};By.useEffectEvent=Ea;var bU={readContext:Wi,use:US,useCallback:function(h,x){return Hs().memoizedState=[h,x===void 0?null:x],h},useContext:Wi,useEffect:eU,useImperativeHandle:function(h,x,S){S=S!=null?S.concat([h]):null,HS(4194308,4,aU.bind(null,x,h),S)},useLayoutEffect:function(h,x){return HS(4194308,4,h,x)},useInsertionEffect:function(h,x){HS(4,2,h,x)},useMemo:function(h,x){var S=Hs();x=x===void 0?null:x;var E=h();if(Pp){je(!0);try{h()}finally{je(!1)}}return S.memoizedState=[E,x],E},useReducer:function(h,x,S){var E=Hs();if(S!==void 0){var H=S(x);if(Pp){je(!0);try{S(x)}finally{je(!1)}}}else H=x;return E.memoizedState=E.baseState=H,h={pending:null,lanes:0,dispatch:null,lastRenderedReducer:h,lastRenderedState:H},E.queue=h,h=h.dispatch=lce.bind(null,Yn,h),[E.memoizedState,h]},useRef:function(h){var x=Hs();return h={current:h},x.memoizedState=h},useState:function(h){h=HA(h);var x=h.queue,S=pU.bind(null,Yn,x);return x.dispatch=S,[h.memoizedState,S]},useDebugValue:VA,useDeferredValue:function(h,x){var S=Hs();return GA(S,h,x)},useTransition:function(){var h=HA(!1);return h=cU.bind(null,Yn,h.queue,!0,!1),Hs().memoizedState=h,[!1,h]},useSyncExternalStore:function(h,x,S){var E=Yn,H=Hs();if(br){if(S===void 0)throw Error(r(407));S=S()}else{if(S=x(),Xr===null)throw Error(r(349));(hr&127)!==0||I5(E,x,S)}H.memoizedState=S;var Z={value:S,getSnapshot:x};return H.queue=Z,eU(U5.bind(null,E,Z,h),[h]),E.flags|=2048,Rg(9,{destroy:void 0},z5.bind(null,E,Z,S,x),null),S},useId:function(){var h=Hs(),x=Xr.identifierPrefix;if(br){var S=Kc,E=Wc;S=(E&~(1<<32-qe(E)-1)).toString(32)+S,x="_"+x+"R_"+S,S=IS++,0<S&&(x+="H"+S.toString(32)),x+="_"}else S=tce++,x="_"+x+"r_"+S.toString(32)+"_";return h.memoizedState=x},useHostTransitionStatus:KA,useFormState:Y5,useActionState:Y5,useOptimistic:function(h){var x=Hs();x.memoizedState=x.baseState=h;var S={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return x.queue=S,x=YA.bind(null,Yn,!0,S),S.dispatch=x,[h,x]},useMemoCache:zA,useCacheRefresh:function(){return Hs().memoizedState=oce.bind(null,Yn)},useEffectEvent:function(h){var x=Hs(),S={impl:h};return x.memoizedState=S,function(){if((Ar&2)!==0)throw Error(r(440));return S.impl.apply(void 0,arguments)}}},XA={readContext:Wi,use:US,useCallback:sU,useContext:Wi,useEffect:$A,useImperativeHandle:iU,useInsertionEffect:nU,useLayoutEffect:rU,useMemo:oU,useReducer:BS,useRef:J5,useState:function(){return BS(Vd)},useDebugValue:VA,useDeferredValue:function(h,x){var S=Ya();return lU(S,Ir.memoizedState,h,x)},useTransition:function(){var h=BS(Vd)[0],x=Ya().memoizedState;return[typeof h=="boolean"?h:zy(h),x]},useSyncExternalStore:O5,useId:mU,useHostTransitionStatus:KA,useFormState:X5,useActionState:X5,useOptimistic:function(h,x){var S=Ya();return q5(S,Ir,h,x)},useMemoCache:zA,useCacheRefresh:hU};XA.useEffectEvent=tU;var xU={readContext:Wi,use:US,useCallback:sU,useContext:Wi,useEffect:$A,useImperativeHandle:iU,useInsertionEffect:nU,useLayoutEffect:rU,useMemo:oU,useReducer:BA,useRef:J5,useState:function(){return BA(Vd)},useDebugValue:VA,useDeferredValue:function(h,x){var S=Ya();return Ir===null?GA(S,h,x):lU(S,Ir.memoizedState,h,x)},useTransition:function(){var h=BA(Vd)[0],x=Ya().memoizedState;return[typeof h=="boolean"?h:zy(h),x]},useSyncExternalStore:O5,useId:mU,useHostTransitionStatus:KA,useFormState:Z5,useActionState:Z5,useOptimistic:function(h,x){var S=Ya();return Ir!==null?q5(S,Ir,h,x):(S.baseState=h,[h,S.queue.dispatch])},useMemoCache:zA,useCacheRefresh:hU};xU.useEffectEvent=tU;function QA(h,x,S,E){x=h.memoizedState,S=S(E,x),S=S==null?x:m({},x,S),h.memoizedState=S,h.lanes===0&&(h.updateQueue.baseState=S)}var ZA={enqueueSetState:function(h,x,S){h=h._reactInternals;var E=Vo(),H=_m(E);H.payload=x,S!=null&&(H.callback=S),x=km(h,H,E),x!==null&&(go(x,h,E),Ry(x,h,E))},enqueueReplaceState:function(h,x,S){h=h._reactInternals;var E=Vo(),H=_m(E);H.tag=1,H.payload=x,S!=null&&(H.callback=S),x=km(h,H,E),x!==null&&(go(x,h,E),Ry(x,h,E))},enqueueForceUpdate:function(h,x){h=h._reactInternals;var S=Vo(),E=_m(S);E.tag=2,x!=null&&(E.callback=x),x=km(h,E,S),x!==null&&(go(x,h,S),Ry(x,h,S))}};function yU(h,x,S,E,H,Z,ke){return h=h.stateNode,typeof h.shouldComponentUpdate=="function"?h.shouldComponentUpdate(E,Z,ke):x.prototype&&x.prototype.isPureReactComponent?!Py(S,E)||!Py(H,Z):!0}function vU(h,x,S,E){h=x.state,typeof x.componentWillReceiveProps=="function"&&x.componentWillReceiveProps(S,E),typeof x.UNSAFE_componentWillReceiveProps=="function"&&x.UNSAFE_componentWillReceiveProps(S,E),x.state!==h&&ZA.enqueueReplaceState(x,x.state,null)}function Tp(h,x){var S=x;if("ref"in x){S={};for(var E in x)E!=="ref"&&(S[E]=x[E])}if(h=h.defaultProps){S===x&&(S=m({},S));for(var H in h)S[H]===void 0&&(S[H]=h[H])}return S}function wU(h){SS(h)}function SU(h){console.error(h)}function _U(h){SS(h)}function VS(h,x){try{var S=h.onUncaughtError;S(x.value,{componentStack:x.stack})}catch(E){setTimeout(function(){throw E})}}function kU(h,x,S){try{var E=h.onCaughtError;E(S.value,{componentStack:S.stack,errorBoundary:x.tag===1?x.stateNode:null})}catch(H){setTimeout(function(){throw H})}}function JA(h,x,S){return S=_m(S),S.tag=3,S.payload={element:null},S.callback=function(){VS(h,x)},S}function NU(h){return h=_m(h),h.tag=3,h}function CU(h,x,S,E){var H=S.type.getDerivedStateFromError;if(typeof H=="function"){var Z=E.value;h.payload=function(){return H(Z)},h.callback=function(){kU(x,S,E)}}var ke=S.stateNode;ke!==null&&typeof ke.componentDidCatch=="function"&&(h.callback=function(){kU(x,S,E),typeof H!="function"&&(Mm===null?Mm=new Set([this]):Mm.add(this));var Be=E.stack;this.componentDidCatch(E.value,{componentStack:Be!==null?Be:""})})}function cce(h,x,S,E,H){if(S.flags|=32768,E!==null&&typeof E=="object"&&typeof E.then=="function"){if(x=S.alternate,x!==null&&Pg(x,S,H,!0),S=Bo.current,S!==null){switch(S.tag){case 31:case 13:return yl===null?r_():S.alternate===null&&Da===0&&(Da=3),S.flags&=-257,S.flags|=65536,S.lanes=H,E===ES?S.flags|=16384:(x=S.updateQueue,x===null?S.updateQueue=new Set([E]):x.add(E),kM(h,E,H)),!1;case 22:return S.flags|=65536,E===ES?S.flags|=16384:(x=S.updateQueue,x===null?(x={transitions:null,markerInstances:null,retryQueue:new Set([E])},S.updateQueue=x):(S=x.retryQueue,S===null?x.retryQueue=new Set([E]):S.add(E)),kM(h,E,H)),!1}throw Error(r(435,S.tag))}return kM(h,E,H),r_(),!1}if(br)return x=Bo.current,x!==null?((x.flags&65536)===0&&(x.flags|=256),x.flags|=65536,x.lanes=H,E!==xA&&(h=Error(r(422),{cause:E}),My(fl(h,S)))):(E!==xA&&(x=Error(r(423),{cause:E}),My(fl(x,S))),h=h.current.alternate,h.flags|=65536,H&=-H,h.lanes|=H,E=fl(E,S),H=JA(h.stateNode,E,H),AA(h,H),Da!==4&&(Da=2)),!1;var Z=Error(r(520),{cause:E});if(Z=fl(Z,S),Yy===null?Yy=[Z]:Yy.push(Z),Da!==4&&(Da=2),x===null)return!0;E=fl(E,S),S=x;do{switch(S.tag){case 3:return S.flags|=65536,h=H&-H,S.lanes|=h,h=JA(S.stateNode,E,h),AA(S,h),!1;case 1:if(x=S.type,Z=S.stateNode,(S.flags&128)===0&&(typeof x.getDerivedStateFromError=="function"||Z!==null&&typeof Z.componentDidCatch=="function"&&(Mm===null||!Mm.has(Z))))return S.flags|=65536,H&=-H,S.lanes|=H,H=NU(H),CU(H,h,S,E),AA(S,H),!1}S=S.return}while(S!==null);return!1}var eM=Error(r(461)),ti=!1;function Ki(h,x,S,E){x.child=h===null?M5(x,null,S,E):Cp(x,h.child,S,E)}function PU(h,x,S,E,H){S=S.render;var Z=x.ref;if("ref"in E){var ke={};for(var Be in E)Be!=="ref"&&(ke[Be]=E[Be])}else ke=E;return Sp(x),E=RA(h,x,S,ke,Z,H),Be=LA(),h!==null&&!ti?(OA(h,x,H),Gd(h,x,H)):(br&&Be&&gA(x),x.flags|=1,Ki(h,x,E,H),x.child)}function TU(h,x,S,E,H){if(h===null){var Z=S.type;return typeof Z=="function"&&!hA(Z)&&Z.defaultProps===void 0&&S.compare===null?(x.tag=15,x.type=Z,AU(h,x,Z,E,H)):(h=CS(S.type,null,E,x,x.mode,H),h.ref=x.ref,h.return=x,x.child=h)}if(Z=h.child,!lM(h,H)){var ke=Z.memoizedProps;if(S=S.compare,S=S!==null?S:Py,S(ke,E)&&h.ref===x.ref)return Gd(h,x,H)}return x.flags|=1,h=Ud(Z,E),h.ref=x.ref,h.return=x,x.child=h}function AU(h,x,S,E,H){if(h!==null){var Z=h.memoizedProps;if(Py(Z,E)&&h.ref===x.ref)if(ti=!1,x.pendingProps=E=Z,lM(h,H))(h.flags&131072)!==0&&(ti=!0);else return x.lanes=h.lanes,Gd(h,x,H)}return tM(h,x,S,E,H)}function MU(h,x,S,E){var H=E.children,Z=h!==null?h.memoizedState:null;if(h===null&&x.stateNode===null&&(x.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),E.mode==="hidden"){if((x.flags&128)!==0){if(Z=Z!==null?Z.baseLanes|S:S,h!==null){for(E=x.child=h.child,H=0;E!==null;)H=H|E.lanes|E.childLanes,E=E.sibling;E=H&~Z}else E=0,x.child=null;return jU(h,x,Z,S,E)}if((S&536870912)!==0)x.memoizedState={baseLanes:0,cachePool:null},h!==null&&MS(x,Z!==null?Z.cachePool:null),Z!==null?D5(x,Z):jA(),F5(x);else return E=x.lanes=536870912,jU(h,x,Z!==null?Z.baseLanes|S:S,S,E)}else Z!==null?(MS(x,Z.cachePool),D5(x,Z),Cm(),x.memoizedState=null):(h!==null&&MS(x,null),jA(),Cm());return Ki(h,x,H,S),x.child}function Hy(h,x){return h!==null&&h.tag===22||x.stateNode!==null||(x.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),x.sibling}function jU(h,x,S,E,H){var Z=NA();return Z=Z===null?null:{parent:Ja._currentValue,pool:Z},x.memoizedState={baseLanes:S,cachePool:Z},h!==null&&MS(x,null),jA(),F5(x),h!==null&&Pg(h,x,E,!0),x.childLanes=H,null}function GS(h,x){return x=KS({mode:x.mode,children:x.children},h.mode),x.ref=h.ref,h.child=x,x.return=h,x}function EU(h,x,S){return Cp(x,h.child,null,S),h=GS(x,x.pendingProps),h.flags|=2,Ho(x),x.memoizedState=null,h}function dce(h,x,S){var E=x.pendingProps,H=(x.flags&128)!==0;if(x.flags&=-129,h===null){if(br){if(E.mode==="hidden")return h=GS(x,E),x.lanes=536870912,Hy(null,h);if(DA(x),(h=ca)?(h=$B(h,xl),h=h!==null&&h.data==="&"?h:null,h!==null&&(x.memoizedState={dehydrated:h,treeContext:xm!==null?{id:Wc,overflow:Kc}:null,retryLane:536870912,hydrationErrors:null},S=f5(h),S.return=x,x.child=S,Gi=x,ca=null)):h=null,h===null)throw vm(x);return x.lanes=536870912,null}return GS(x,E)}var Z=h.memoizedState;if(Z!==null){var ke=Z.dehydrated;if(DA(x),H)if(x.flags&256)x.flags&=-257,x=EU(h,x,S);else if(x.memoizedState!==null)x.child=h.child,x.flags|=128,x=null;else throw Error(r(558));else if(ti||Pg(h,x,S,!1),H=(S&h.childLanes)!==0,ti||H){if(E=Xr,E!==null&&(ke=Kt(E,S),ke!==0&&ke!==Z.retryLane))throw Z.retryLane=ke,xp(h,ke),go(E,h,ke),eM;r_(),x=EU(h,x,S)}else h=Z.treeContext,ca=vl(ke.nextSibling),Gi=x,br=!0,ym=null,xl=!1,h!==null&&x5(x,h),x=GS(x,E),x.flags|=4096;return x}return h=Ud(h.child,{mode:E.mode,children:E.children}),h.ref=x.ref,x.child=h,h.return=x,h}function WS(h,x){var S=x.ref;if(S===null)h!==null&&h.ref!==null&&(x.flags|=4194816);else{if(typeof S!="function"&&typeof S!="object")throw Error(r(284));(h===null||h.ref!==S)&&(x.flags|=4194816)}}function tM(h,x,S,E,H){return Sp(x),S=RA(h,x,S,E,void 0,H),E=LA(),h!==null&&!ti?(OA(h,x,H),Gd(h,x,H)):(br&&E&&gA(x),x.flags|=1,Ki(h,x,S,H),x.child)}function DU(h,x,S,E,H,Z){return Sp(x),x.updateQueue=null,S=L5(x,E,S,H),R5(h),E=LA(),h!==null&&!ti?(OA(h,x,Z),Gd(h,x,Z)):(br&&E&&gA(x),x.flags|=1,Ki(h,x,S,Z),x.child)}function FU(h,x,S,E,H){if(Sp(x),x.stateNode===null){var Z=_g,ke=S.contextType;typeof ke=="object"&&ke!==null&&(Z=Wi(ke)),Z=new S(E,Z),x.memoizedState=Z.state!==null&&Z.state!==void 0?Z.state:null,Z.updater=ZA,x.stateNode=Z,Z._reactInternals=x,Z=x.stateNode,Z.props=E,Z.state=x.memoizedState,Z.refs={},PA(x),ke=S.contextType,Z.context=typeof ke=="object"&&ke!==null?Wi(ke):_g,Z.state=x.memoizedState,ke=S.getDerivedStateFromProps,typeof ke=="function"&&(QA(x,S,ke,E),Z.state=x.memoizedState),typeof S.getDerivedStateFromProps=="function"||typeof Z.getSnapshotBeforeUpdate=="function"||typeof Z.UNSAFE_componentWillMount!="function"&&typeof Z.componentWillMount!="function"||(ke=Z.state,typeof Z.componentWillMount=="function"&&Z.componentWillMount(),typeof Z.UNSAFE_componentWillMount=="function"&&Z.UNSAFE_componentWillMount(),ke!==Z.state&&ZA.enqueueReplaceState(Z,Z.state,null),Oy(x,E,Z,H),Ly(),Z.state=x.memoizedState),typeof Z.componentDidMount=="function"&&(x.flags|=4194308),E=!0}else if(h===null){Z=x.stateNode;var Be=x.memoizedProps,nt=Tp(S,Be);Z.props=nt;var kt=Z.context,Ot=S.contextType;ke=_g,typeof Ot=="object"&&Ot!==null&&(ke=Wi(Ot));var zt=S.getDerivedStateFromProps;Ot=typeof zt=="function"||typeof Z.getSnapshotBeforeUpdate=="function",Be=x.pendingProps!==Be,Ot||typeof Z.UNSAFE_componentWillReceiveProps!="function"&&typeof Z.componentWillReceiveProps!="function"||(Be||kt!==ke)&&vU(x,Z,E,ke),Sm=!1;var Tt=x.memoizedState;Z.state=Tt,Oy(x,E,Z,H),Ly(),kt=x.memoizedState,Be||Tt!==kt||Sm?(typeof zt=="function"&&(QA(x,S,zt,E),kt=x.memoizedState),(nt=Sm||yU(x,S,nt,E,Tt,kt,ke))?(Ot||typeof Z.UNSAFE_componentWillMount!="function"&&typeof Z.componentWillMount!="function"||(typeof Z.componentWillMount=="function"&&Z.componentWillMount(),typeof Z.UNSAFE_componentWillMount=="function"&&Z.UNSAFE_componentWillMount()),typeof Z.componentDidMount=="function"&&(x.flags|=4194308)):(typeof Z.componentDidMount=="function"&&(x.flags|=4194308),x.memoizedProps=E,x.memoizedState=kt),Z.props=E,Z.state=kt,Z.context=ke,E=nt):(typeof Z.componentDidMount=="function"&&(x.flags|=4194308),E=!1)}else{Z=x.stateNode,TA(h,x),ke=x.memoizedProps,Ot=Tp(S,ke),Z.props=Ot,zt=x.pendingProps,Tt=Z.context,kt=S.contextType,nt=_g,typeof kt=="object"&&kt!==null&&(nt=Wi(kt)),Be=S.getDerivedStateFromProps,(kt=typeof Be=="function"||typeof Z.getSnapshotBeforeUpdate=="function")||typeof Z.UNSAFE_componentWillReceiveProps!="function"&&typeof Z.componentWillReceiveProps!="function"||(ke!==zt||Tt!==nt)&&vU(x,Z,E,nt),Sm=!1,Tt=x.memoizedState,Z.state=Tt,Oy(x,E,Z,H),Ly();var Et=x.memoizedState;ke!==zt||Tt!==Et||Sm||h!==null&&h.dependencies!==null&&TS(h.dependencies)?(typeof Be=="function"&&(QA(x,S,Be,E),Et=x.memoizedState),(Ot=Sm||yU(x,S,Ot,E,Tt,Et,nt)||h!==null&&h.dependencies!==null&&TS(h.dependencies))?(kt||typeof Z.UNSAFE_componentWillUpdate!="function"&&typeof Z.componentWillUpdate!="function"||(typeof Z.componentWillUpdate=="function"&&Z.componentWillUpdate(E,Et,nt),typeof Z.UNSAFE_componentWillUpdate=="function"&&Z.UNSAFE_componentWillUpdate(E,Et,nt)),typeof Z.componentDidUpdate=="function"&&(x.flags|=4),typeof Z.getSnapshotBeforeUpdate=="function"&&(x.flags|=1024)):(typeof Z.componentDidUpdate!="function"||ke===h.memoizedProps&&Tt===h.memoizedState||(x.flags|=4),typeof Z.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&Tt===h.memoizedState||(x.flags|=1024),x.memoizedProps=E,x.memoizedState=Et),Z.props=E,Z.state=Et,Z.context=nt,E=Ot):(typeof Z.componentDidUpdate!="function"||ke===h.memoizedProps&&Tt===h.memoizedState||(x.flags|=4),typeof Z.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&Tt===h.memoizedState||(x.flags|=1024),E=!1)}return Z=E,WS(h,x),E=(x.flags&128)!==0,Z||E?(Z=x.stateNode,S=E&&typeof S.getDerivedStateFromError!="function"?null:Z.render(),x.flags|=1,h!==null&&E?(x.child=Cp(x,h.child,null,H),x.child=Cp(x,null,S,H)):Ki(h,x,S,H),x.memoizedState=Z.state,h=x.child):h=Gd(h,x,H),h}function RU(h,x,S,E){return vp(),x.flags|=256,Ki(h,x,S,E),x.child}var nM={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function rM(h){return{baseLanes:h,cachePool:k5()}}function aM(h,x,S){return h=h!==null?h.childLanes&~S:0,x&&(h|=$o),h}function LU(h,x,S){var E=x.pendingProps,H=!1,Z=(x.flags&128)!==0,ke;if((ke=Z)||(ke=h!==null&&h.memoizedState===null?!1:(Ka.current&2)!==0),ke&&(H=!0,x.flags&=-129),ke=(x.flags&32)!==0,x.flags&=-33,h===null){if(br){if(H?Nm(x):Cm(),(h=ca)?(h=$B(h,xl),h=h!==null&&h.data!=="&"?h:null,h!==null&&(x.memoizedState={dehydrated:h,treeContext:xm!==null?{id:Wc,overflow:Kc}:null,retryLane:536870912,hydrationErrors:null},S=f5(h),S.return=x,x.child=S,Gi=x,ca=null)):h=null,h===null)throw vm(x);return UM(h)?x.lanes=32:x.lanes=536870912,null}var Be=E.children;return E=E.fallback,H?(Cm(),H=x.mode,Be=KS({mode:"hidden",children:Be},H),E=yp(E,H,S,null),Be.return=x,E.return=x,Be.sibling=E,x.child=Be,E=x.child,E.memoizedState=rM(S),E.childLanes=aM(h,ke,S),x.memoizedState=nM,Hy(null,E)):(Nm(x),iM(x,Be))}var nt=h.memoizedState;if(nt!==null&&(Be=nt.dehydrated,Be!==null)){if(Z)x.flags&256?(Nm(x),x.flags&=-257,x=sM(h,x,S)):x.memoizedState!==null?(Cm(),x.child=h.child,x.flags|=128,x=null):(Cm(),Be=E.fallback,H=x.mode,E=KS({mode:"visible",children:E.children},H),Be=yp(Be,H,S,null),Be.flags|=2,E.return=x,Be.return=x,E.sibling=Be,x.child=E,Cp(x,h.child,null,S),E=x.child,E.memoizedState=rM(S),E.childLanes=aM(h,ke,S),x.memoizedState=nM,x=Hy(null,E));else if(Nm(x),UM(Be)){if(ke=Be.nextSibling&&Be.nextSibling.dataset,ke)var kt=ke.dgst;ke=kt,E=Error(r(419)),E.stack="",E.digest=ke,My({value:E,source:null,stack:null}),x=sM(h,x,S)}else if(ti||Pg(h,x,S,!1),ke=(S&h.childLanes)!==0,ti||ke){if(ke=Xr,ke!==null&&(E=Kt(ke,S),E!==0&&E!==nt.retryLane))throw nt.retryLane=E,xp(h,E),go(ke,h,E),eM;zM(Be)||r_(),x=sM(h,x,S)}else zM(Be)?(x.flags|=192,x.child=h.child,x=null):(h=nt.treeContext,ca=vl(Be.nextSibling),Gi=x,br=!0,ym=null,xl=!1,h!==null&&x5(x,h),x=iM(x,E.children),x.flags|=4096);return x}return H?(Cm(),Be=E.fallback,H=x.mode,nt=h.child,kt=nt.sibling,E=Ud(nt,{mode:"hidden",children:E.children}),E.subtreeFlags=nt.subtreeFlags&65011712,kt!==null?Be=Ud(kt,Be):(Be=yp(Be,H,S,null),Be.flags|=2),Be.return=x,E.return=x,E.sibling=Be,x.child=E,Hy(null,E),E=x.child,Be=h.child.memoizedState,Be===null?Be=rM(S):(H=Be.cachePool,H!==null?(nt=Ja._currentValue,H=H.parent!==nt?{parent:nt,pool:nt}:H):H=k5(),Be={baseLanes:Be.baseLanes|S,cachePool:H}),E.memoizedState=Be,E.childLanes=aM(h,ke,S),x.memoizedState=nM,Hy(h.child,E)):(Nm(x),S=h.child,h=S.sibling,S=Ud(S,{mode:"visible",children:E.children}),S.return=x,S.sibling=null,h!==null&&(ke=x.deletions,ke===null?(x.deletions=[h],x.flags|=16):ke.push(h)),x.child=S,x.memoizedState=null,S)}function iM(h,x){return x=KS({mode:"visible",children:x},h.mode),x.return=h,h.child=x}function KS(h,x){return h=Uo(22,h,null,x),h.lanes=0,h}function sM(h,x,S){return Cp(x,h.child,null,S),h=iM(x,x.pendingProps.children),h.flags|=2,x.memoizedState=null,h}function OU(h,x,S){h.lanes|=x;var E=h.alternate;E!==null&&(E.lanes|=x),wA(h.return,x,S)}function oM(h,x,S,E,H,Z){var ke=h.memoizedState;ke===null?h.memoizedState={isBackwards:x,rendering:null,renderingStartTime:0,last:E,tail:S,tailMode:H,treeForkCount:Z}:(ke.isBackwards=x,ke.rendering=null,ke.renderingStartTime=0,ke.last=E,ke.tail=S,ke.tailMode=H,ke.treeForkCount=Z)}function IU(h,x,S){var E=x.pendingProps,H=E.revealOrder,Z=E.tail;E=E.children;var ke=Ka.current,Be=(ke&2)!==0;if(Be?(ke=ke&1|2,x.flags|=128):ke&=1,oe(Ka,ke),Ki(h,x,E,S),E=br?Ay:0,!Be&&h!==null&&(h.flags&128)!==0)e:for(h=x.child;h!==null;){if(h.tag===13)h.memoizedState!==null&&OU(h,S,x);else if(h.tag===19)OU(h,S,x);else if(h.child!==null){h.child.return=h,h=h.child;continue}if(h===x)break e;for(;h.sibling===null;){if(h.return===null||h.return===x)break e;h=h.return}h.sibling.return=h.return,h=h.sibling}switch(H){case"forwards":for(S=x.child,H=null;S!==null;)h=S.alternate,h!==null&&LS(h)===null&&(H=S),S=S.sibling;S=H,S===null?(H=x.child,x.child=null):(H=S.sibling,S.sibling=null),oM(x,!1,H,S,Z,E);break;case"backwards":case"unstable_legacy-backwards":for(S=null,H=x.child,x.child=null;H!==null;){if(h=H.alternate,h!==null&&LS(h)===null){x.child=H;break}h=H.sibling,H.sibling=S,S=H,H=h}oM(x,!0,S,null,Z,E);break;case"together":oM(x,!1,null,null,void 0,E);break;default:x.memoizedState=null}return x.child}function Gd(h,x,S){if(h!==null&&(x.dependencies=h.dependencies),Am|=x.lanes,(S&x.childLanes)===0)if(h!==null){if(Pg(h,x,S,!1),(S&x.childLanes)===0)return null}else return null;if(h!==null&&x.child!==h.child)throw Error(r(153));if(x.child!==null){for(h=x.child,S=Ud(h,h.pendingProps),x.child=S,S.return=x;h.sibling!==null;)h=h.sibling,S=S.sibling=Ud(h,h.pendingProps),S.return=x;S.sibling=null}return x.child}function lM(h,x){return(h.lanes&x)!==0?!0:(h=h.dependencies,!!(h!==null&&TS(h)))}function uce(h,x,S){switch(x.tag){case 3:D(x,x.stateNode.containerInfo),wm(x,Ja,h.memoizedState.cache),vp();break;case 27:case 5:z(x);break;case 4:D(x,x.stateNode.containerInfo);break;case 10:wm(x,x.type,x.memoizedProps.value);break;case 31:if(x.memoizedState!==null)return x.flags|=128,DA(x),null;break;case 13:var E=x.memoizedState;if(E!==null)return E.dehydrated!==null?(Nm(x),x.flags|=128,null):(S&x.child.childLanes)!==0?LU(h,x,S):(Nm(x),h=Gd(h,x,S),h!==null?h.sibling:null);Nm(x);break;case 19:var H=(h.flags&128)!==0;if(E=(S&x.childLanes)!==0,E||(Pg(h,x,S,!1),E=(S&x.childLanes)!==0),H){if(E)return IU(h,x,S);x.flags|=128}if(H=x.memoizedState,H!==null&&(H.rendering=null,H.tail=null,H.lastEffect=null),oe(Ka,Ka.current),E)break;return null;case 22:return x.lanes=0,MU(h,x,S,x.pendingProps);case 24:wm(x,Ja,h.memoizedState.cache)}return Gd(h,x,S)}function zU(h,x,S){if(h!==null)if(h.memoizedProps!==x.pendingProps)ti=!0;else{if(!lM(h,S)&&(x.flags&128)===0)return ti=!1,uce(h,x,S);ti=(h.flags&131072)!==0}else ti=!1,br&&(x.flags&1048576)!==0&&b5(x,Ay,x.index);switch(x.lanes=0,x.tag){case 16:e:{var E=x.pendingProps;if(h=kp(x.elementType),x.type=h,typeof h=="function")hA(h)?(E=Tp(h,E),x.tag=1,x=FU(null,x,h,E,S)):(x.tag=0,x=tM(null,x,h,E,S));else{if(h!=null){var H=h.$$typeof;if(H===P){x.tag=11,x=PU(null,x,h,E,S);break e}else if(H===A){x.tag=14,x=TU(null,x,h,E,S);break e}}throw x=L(h)||h,Error(r(306,x,""))}}return x;case 0:return tM(h,x,x.type,x.pendingProps,S);case 1:return E=x.type,H=Tp(E,x.pendingProps),FU(h,x,E,H,S);case 3:e:{if(D(x,x.stateNode.containerInfo),h===null)throw Error(r(387));E=x.pendingProps;var Z=x.memoizedState;H=Z.element,TA(h,x),Oy(x,E,null,S);var ke=x.memoizedState;if(E=ke.cache,wm(x,Ja,E),E!==Z.cache&&SA(x,[Ja],S,!0),Ly(),E=ke.element,Z.isDehydrated)if(Z={element:E,isDehydrated:!1,cache:ke.cache},x.updateQueue.baseState=Z,x.memoizedState=Z,x.flags&256){x=RU(h,x,E,S);break e}else if(E!==H){H=fl(Error(r(424)),x),My(H),x=RU(h,x,E,S);break e}else for(h=x.stateNode.containerInfo,h.nodeType===9?h=h.body:h=h.nodeName==="HTML"?h.ownerDocument.body:h,ca=vl(h.firstChild),Gi=x,br=!0,ym=null,xl=!0,S=M5(x,null,E,S),x.child=S;S;)S.flags=S.flags&-3|4096,S=S.sibling;else{if(vp(),E===H){x=Gd(h,x,S);break e}Ki(h,x,E,S)}x=x.child}return x;case 26:return WS(h,x),h===null?(S=XB(x.type,null,x.pendingProps,null))?x.memoizedState=S:br||(S=x.type,h=x.pendingProps,E=d_(B.current).createElement(S),E[ht]=x,E[Mt]=h,Yi(E,S,h),Qe(E),x.stateNode=E):x.memoizedState=XB(x.type,h.memoizedProps,x.pendingProps,h.memoizedState),null;case 27:return z(x),h===null&&br&&(E=x.stateNode=WB(x.type,x.pendingProps,B.current),Gi=x,xl=!0,H=ca,Fm(x.type)?(BM=H,ca=vl(E.firstChild)):ca=H),Ki(h,x,x.pendingProps.children,S),WS(h,x),h===null&&(x.flags|=4194304),x.child;case 5:return h===null&&br&&((H=E=ca)&&(E=Bce(E,x.type,x.pendingProps,xl),E!==null?(x.stateNode=E,Gi=x,ca=vl(E.firstChild),xl=!1,H=!0):H=!1),H||vm(x)),z(x),H=x.type,Z=x.pendingProps,ke=h!==null?h.memoizedProps:null,E=Z.children,LM(H,Z)?E=null:ke!==null&&LM(H,ke)&&(x.flags|=32),x.memoizedState!==null&&(H=RA(h,x,nce,null,null,S),rv._currentValue=H),WS(h,x),Ki(h,x,E,S),x.child;case 6:return h===null&&br&&((h=S=ca)&&(S=Hce(S,x.pendingProps,xl),S!==null?(x.stateNode=S,Gi=x,ca=null,h=!0):h=!1),h||vm(x)),null;case 13:return LU(h,x,S);case 4:return D(x,x.stateNode.containerInfo),E=x.pendingProps,h===null?x.child=Cp(x,null,E,S):Ki(h,x,E,S),x.child;case 11:return PU(h,x,x.type,x.pendingProps,S);case 7:return Ki(h,x,x.pendingProps,S),x.child;case 8:return Ki(h,x,x.pendingProps.children,S),x.child;case 12:return Ki(h,x,x.pendingProps.children,S),x.child;case 10:return E=x.pendingProps,wm(x,x.type,E.value),Ki(h,x,E.children,S),x.child;case 9:return H=x.type._context,E=x.pendingProps.children,Sp(x),H=Wi(H),E=E(H),x.flags|=1,Ki(h,x,E,S),x.child;case 14:return TU(h,x,x.type,x.pendingProps,S);case 15:return AU(h,x,x.type,x.pendingProps,S);case 19:return IU(h,x,S);case 31:return dce(h,x,S);case 22:return MU(h,x,S,x.pendingProps);case 24:return Sp(x),E=Wi(Ja),h===null?(H=NA(),H===null&&(H=Xr,Z=_A(),H.pooledCache=Z,Z.refCount++,Z!==null&&(H.pooledCacheLanes|=S),H=Z),x.memoizedState={parent:E,cache:H},PA(x),wm(x,Ja,H)):((h.lanes&S)!==0&&(TA(h,x),Oy(x,null,null,S),Ly()),H=h.memoizedState,Z=x.memoizedState,H.parent!==E?(H={parent:E,cache:E},x.memoizedState=H,x.lanes===0&&(x.memoizedState=x.updateQueue.baseState=H),wm(x,Ja,E)):(E=Z.cache,wm(x,Ja,E),E!==H.cache&&SA(x,[Ja],S,!0))),Ki(h,x,x.pendingProps.children,S),x.child;case 29:throw x.pendingProps}throw Error(r(156,x.tag))}function Wd(h){h.flags|=4}function cM(h,x,S,E,H){if((x=(h.mode&32)!==0)&&(x=!1),x){if(h.flags|=16777216,(H&335544128)===H)if(h.stateNode.complete)h.flags|=8192;else if(mB())h.flags|=8192;else throw Np=ES,CA}else h.flags&=-16777217}function UU(h,x){if(x.type!=="stylesheet"||(x.state.loading&4)!==0)h.flags&=-16777217;else if(h.flags|=16777216,!t8(x))if(mB())h.flags|=8192;else throw Np=ES,CA}function YS(h,x){x!==null&&(h.flags|=4),h.flags&16384&&(x=h.tag!==22?tt():536870912,h.lanes|=x,zg|=x)}function qy(h,x){if(!br)switch(h.tailMode){case"hidden":x=h.tail;for(var S=null;x!==null;)x.alternate!==null&&(S=x),x=x.sibling;S===null?h.tail=null:S.sibling=null;break;case"collapsed":S=h.tail;for(var E=null;S!==null;)S.alternate!==null&&(E=S),S=S.sibling;E===null?x||h.tail===null?h.tail=null:h.tail.sibling=null:E.sibling=null}}function da(h){var x=h.alternate!==null&&h.alternate.child===h.child,S=0,E=0;if(x)for(var H=h.child;H!==null;)S|=H.lanes|H.childLanes,E|=H.subtreeFlags&65011712,E|=H.flags&65011712,H.return=h,H=H.sibling;else for(H=h.child;H!==null;)S|=H.lanes|H.childLanes,E|=H.subtreeFlags,E|=H.flags,H.return=h,H=H.sibling;return h.subtreeFlags|=E,h.childLanes=S,x}function mce(h,x,S){var E=x.pendingProps;switch(bA(x),x.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return da(x),null;case 1:return da(x),null;case 3:return S=x.stateNode,E=null,h!==null&&(E=h.memoizedState.cache),x.memoizedState.cache!==E&&(x.flags|=2048),qd(Ja),j(),S.pendingContext&&(S.context=S.pendingContext,S.pendingContext=null),(h===null||h.child===null)&&(Cg(x)?Wd(x):h===null||h.memoizedState.isDehydrated&&(x.flags&256)===0||(x.flags|=1024,yA())),da(x),null;case 26:var H=x.type,Z=x.memoizedState;return h===null?(Wd(x),Z!==null?(da(x),UU(x,Z)):(da(x),cM(x,H,null,E,S))):Z?Z!==h.memoizedState?(Wd(x),da(x),UU(x,Z)):(da(x),x.flags&=-16777217):(h=h.memoizedProps,h!==E&&Wd(x),da(x),cM(x,H,h,E,S)),null;case 27:if(W(x),S=B.current,H=x.type,h!==null&&x.stateNode!=null)h.memoizedProps!==E&&Wd(x);else{if(!E){if(x.stateNode===null)throw Error(r(166));return da(x),null}h=be.current,Cg(x)?y5(x):(h=WB(H,E,S),x.stateNode=h,Wd(x))}return da(x),null;case 5:if(W(x),H=x.type,h!==null&&x.stateNode!=null)h.memoizedProps!==E&&Wd(x);else{if(!E){if(x.stateNode===null)throw Error(r(166));return da(x),null}if(Z=be.current,Cg(x))y5(x);else{var ke=d_(B.current);switch(Z){case 1:Z=ke.createElementNS("http://www.w3.org/2000/svg",H);break;case 2:Z=ke.createElementNS("http://www.w3.org/1998/Math/MathML",H);break;default:switch(H){case"svg":Z=ke.createElementNS("http://www.w3.org/2000/svg",H);break;case"math":Z=ke.createElementNS("http://www.w3.org/1998/Math/MathML",H);break;case"script":Z=ke.createElement("div"),Z.innerHTML="<script><\/script>",Z=Z.removeChild(Z.firstChild);break;case"select":Z=typeof E.is=="string"?ke.createElement("select",{is:E.is}):ke.createElement("select"),E.multiple?Z.multiple=!0:E.size&&(Z.size=E.size);break;default:Z=typeof E.is=="string"?ke.createElement(H,{is:E.is}):ke.createElement(H)}}Z[ht]=x,Z[Mt]=E;e:for(ke=x.child;ke!==null;){if(ke.tag===5||ke.tag===6)Z.appendChild(ke.stateNode);else if(ke.tag!==4&&ke.tag!==27&&ke.child!==null){ke.child.return=ke,ke=ke.child;continue}if(ke===x)break e;for(;ke.sibling===null;){if(ke.return===null||ke.return===x)break e;ke=ke.return}ke.sibling.return=ke.return,ke=ke.sibling}x.stateNode=Z;e:switch(Yi(Z,H,E),H){case"button":case"input":case"select":case"textarea":E=!!E.autoFocus;break e;case"img":E=!0;break e;default:E=!1}E&&Wd(x)}}return da(x),cM(x,x.type,h===null?null:h.memoizedProps,x.pendingProps,S),null;case 6:if(h&&x.stateNode!=null)h.memoizedProps!==E&&Wd(x);else{if(typeof E!="string"&&x.stateNode===null)throw Error(r(166));if(h=B.current,Cg(x)){if(h=x.stateNode,S=x.memoizedProps,E=null,H=Gi,H!==null)switch(H.tag){case 27:case 5:E=H.memoizedProps}h[ht]=x,h=!!(h.nodeValue===S||E!==null&&E.suppressHydrationWarning===!0||LB(h.nodeValue,S)),h||vm(x,!0)}else h=d_(h).createTextNode(E),h[ht]=x,x.stateNode=h}return da(x),null;case 31:if(S=x.memoizedState,h===null||h.memoizedState!==null){if(E=Cg(x),S!==null){if(h===null){if(!E)throw Error(r(318));if(h=x.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(557));h[ht]=x}else vp(),(x.flags&128)===0&&(x.memoizedState=null),x.flags|=4;da(x),h=!1}else S=yA(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=S),h=!0;if(!h)return x.flags&256?(Ho(x),x):(Ho(x),null);if((x.flags&128)!==0)throw Error(r(558))}return da(x),null;case 13:if(E=x.memoizedState,h===null||h.memoizedState!==null&&h.memoizedState.dehydrated!==null){if(H=Cg(x),E!==null&&E.dehydrated!==null){if(h===null){if(!H)throw Error(r(318));if(H=x.memoizedState,H=H!==null?H.dehydrated:null,!H)throw Error(r(317));H[ht]=x}else vp(),(x.flags&128)===0&&(x.memoizedState=null),x.flags|=4;da(x),H=!1}else H=yA(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=H),H=!0;if(!H)return x.flags&256?(Ho(x),x):(Ho(x),null)}return Ho(x),(x.flags&128)!==0?(x.lanes=S,x):(S=E!==null,h=h!==null&&h.memoizedState!==null,S&&(E=x.child,H=null,E.alternate!==null&&E.alternate.memoizedState!==null&&E.alternate.memoizedState.cachePool!==null&&(H=E.alternate.memoizedState.cachePool.pool),Z=null,E.memoizedState!==null&&E.memoizedState.cachePool!==null&&(Z=E.memoizedState.cachePool.pool),Z!==H&&(E.flags|=2048)),S!==h&&S&&(x.child.flags|=8192),YS(x,x.updateQueue),da(x),null);case 4:return j(),h===null&&jM(x.stateNode.containerInfo),da(x),null;case 10:return qd(x.type),da(x),null;case 19:if(ne(Ka),E=x.memoizedState,E===null)return da(x),null;if(H=(x.flags&128)!==0,Z=E.rendering,Z===null)if(H)qy(E,!1);else{if(Da!==0||h!==null&&(h.flags&128)!==0)for(h=x.child;h!==null;){if(Z=LS(h),Z!==null){for(x.flags|=128,qy(E,!1),h=Z.updateQueue,x.updateQueue=h,YS(x,h),x.subtreeFlags=0,h=S,S=x.child;S!==null;)p5(S,h),S=S.sibling;return oe(Ka,Ka.current&1|2),br&&Bd(x,E.treeForkCount),x.child}h=h.sibling}E.tail!==null&&R()>e_&&(x.flags|=128,H=!0,qy(E,!1),x.lanes=4194304)}else{if(!H)if(h=LS(Z),h!==null){if(x.flags|=128,H=!0,h=h.updateQueue,x.updateQueue=h,YS(x,h),qy(E,!0),E.tail===null&&E.tailMode==="hidden"&&!Z.alternate&&!br)return da(x),null}else 2*R()-E.renderingStartTime>e_&&S!==536870912&&(x.flags|=128,H=!0,qy(E,!1),x.lanes=4194304);E.isBackwards?(Z.sibling=x.child,x.child=Z):(h=E.last,h!==null?h.sibling=Z:x.child=Z,E.last=Z)}return E.tail!==null?(h=E.tail,E.rendering=h,E.tail=h.sibling,E.renderingStartTime=R(),h.sibling=null,S=Ka.current,oe(Ka,H?S&1|2:S&1),br&&Bd(x,E.treeForkCount),h):(da(x),null);case 22:case 23:return Ho(x),EA(),E=x.memoizedState!==null,h!==null?h.memoizedState!==null!==E&&(x.flags|=8192):E&&(x.flags|=8192),E?(S&536870912)!==0&&(x.flags&128)===0&&(da(x),x.subtreeFlags&6&&(x.flags|=8192)):da(x),S=x.updateQueue,S!==null&&YS(x,S.retryQueue),S=null,h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(S=h.memoizedState.cachePool.pool),E=null,x.memoizedState!==null&&x.memoizedState.cachePool!==null&&(E=x.memoizedState.cachePool.pool),E!==S&&(x.flags|=2048),h!==null&&ne(_p),null;case 24:return S=null,h!==null&&(S=h.memoizedState.cache),x.memoizedState.cache!==S&&(x.flags|=2048),qd(Ja),da(x),null;case 25:return null;case 30:return null}throw Error(r(156,x.tag))}function hce(h,x){switch(bA(x),x.tag){case 1:return h=x.flags,h&65536?(x.flags=h&-65537|128,x):null;case 3:return qd(Ja),j(),h=x.flags,(h&65536)!==0&&(h&128)===0?(x.flags=h&-65537|128,x):null;case 26:case 27:case 5:return W(x),null;case 31:if(x.memoizedState!==null){if(Ho(x),x.alternate===null)throw Error(r(340));vp()}return h=x.flags,h&65536?(x.flags=h&-65537|128,x):null;case 13:if(Ho(x),h=x.memoizedState,h!==null&&h.dehydrated!==null){if(x.alternate===null)throw Error(r(340));vp()}return h=x.flags,h&65536?(x.flags=h&-65537|128,x):null;case 19:return ne(Ka),null;case 4:return j(),null;case 10:return qd(x.type),null;case 22:case 23:return Ho(x),EA(),h!==null&&ne(_p),h=x.flags,h&65536?(x.flags=h&-65537|128,x):null;case 24:return qd(Ja),null;case 25:return null;default:return null}}function BU(h,x){switch(bA(x),x.tag){case 3:qd(Ja),j();break;case 26:case 27:case 5:W(x);break;case 4:j();break;case 31:x.memoizedState!==null&&Ho(x);break;case 13:Ho(x);break;case 19:ne(Ka);break;case 10:qd(x.type);break;case 22:case 23:Ho(x),EA(),h!==null&&ne(_p);break;case 24:qd(Ja)}}function $y(h,x){try{var S=x.updateQueue,E=S!==null?S.lastEffect:null;if(E!==null){var H=E.next;S=H;do{if((S.tag&h)===h){E=void 0;var Z=S.create,ke=S.inst;E=Z(),ke.destroy=E}S=S.next}while(S!==H)}}catch(Be){Rr(x,x.return,Be)}}function Pm(h,x,S){try{var E=x.updateQueue,H=E!==null?E.lastEffect:null;if(H!==null){var Z=H.next;E=Z;do{if((E.tag&h)===h){var ke=E.inst,Be=ke.destroy;if(Be!==void 0){ke.destroy=void 0,H=x;var nt=S,kt=Be;try{kt()}catch(Ot){Rr(H,nt,Ot)}}}E=E.next}while(E!==Z)}}catch(Ot){Rr(x,x.return,Ot)}}function HU(h){var x=h.updateQueue;if(x!==null){var S=h.stateNode;try{E5(x,S)}catch(E){Rr(h,h.return,E)}}}function qU(h,x,S){S.props=Tp(h.type,h.memoizedProps),S.state=h.memoizedState;try{S.componentWillUnmount()}catch(E){Rr(h,x,E)}}function Vy(h,x){try{var S=h.ref;if(S!==null){switch(h.tag){case 26:case 27:case 5:var E=h.stateNode;break;case 30:E=h.stateNode;break;default:E=h.stateNode}typeof S=="function"?h.refCleanup=S(E):S.current=E}}catch(H){Rr(h,x,H)}}function Yc(h,x){var S=h.ref,E=h.refCleanup;if(S!==null)if(typeof E=="function")try{E()}catch(H){Rr(h,x,H)}finally{h.refCleanup=null,h=h.alternate,h!=null&&(h.refCleanup=null)}else if(typeof S=="function")try{S(null)}catch(H){Rr(h,x,H)}else S.current=null}function $U(h){var x=h.type,S=h.memoizedProps,E=h.stateNode;try{e:switch(x){case"button":case"input":case"select":case"textarea":S.autoFocus&&E.focus();break e;case"img":S.src?E.src=S.src:S.srcSet&&(E.srcset=S.srcSet)}}catch(H){Rr(h,h.return,H)}}function dM(h,x,S){try{var E=h.stateNode;Rce(E,h.type,S,x),E[Mt]=x}catch(H){Rr(h,h.return,H)}}function VU(h){return h.tag===5||h.tag===3||h.tag===26||h.tag===27&&Fm(h.type)||h.tag===4}function uM(h){e:for(;;){for(;h.sibling===null;){if(h.return===null||VU(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&&Fm(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 mM(h,x,S){var E=h.tag;if(E===5||E===6)h=h.stateNode,x?(S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S).insertBefore(h,x):(x=S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S,x.appendChild(h),S=S._reactRootContainer,S!=null||x.onclick!==null||(x.onclick=Vt));else if(E!==4&&(E===27&&Fm(h.type)&&(S=h.stateNode,x=null),h=h.child,h!==null))for(mM(h,x,S),h=h.sibling;h!==null;)mM(h,x,S),h=h.sibling}function XS(h,x,S){var E=h.tag;if(E===5||E===6)h=h.stateNode,x?S.insertBefore(h,x):S.appendChild(h);else if(E!==4&&(E===27&&Fm(h.type)&&(S=h.stateNode),h=h.child,h!==null))for(XS(h,x,S),h=h.sibling;h!==null;)XS(h,x,S),h=h.sibling}function GU(h){var x=h.stateNode,S=h.memoizedProps;try{for(var E=h.type,H=x.attributes;H.length;)x.removeAttributeNode(H[0]);Yi(x,E,S),x[ht]=h,x[Mt]=S}catch(Z){Rr(h,h.return,Z)}}var Kd=!1,ni=!1,hM=!1,WU=typeof WeakSet=="function"?WeakSet:Set,Ti=null;function pce(h,x){if(h=h.containerInfo,FM=b_,h=i5(h),sA(h)){if("selectionStart"in h)var S={start:h.selectionStart,end:h.selectionEnd};else e:{S=(S=h.ownerDocument)&&S.defaultView||window;var E=S.getSelection&&S.getSelection();if(E&&E.rangeCount!==0){S=E.anchorNode;var H=E.anchorOffset,Z=E.focusNode;E=E.focusOffset;try{S.nodeType,Z.nodeType}catch{S=null;break e}var ke=0,Be=-1,nt=-1,kt=0,Ot=0,zt=h,Tt=null;t:for(;;){for(var Et;zt!==S||H!==0&&zt.nodeType!==3||(Be=ke+H),zt!==Z||E!==0&&zt.nodeType!==3||(nt=ke+E),zt.nodeType===3&&(ke+=zt.nodeValue.length),(Et=zt.firstChild)!==null;)Tt=zt,zt=Et;for(;;){if(zt===h)break t;if(Tt===S&&++kt===H&&(Be=ke),Tt===Z&&++Ot===E&&(nt=ke),(Et=zt.nextSibling)!==null)break;zt=Tt,Tt=zt.parentNode}zt=Et}S=Be===-1||nt===-1?null:{start:Be,end:nt}}else S=null}S=S||{start:0,end:0}}else S=null;for(RM={focusedElem:h,selectionRange:S},b_=!1,Ti=x;Ti!==null;)if(x=Ti,h=x.child,(x.subtreeFlags&1028)!==0&&h!==null)h.return=x,Ti=h;else for(;Ti!==null;){switch(x=Ti,Z=x.alternate,h=x.flags,x.tag){case 0:if((h&4)!==0&&(h=x.updateQueue,h=h!==null?h.events:null,h!==null))for(S=0;S<h.length;S++)H=h[S],H.ref.impl=H.nextImpl;break;case 11:case 15:break;case 1:if((h&1024)!==0&&Z!==null){h=void 0,S=x,H=Z.memoizedProps,Z=Z.memoizedState,E=S.stateNode;try{var pn=Tp(S.type,H);h=E.getSnapshotBeforeUpdate(pn,Z),E.__reactInternalSnapshotBeforeUpdate=h}catch(jn){Rr(S,S.return,jn)}}break;case 3:if((h&1024)!==0){if(h=x.stateNode.containerInfo,S=h.nodeType,S===9)IM(h);else if(S===1)switch(h.nodeName){case"HEAD":case"HTML":case"BODY":IM(h);break;default:h.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((h&1024)!==0)throw Error(r(163))}if(h=x.sibling,h!==null){h.return=x.return,Ti=h;break}Ti=x.return}}function KU(h,x,S){var E=S.flags;switch(S.tag){case 0:case 11:case 15:Xd(h,S),E&4&&$y(5,S);break;case 1:if(Xd(h,S),E&4)if(h=S.stateNode,x===null)try{h.componentDidMount()}catch(ke){Rr(S,S.return,ke)}else{var H=Tp(S.type,x.memoizedProps);x=x.memoizedState;try{h.componentDidUpdate(H,x,h.__reactInternalSnapshotBeforeUpdate)}catch(ke){Rr(S,S.return,ke)}}E&64&&HU(S),E&512&&Vy(S,S.return);break;case 3:if(Xd(h,S),E&64&&(h=S.updateQueue,h!==null)){if(x=null,S.child!==null)switch(S.child.tag){case 27:case 5:x=S.child.stateNode;break;case 1:x=S.child.stateNode}try{E5(h,x)}catch(ke){Rr(S,S.return,ke)}}break;case 27:x===null&&E&4&&GU(S);case 26:case 5:Xd(h,S),x===null&&E&4&&$U(S),E&512&&Vy(S,S.return);break;case 12:Xd(h,S);break;case 31:Xd(h,S),E&4&&QU(h,S);break;case 13:Xd(h,S),E&4&&ZU(h,S),E&64&&(h=S.memoizedState,h!==null&&(h=h.dehydrated,h!==null&&(S=_ce.bind(null,S),qce(h,S))));break;case 22:if(E=S.memoizedState!==null||Kd,!E){x=x!==null&&x.memoizedState!==null||ni,H=Kd;var Z=ni;Kd=E,(ni=x)&&!Z?Qd(h,S,(S.subtreeFlags&8772)!==0):Xd(h,S),Kd=H,ni=Z}break;case 30:break;default:Xd(h,S)}}function YU(h){var x=h.alternate;x!==null&&(h.alternate=null,YU(x)),h.child=null,h.deletions=null,h.sibling=null,h.tag===5&&(x=h.stateNode,x!==null&&Le(x)),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 fa=null,mo=!1;function Yd(h,x,S){for(S=S.child;S!==null;)XU(h,x,S),S=S.sibling}function XU(h,x,S){if(Se&&typeof Se.onCommitFiberUnmount=="function")try{Se.onCommitFiberUnmount(Ee,S)}catch{}switch(S.tag){case 26:ni||Yc(S,x),Yd(h,x,S),S.memoizedState?S.memoizedState.count--:S.stateNode&&(S=S.stateNode,S.parentNode.removeChild(S));break;case 27:ni||Yc(S,x);var E=fa,H=mo;Fm(S.type)&&(fa=S.stateNode,mo=!1),Yd(h,x,S),ev(S.stateNode),fa=E,mo=H;break;case 5:ni||Yc(S,x);case 6:if(E=fa,H=mo,fa=null,Yd(h,x,S),fa=E,mo=H,fa!==null)if(mo)try{(fa.nodeType===9?fa.body:fa.nodeName==="HTML"?fa.ownerDocument.body:fa).removeChild(S.stateNode)}catch(Z){Rr(S,x,Z)}else try{fa.removeChild(S.stateNode)}catch(Z){Rr(S,x,Z)}break;case 18:fa!==null&&(mo?(h=fa,HB(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,S.stateNode),Wg(h)):HB(fa,S.stateNode));break;case 4:E=fa,H=mo,fa=S.stateNode.containerInfo,mo=!0,Yd(h,x,S),fa=E,mo=H;break;case 0:case 11:case 14:case 15:Pm(2,S,x),ni||Pm(4,S,x),Yd(h,x,S);break;case 1:ni||(Yc(S,x),E=S.stateNode,typeof E.componentWillUnmount=="function"&&qU(S,x,E)),Yd(h,x,S);break;case 21:Yd(h,x,S);break;case 22:ni=(E=ni)||S.memoizedState!==null,Yd(h,x,S),ni=E;break;default:Yd(h,x,S)}}function QU(h,x){if(x.memoizedState===null&&(h=x.alternate,h!==null&&(h=h.memoizedState,h!==null))){h=h.dehydrated;try{Wg(h)}catch(S){Rr(x,x.return,S)}}}function ZU(h,x){if(x.memoizedState===null&&(h=x.alternate,h!==null&&(h=h.memoizedState,h!==null&&(h=h.dehydrated,h!==null))))try{Wg(h)}catch(S){Rr(x,x.return,S)}}function fce(h){switch(h.tag){case 31:case 13:case 19:var x=h.stateNode;return x===null&&(x=h.stateNode=new WU),x;case 22:return h=h.stateNode,x=h._retryCache,x===null&&(x=h._retryCache=new WU),x;default:throw Error(r(435,h.tag))}}function QS(h,x){var S=fce(h);x.forEach(function(E){if(!S.has(E)){S.add(E);var H=kce.bind(null,h,E);E.then(H,H)}})}function ho(h,x){var S=x.deletions;if(S!==null)for(var E=0;E<S.length;E++){var H=S[E],Z=h,ke=x,Be=ke;e:for(;Be!==null;){switch(Be.tag){case 27:if(Fm(Be.type)){fa=Be.stateNode,mo=!1;break e}break;case 5:fa=Be.stateNode,mo=!1;break e;case 3:case 4:fa=Be.stateNode.containerInfo,mo=!0;break e}Be=Be.return}if(fa===null)throw Error(r(160));XU(Z,ke,H),fa=null,mo=!1,Z=H.alternate,Z!==null&&(Z.return=null),H.return=null}if(x.subtreeFlags&13886)for(x=x.child;x!==null;)JU(x,h),x=x.sibling}var uc=null;function JU(h,x){var S=h.alternate,E=h.flags;switch(h.tag){case 0:case 11:case 14:case 15:ho(x,h),po(h),E&4&&(Pm(3,h,h.return),$y(3,h),Pm(5,h,h.return));break;case 1:ho(x,h),po(h),E&512&&(ni||S===null||Yc(S,S.return)),E&64&&Kd&&(h=h.updateQueue,h!==null&&(E=h.callbacks,E!==null&&(S=h.shared.hiddenCallbacks,h.shared.hiddenCallbacks=S===null?E:S.concat(E))));break;case 26:var H=uc;if(ho(x,h),po(h),E&512&&(ni||S===null||Yc(S,S.return)),E&4){var Z=S!==null?S.memoizedState:null;if(E=h.memoizedState,S===null)if(E===null)if(h.stateNode===null){e:{E=h.type,S=h.memoizedProps,H=H.ownerDocument||H;t:switch(E){case"title":Z=H.getElementsByTagName("title")[0],(!Z||Z[De]||Z[ht]||Z.namespaceURI==="http://www.w3.org/2000/svg"||Z.hasAttribute("itemprop"))&&(Z=H.createElement(E),H.head.insertBefore(Z,H.querySelector("head > title"))),Yi(Z,E,S),Z[ht]=h,Qe(Z),E=Z;break e;case"link":var ke=JB("link","href",H).get(E+(S.href||""));if(ke){for(var Be=0;Be<ke.length;Be++)if(Z=ke[Be],Z.getAttribute("href")===(S.href==null||S.href===""?null:S.href)&&Z.getAttribute("rel")===(S.rel==null?null:S.rel)&&Z.getAttribute("title")===(S.title==null?null:S.title)&&Z.getAttribute("crossorigin")===(S.crossOrigin==null?null:S.crossOrigin)){ke.splice(Be,1);break t}}Z=H.createElement(E),Yi(Z,E,S),H.head.appendChild(Z);break;case"meta":if(ke=JB("meta","content",H).get(E+(S.content||""))){for(Be=0;Be<ke.length;Be++)if(Z=ke[Be],Z.getAttribute("content")===(S.content==null?null:""+S.content)&&Z.getAttribute("name")===(S.name==null?null:S.name)&&Z.getAttribute("property")===(S.property==null?null:S.property)&&Z.getAttribute("http-equiv")===(S.httpEquiv==null?null:S.httpEquiv)&&Z.getAttribute("charset")===(S.charSet==null?null:S.charSet)){ke.splice(Be,1);break t}}Z=H.createElement(E),Yi(Z,E,S),H.head.appendChild(Z);break;default:throw Error(r(468,E))}Z[ht]=h,Qe(Z),E=Z}h.stateNode=E}else e8(H,h.type,h.stateNode);else h.stateNode=ZB(H,E,h.memoizedProps);else Z!==E?(Z===null?S.stateNode!==null&&(S=S.stateNode,S.parentNode.removeChild(S)):Z.count--,E===null?e8(H,h.type,h.stateNode):ZB(H,E,h.memoizedProps)):E===null&&h.stateNode!==null&&dM(h,h.memoizedProps,S.memoizedProps)}break;case 27:ho(x,h),po(h),E&512&&(ni||S===null||Yc(S,S.return)),S!==null&&E&4&&dM(h,h.memoizedProps,S.memoizedProps);break;case 5:if(ho(x,h),po(h),E&512&&(ni||S===null||Yc(S,S.return)),h.flags&32){H=h.stateNode;try{Bi(H,"")}catch(pn){Rr(h,h.return,pn)}}E&4&&h.stateNode!=null&&(H=h.memoizedProps,dM(h,H,S!==null?S.memoizedProps:H)),E&1024&&(hM=!0);break;case 6:if(ho(x,h),po(h),E&4){if(h.stateNode===null)throw Error(r(162));E=h.memoizedProps,S=h.stateNode;try{S.nodeValue=E}catch(pn){Rr(h,h.return,pn)}}break;case 3:if(h_=null,H=uc,uc=u_(x.containerInfo),ho(x,h),uc=H,po(h),E&4&&S!==null&&S.memoizedState.isDehydrated)try{Wg(x.containerInfo)}catch(pn){Rr(h,h.return,pn)}hM&&(hM=!1,eB(h));break;case 4:E=uc,uc=u_(h.stateNode.containerInfo),ho(x,h),po(h),uc=E;break;case 12:ho(x,h),po(h);break;case 31:ho(x,h),po(h),E&4&&(E=h.updateQueue,E!==null&&(h.updateQueue=null,QS(h,E)));break;case 13:ho(x,h),po(h),h.child.flags&8192&&h.memoizedState!==null!=(S!==null&&S.memoizedState!==null)&&(JS=R()),E&4&&(E=h.updateQueue,E!==null&&(h.updateQueue=null,QS(h,E)));break;case 22:H=h.memoizedState!==null;var nt=S!==null&&S.memoizedState!==null,kt=Kd,Ot=ni;if(Kd=kt||H,ni=Ot||nt,ho(x,h),ni=Ot,Kd=kt,po(h),E&8192)e:for(x=h.stateNode,x._visibility=H?x._visibility&-2:x._visibility|1,H&&(S===null||nt||Kd||ni||Ap(h)),S=null,x=h;;){if(x.tag===5||x.tag===26){if(S===null){nt=S=x;try{if(Z=nt.stateNode,H)ke=Z.style,typeof ke.setProperty=="function"?ke.setProperty("display","none","important"):ke.display="none";else{Be=nt.stateNode;var zt=nt.memoizedProps.style,Tt=zt!=null&&zt.hasOwnProperty("display")?zt.display:null;Be.style.display=Tt==null||typeof Tt=="boolean"?"":(""+Tt).trim()}}catch(pn){Rr(nt,nt.return,pn)}}}else if(x.tag===6){if(S===null){nt=x;try{nt.stateNode.nodeValue=H?"":nt.memoizedProps}catch(pn){Rr(nt,nt.return,pn)}}}else if(x.tag===18){if(S===null){nt=x;try{var Et=nt.stateNode;H?qB(Et,!0):qB(nt.stateNode,!1)}catch(pn){Rr(nt,nt.return,pn)}}}else if((x.tag!==22&&x.tag!==23||x.memoizedState===null||x===h)&&x.child!==null){x.child.return=x,x=x.child;continue}if(x===h)break e;for(;x.sibling===null;){if(x.return===null||x.return===h)break e;S===x&&(S=null),x=x.return}S===x&&(S=null),x.sibling.return=x.return,x=x.sibling}E&4&&(E=h.updateQueue,E!==null&&(S=E.retryQueue,S!==null&&(E.retryQueue=null,QS(h,S))));break;case 19:ho(x,h),po(h),E&4&&(E=h.updateQueue,E!==null&&(h.updateQueue=null,QS(h,E)));break;case 30:break;case 21:break;default:ho(x,h),po(h)}}function po(h){var x=h.flags;if(x&2){try{for(var S,E=h.return;E!==null;){if(VU(E)){S=E;break}E=E.return}if(S==null)throw Error(r(160));switch(S.tag){case 27:var H=S.stateNode,Z=uM(h);XS(h,Z,H);break;case 5:var ke=S.stateNode;S.flags&32&&(Bi(ke,""),S.flags&=-33);var Be=uM(h);XS(h,Be,ke);break;case 3:case 4:var nt=S.stateNode.containerInfo,kt=uM(h);mM(h,kt,nt);break;default:throw Error(r(161))}}catch(Ot){Rr(h,h.return,Ot)}h.flags&=-3}x&4096&&(h.flags&=-4097)}function eB(h){if(h.subtreeFlags&1024)for(h=h.child;h!==null;){var x=h;eB(x),x.tag===5&&x.flags&1024&&x.stateNode.reset(),h=h.sibling}}function Xd(h,x){if(x.subtreeFlags&8772)for(x=x.child;x!==null;)KU(h,x.alternate,x),x=x.sibling}function Ap(h){for(h=h.child;h!==null;){var x=h;switch(x.tag){case 0:case 11:case 14:case 15:Pm(4,x,x.return),Ap(x);break;case 1:Yc(x,x.return);var S=x.stateNode;typeof S.componentWillUnmount=="function"&&qU(x,x.return,S),Ap(x);break;case 27:ev(x.stateNode);case 26:case 5:Yc(x,x.return),Ap(x);break;case 22:x.memoizedState===null&&Ap(x);break;case 30:Ap(x);break;default:Ap(x)}h=h.sibling}}function Qd(h,x,S){for(S=S&&(x.subtreeFlags&8772)!==0,x=x.child;x!==null;){var E=x.alternate,H=h,Z=x,ke=Z.flags;switch(Z.tag){case 0:case 11:case 15:Qd(H,Z,S),$y(4,Z);break;case 1:if(Qd(H,Z,S),E=Z,H=E.stateNode,typeof H.componentDidMount=="function")try{H.componentDidMount()}catch(kt){Rr(E,E.return,kt)}if(E=Z,H=E.updateQueue,H!==null){var Be=E.stateNode;try{var nt=H.shared.hiddenCallbacks;if(nt!==null)for(H.shared.hiddenCallbacks=null,H=0;H<nt.length;H++)j5(nt[H],Be)}catch(kt){Rr(E,E.return,kt)}}S&&ke&64&&HU(Z),Vy(Z,Z.return);break;case 27:GU(Z);case 26:case 5:Qd(H,Z,S),S&&E===null&&ke&4&&$U(Z),Vy(Z,Z.return);break;case 12:Qd(H,Z,S);break;case 31:Qd(H,Z,S),S&&ke&4&&QU(H,Z);break;case 13:Qd(H,Z,S),S&&ke&4&&ZU(H,Z);break;case 22:Z.memoizedState===null&&Qd(H,Z,S),Vy(Z,Z.return);break;case 30:break;default:Qd(H,Z,S)}x=x.sibling}}function pM(h,x){var S=null;h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(S=h.memoizedState.cachePool.pool),h=null,x.memoizedState!==null&&x.memoizedState.cachePool!==null&&(h=x.memoizedState.cachePool.pool),h!==S&&(h!=null&&h.refCount++,S!=null&&jy(S))}function fM(h,x){h=null,x.alternate!==null&&(h=x.alternate.memoizedState.cache),x=x.memoizedState.cache,x!==h&&(x.refCount++,h!=null&&jy(h))}function mc(h,x,S,E){if(x.subtreeFlags&10256)for(x=x.child;x!==null;)tB(h,x,S,E),x=x.sibling}function tB(h,x,S,E){var H=x.flags;switch(x.tag){case 0:case 11:case 15:mc(h,x,S,E),H&2048&&$y(9,x);break;case 1:mc(h,x,S,E);break;case 3:mc(h,x,S,E),H&2048&&(h=null,x.alternate!==null&&(h=x.alternate.memoizedState.cache),x=x.memoizedState.cache,x!==h&&(x.refCount++,h!=null&&jy(h)));break;case 12:if(H&2048){mc(h,x,S,E),h=x.stateNode;try{var Z=x.memoizedProps,ke=Z.id,Be=Z.onPostCommit;typeof Be=="function"&&Be(ke,x.alternate===null?"mount":"update",h.passiveEffectDuration,-0)}catch(nt){Rr(x,x.return,nt)}}else mc(h,x,S,E);break;case 31:mc(h,x,S,E);break;case 13:mc(h,x,S,E);break;case 23:break;case 22:Z=x.stateNode,ke=x.alternate,x.memoizedState!==null?Z._visibility&2?mc(h,x,S,E):Gy(h,x):Z._visibility&2?mc(h,x,S,E):(Z._visibility|=2,Lg(h,x,S,E,(x.subtreeFlags&10256)!==0||!1)),H&2048&&pM(ke,x);break;case 24:mc(h,x,S,E),H&2048&&fM(x.alternate,x);break;default:mc(h,x,S,E)}}function Lg(h,x,S,E,H){for(H=H&&((x.subtreeFlags&10256)!==0||!1),x=x.child;x!==null;){var Z=h,ke=x,Be=S,nt=E,kt=ke.flags;switch(ke.tag){case 0:case 11:case 15:Lg(Z,ke,Be,nt,H),$y(8,ke);break;case 23:break;case 22:var Ot=ke.stateNode;ke.memoizedState!==null?Ot._visibility&2?Lg(Z,ke,Be,nt,H):Gy(Z,ke):(Ot._visibility|=2,Lg(Z,ke,Be,nt,H)),H&&kt&2048&&pM(ke.alternate,ke);break;case 24:Lg(Z,ke,Be,nt,H),H&&kt&2048&&fM(ke.alternate,ke);break;default:Lg(Z,ke,Be,nt,H)}x=x.sibling}}function Gy(h,x){if(x.subtreeFlags&10256)for(x=x.child;x!==null;){var S=h,E=x,H=E.flags;switch(E.tag){case 22:Gy(S,E),H&2048&&pM(E.alternate,E);break;case 24:Gy(S,E),H&2048&&fM(E.alternate,E);break;default:Gy(S,E)}x=x.sibling}}var Wy=8192;function Og(h,x,S){if(h.subtreeFlags&Wy)for(h=h.child;h!==null;)nB(h,x,S),h=h.sibling}function nB(h,x,S){switch(h.tag){case 26:Og(h,x,S),h.flags&Wy&&h.memoizedState!==null&&tde(S,uc,h.memoizedState,h.memoizedProps);break;case 5:Og(h,x,S);break;case 3:case 4:var E=uc;uc=u_(h.stateNode.containerInfo),Og(h,x,S),uc=E;break;case 22:h.memoizedState===null&&(E=h.alternate,E!==null&&E.memoizedState!==null?(E=Wy,Wy=16777216,Og(h,x,S),Wy=E):Og(h,x,S));break;default:Og(h,x,S)}}function rB(h){var x=h.alternate;if(x!==null&&(h=x.child,h!==null)){x.child=null;do x=h.sibling,h.sibling=null,h=x;while(h!==null)}}function Ky(h){var x=h.deletions;if((h.flags&16)!==0){if(x!==null)for(var S=0;S<x.length;S++){var E=x[S];Ti=E,iB(E,h)}rB(h)}if(h.subtreeFlags&10256)for(h=h.child;h!==null;)aB(h),h=h.sibling}function aB(h){switch(h.tag){case 0:case 11:case 15:Ky(h),h.flags&2048&&Pm(9,h,h.return);break;case 3:Ky(h);break;case 12:Ky(h);break;case 22:var x=h.stateNode;h.memoizedState!==null&&x._visibility&2&&(h.return===null||h.return.tag!==13)?(x._visibility&=-3,ZS(h)):Ky(h);break;default:Ky(h)}}function ZS(h){var x=h.deletions;if((h.flags&16)!==0){if(x!==null)for(var S=0;S<x.length;S++){var E=x[S];Ti=E,iB(E,h)}rB(h)}for(h=h.child;h!==null;){switch(x=h,x.tag){case 0:case 11:case 15:Pm(8,x,x.return),ZS(x);break;case 22:S=x.stateNode,S._visibility&2&&(S._visibility&=-3,ZS(x));break;default:ZS(x)}h=h.sibling}}function iB(h,x){for(;Ti!==null;){var S=Ti;switch(S.tag){case 0:case 11:case 15:Pm(8,S,x);break;case 23:case 22:if(S.memoizedState!==null&&S.memoizedState.cachePool!==null){var E=S.memoizedState.cachePool.pool;E!=null&&E.refCount++}break;case 24:jy(S.memoizedState.cache)}if(E=S.child,E!==null)E.return=S,Ti=E;else e:for(S=h;Ti!==null;){E=Ti;var H=E.sibling,Z=E.return;if(YU(E),E===S){Ti=null;break e}if(H!==null){H.return=Z,Ti=H;break e}Ti=Z}}}var gce={getCacheForType:function(h){var x=Wi(Ja),S=x.data.get(h);return S===void 0&&(S=h(),x.data.set(h,S)),S},cacheSignal:function(){return Wi(Ja).controller.signal}},bce=typeof WeakMap=="function"?WeakMap:Map,Ar=0,Xr=null,cr=null,hr=0,Fr=0,qo=null,Tm=!1,Ig=!1,gM=!1,Zd=0,Da=0,Am=0,Mp=0,bM=0,$o=0,zg=0,Yy=null,fo=null,xM=!1,JS=0,sB=0,e_=1/0,t_=null,Mm=null,hi=0,jm=null,Ug=null,Jd=0,yM=0,vM=null,oB=null,Xy=0,wM=null;function Vo(){return(Ar&2)!==0&&hr!==0?hr&-hr:ae.T!==null?PM():Ke()}function lB(){if($o===0)if((hr&536870912)===0||br){var h=Ne;Ne<<=1,(Ne&3932160)===0&&(Ne=262144),$o=h}else $o=536870912;return h=Bo.current,h!==null&&(h.flags|=32),$o}function go(h,x,S){(h===Xr&&(Fr===2||Fr===9)||h.cancelPendingCommit!==null)&&(Bg(h,0),Em(h,hr,$o,!1)),xt(h,S),((Ar&2)===0||h!==Xr)&&(h===Xr&&((Ar&2)===0&&(Mp|=S),Da===4&&Em(h,hr,$o,!1)),Xc(h))}function cB(h,x,S){if((Ar&6)!==0)throw Error(r(327));var E=!S&&(x&127)===0&&(x&h.expiredLanes)===0||Me(h,x),H=E?vce(h,x):_M(h,x,!0),Z=E;do{if(H===0){Ig&&!E&&Em(h,x,0,!1);break}else{if(S=h.current.alternate,Z&&!xce(S)){H=_M(h,x,!1),Z=!1;continue}if(H===2){if(Z=x,h.errorRecoveryDisabledLanes&Z)var ke=0;else ke=h.pendingLanes&-536870913,ke=ke!==0?ke:ke&536870912?536870912:0;if(ke!==0){x=ke;e:{var Be=h;H=Yy;var nt=Be.current.memoizedState.isDehydrated;if(nt&&(Bg(Be,ke).flags|=256),ke=_M(Be,ke,!1),ke!==2){if(gM&&!nt){Be.errorRecoveryDisabledLanes|=Z,Mp|=Z,H=4;break e}Z=fo,fo=H,Z!==null&&(fo===null?fo=Z:fo.push.apply(fo,Z))}H=ke}if(Z=!1,H!==2)continue}}if(H===1){Bg(h,0),Em(h,x,0,!0);break}e:{switch(E=h,Z=H,Z){case 0:case 1:throw Error(r(345));case 4:if((x&4194048)!==x)break;case 6:Em(E,x,$o,!Tm);break e;case 2:fo=null;break;case 3:case 5:break;default:throw Error(r(329))}if((x&62914560)===x&&(H=JS+300-R(),10<H)){if(Em(E,x,$o,!Tm),Pe(E,0,!0)!==0)break e;Jd=x,E.timeoutHandle=UB(dB.bind(null,E,S,fo,t_,xM,x,$o,Mp,zg,Tm,Z,"Throttled",-0,0),H);break e}dB(E,S,fo,t_,xM,x,$o,Mp,zg,Tm,Z,null,-0,0)}}break}while(!0);Xc(h)}function dB(h,x,S,E,H,Z,ke,Be,nt,kt,Ot,zt,Tt,Et){if(h.timeoutHandle=-1,zt=x.subtreeFlags,zt&8192||(zt&16785408)===16785408){zt={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Vt},nB(x,Z,zt);var pn=(Z&62914560)===Z?JS-R():(Z&4194048)===Z?sB-R():0;if(pn=nde(zt,pn),pn!==null){Jd=Z,h.cancelPendingCommit=pn(xB.bind(null,h,x,Z,S,E,H,ke,Be,nt,Ot,zt,null,Tt,Et)),Em(h,Z,ke,!kt);return}}xB(h,x,Z,S,E,H,ke,Be,nt)}function xce(h){for(var x=h;;){var S=x.tag;if((S===0||S===11||S===15)&&x.flags&16384&&(S=x.updateQueue,S!==null&&(S=S.stores,S!==null)))for(var E=0;E<S.length;E++){var H=S[E],Z=H.getSnapshot;H=H.value;try{if(!zo(Z(),H))return!1}catch{return!1}}if(S=x.child,x.subtreeFlags&16384&&S!==null)S.return=x,x=S;else{if(x===h)break;for(;x.sibling===null;){if(x.return===null||x.return===h)return!0;x=x.return}x.sibling.return=x.return,x=x.sibling}}return!0}function Em(h,x,S,E){x&=~bM,x&=~Mp,h.suspendedLanes|=x,h.pingedLanes&=~x,E&&(h.warmLanes|=x),E=h.expirationTimes;for(var H=x;0<H;){var Z=31-qe(H),ke=1<<Z;E[Z]=-1,H&=~ke}S!==0&&Ht(h,S,x)}function n_(){return(Ar&6)===0?(Qy(0),!1):!0}function SM(){if(cr!==null){if(Fr===0)var h=cr.return;else h=cr,Hd=wp=null,IA(h),jg=null,Dy=0,h=cr;for(;h!==null;)BU(h.alternate,h),h=h.return;cr=null}}function Bg(h,x){var S=h.timeoutHandle;S!==-1&&(h.timeoutHandle=-1,Ice(S)),S=h.cancelPendingCommit,S!==null&&(h.cancelPendingCommit=null,S()),Jd=0,SM(),Xr=h,cr=S=Ud(h.current,null),hr=x,Fr=0,qo=null,Tm=!1,Ig=Me(h,x),gM=!1,zg=$o=bM=Mp=Am=Da=0,fo=Yy=null,xM=!1,(x&8)!==0&&(x|=x&32);var E=h.entangledLanes;if(E!==0)for(h=h.entanglements,E&=x;0<E;){var H=31-qe(E),Z=1<<H;x|=h[H],E&=~Z}return Zd=x,_S(),S}function uB(h,x){Yn=null,ae.H=By,x===Mg||x===jS?(x=P5(),Fr=3):x===CA?(x=P5(),Fr=4):Fr=x===eM?8:x!==null&&typeof x=="object"&&typeof x.then=="function"?6:1,qo=x,cr===null&&(Da=1,VS(h,fl(x,h.current)))}function mB(){var h=Bo.current;return h===null?!0:(hr&4194048)===hr?yl===null:(hr&62914560)===hr||(hr&536870912)!==0?h===yl:!1}function hB(){var h=ae.H;return ae.H=By,h===null?By:h}function pB(){var h=ae.A;return ae.A=gce,h}function r_(){Da=4,Tm||(hr&4194048)!==hr&&Bo.current!==null||(Ig=!0),(Am&134217727)===0&&(Mp&134217727)===0||Xr===null||Em(Xr,hr,$o,!1)}function _M(h,x,S){var E=Ar;Ar|=2;var H=hB(),Z=pB();(Xr!==h||hr!==x)&&(t_=null,Bg(h,x)),x=!1;var ke=Da;e:do try{if(Fr!==0&&cr!==null){var Be=cr,nt=qo;switch(Fr){case 8:SM(),ke=6;break e;case 3:case 2:case 9:case 6:Bo.current===null&&(x=!0);var kt=Fr;if(Fr=0,qo=null,Hg(h,Be,nt,kt),S&&Ig){ke=0;break e}break;default:kt=Fr,Fr=0,qo=null,Hg(h,Be,nt,kt)}}yce(),ke=Da;break}catch(Ot){uB(h,Ot)}while(!0);return x&&h.shellSuspendCounter++,Hd=wp=null,Ar=E,ae.H=H,ae.A=Z,cr===null&&(Xr=null,hr=0,_S()),ke}function yce(){for(;cr!==null;)fB(cr)}function vce(h,x){var S=Ar;Ar|=2;var E=hB(),H=pB();Xr!==h||hr!==x?(t_=null,e_=R()+500,Bg(h,x)):Ig=Me(h,x);e:do try{if(Fr!==0&&cr!==null){x=cr;var Z=qo;t:switch(Fr){case 1:Fr=0,qo=null,Hg(h,x,Z,1);break;case 2:case 9:if(N5(Z)){Fr=0,qo=null,gB(x);break}x=function(){Fr!==2&&Fr!==9||Xr!==h||(Fr=7),Xc(h)},Z.then(x,x);break e;case 3:Fr=7;break e;case 4:Fr=5;break e;case 7:N5(Z)?(Fr=0,qo=null,gB(x)):(Fr=0,qo=null,Hg(h,x,Z,7));break;case 5:var ke=null;switch(cr.tag){case 26:ke=cr.memoizedState;case 5:case 27:var Be=cr;if(ke?t8(ke):Be.stateNode.complete){Fr=0,qo=null;var nt=Be.sibling;if(nt!==null)cr=nt;else{var kt=Be.return;kt!==null?(cr=kt,a_(kt)):cr=null}break t}}Fr=0,qo=null,Hg(h,x,Z,5);break;case 6:Fr=0,qo=null,Hg(h,x,Z,6);break;case 8:SM(),Da=6;break e;default:throw Error(r(462))}}wce();break}catch(Ot){uB(h,Ot)}while(!0);return Hd=wp=null,ae.H=E,ae.A=H,Ar=S,cr!==null?0:(Xr=null,hr=0,_S(),Da)}function wce(){for(;cr!==null&&!se();)fB(cr)}function fB(h){var x=zU(h.alternate,h,Zd);h.memoizedProps=h.pendingProps,x===null?a_(h):cr=x}function gB(h){var x=h,S=x.alternate;switch(x.tag){case 15:case 0:x=DU(S,x,x.pendingProps,x.type,void 0,hr);break;case 11:x=DU(S,x,x.pendingProps,x.type.render,x.ref,hr);break;case 5:IA(x);default:BU(S,x),x=cr=p5(x,Zd),x=zU(S,x,Zd)}h.memoizedProps=h.pendingProps,x===null?a_(h):cr=x}function Hg(h,x,S,E){Hd=wp=null,IA(x),jg=null,Dy=0;var H=x.return;try{if(cce(h,H,x,S,hr)){Da=1,VS(h,fl(S,h.current)),cr=null;return}}catch(Z){if(H!==null)throw cr=H,Z;Da=1,VS(h,fl(S,h.current)),cr=null;return}x.flags&32768?(br||E===1?h=!0:Ig||(hr&536870912)!==0?h=!1:(Tm=h=!0,(E===2||E===9||E===3||E===6)&&(E=Bo.current,E!==null&&E.tag===13&&(E.flags|=16384))),bB(x,h)):a_(x)}function a_(h){var x=h;do{if((x.flags&32768)!==0){bB(x,Tm);return}h=x.return;var S=mce(x.alternate,x,Zd);if(S!==null){cr=S;return}if(x=x.sibling,x!==null){cr=x;return}cr=x=h}while(x!==null);Da===0&&(Da=5)}function bB(h,x){do{var S=hce(h.alternate,h);if(S!==null){S.flags&=32767,cr=S;return}if(S=h.return,S!==null&&(S.flags|=32768,S.subtreeFlags=0,S.deletions=null),!x&&(h=h.sibling,h!==null)){cr=h;return}cr=h=S}while(h!==null);Da=6,cr=null}function xB(h,x,S,E,H,Z,ke,Be,nt){h.cancelPendingCommit=null;do i_();while(hi!==0);if((Ar&6)!==0)throw Error(r(327));if(x!==null){if(x===h.current)throw Error(r(177));if(Z=x.lanes|x.childLanes,Z|=uA,wt(h,S,Z,ke,Be,nt),h===Xr&&(cr=Xr=null,hr=0),Ug=x,jm=h,Jd=S,yM=Z,vM=H,oB=E,(x.subtreeFlags&10256)!==0||(x.flags&10256)!==0?(h.callbackNode=null,h.callbackPriority=0,Nce(ye,function(){return _B(),null})):(h.callbackNode=null,h.callbackPriority=0),E=(x.flags&13878)!==0,(x.subtreeFlags&13878)!==0||E){E=ae.T,ae.T=null,H=ee.p,ee.p=2,ke=Ar,Ar|=4;try{pce(h,x,S)}finally{Ar=ke,ee.p=H,ae.T=E}}hi=1,yB(),vB(),wB()}}function yB(){if(hi===1){hi=0;var h=jm,x=Ug,S=(x.flags&13878)!==0;if((x.subtreeFlags&13878)!==0||S){S=ae.T,ae.T=null;var E=ee.p;ee.p=2;var H=Ar;Ar|=4;try{JU(x,h);var Z=RM,ke=i5(h.containerInfo),Be=Z.focusedElem,nt=Z.selectionRange;if(ke!==Be&&Be&&Be.ownerDocument&&a5(Be.ownerDocument.documentElement,Be)){if(nt!==null&&sA(Be)){var kt=nt.start,Ot=nt.end;if(Ot===void 0&&(Ot=kt),"selectionStart"in Be)Be.selectionStart=kt,Be.selectionEnd=Math.min(Ot,Be.value.length);else{var zt=Be.ownerDocument||document,Tt=zt&&zt.defaultView||window;if(Tt.getSelection){var Et=Tt.getSelection(),pn=Be.textContent.length,jn=Math.min(nt.start,pn),Ur=nt.end===void 0?jn:Math.min(nt.end,pn);!Et.extend&&jn>Ur&&(ke=Ur,Ur=jn,jn=ke);var ft=r5(Be,jn),st=r5(Be,Ur);if(ft&&st&&(Et.rangeCount!==1||Et.anchorNode!==ft.node||Et.anchorOffset!==ft.offset||Et.focusNode!==st.node||Et.focusOffset!==st.offset)){var _t=zt.createRange();_t.setStart(ft.node,ft.offset),Et.removeAllRanges(),jn>Ur?(Et.addRange(_t),Et.extend(st.node,st.offset)):(_t.setEnd(st.node,st.offset),Et.addRange(_t))}}}}for(zt=[],Et=Be;Et=Et.parentNode;)Et.nodeType===1&&zt.push({element:Et,left:Et.scrollLeft,top:Et.scrollTop});for(typeof Be.focus=="function"&&Be.focus(),Be=0;Be<zt.length;Be++){var It=zt[Be];It.element.scrollLeft=It.left,It.element.scrollTop=It.top}}b_=!!FM,RM=FM=null}finally{Ar=H,ee.p=E,ae.T=S}}h.current=x,hi=2}}function vB(){if(hi===2){hi=0;var h=jm,x=Ug,S=(x.flags&8772)!==0;if((x.subtreeFlags&8772)!==0||S){S=ae.T,ae.T=null;var E=ee.p;ee.p=2;var H=Ar;Ar|=4;try{KU(h,x.alternate,x)}finally{Ar=H,ee.p=E,ae.T=S}}hi=3}}function wB(){if(hi===4||hi===3){hi=0,U();var h=jm,x=Ug,S=Jd,E=oB;(x.subtreeFlags&10256)!==0||(x.flags&10256)!==0?hi=5:(hi=0,Ug=jm=null,SB(h,h.pendingLanes));var H=h.pendingLanes;if(H===0&&(Mm=null),en(S),x=x.stateNode,Se&&typeof Se.onCommitFiberRoot=="function")try{Se.onCommitFiberRoot(Ee,x,void 0,(x.current.flags&128)===128)}catch{}if(E!==null){x=ae.T,H=ee.p,ee.p=2,ae.T=null;try{for(var Z=h.onRecoverableError,ke=0;ke<E.length;ke++){var Be=E[ke];Z(Be.value,{componentStack:Be.stack})}}finally{ae.T=x,ee.p=H}}(Jd&3)!==0&&i_(),Xc(h),H=h.pendingLanes,(S&261930)!==0&&(H&42)!==0?h===wM?Xy++:(Xy=0,wM=h):Xy=0,Qy(0)}}function SB(h,x){(h.pooledCacheLanes&=x)===0&&(x=h.pooledCache,x!=null&&(h.pooledCache=null,jy(x)))}function i_(){return yB(),vB(),wB(),_B()}function _B(){if(hi!==5)return!1;var h=jm,x=yM;yM=0;var S=en(Jd),E=ae.T,H=ee.p;try{ee.p=32>S?32:S,ae.T=null,S=vM,vM=null;var Z=jm,ke=Jd;if(hi=0,Ug=jm=null,Jd=0,(Ar&6)!==0)throw Error(r(331));var Be=Ar;if(Ar|=4,aB(Z.current),tB(Z,Z.current,ke,S),Ar=Be,Qy(0,!1),Se&&typeof Se.onPostCommitFiberRoot=="function")try{Se.onPostCommitFiberRoot(Ee,Z)}catch{}return!0}finally{ee.p=H,ae.T=E,SB(h,x)}}function kB(h,x,S){x=fl(S,x),x=JA(h.stateNode,x,2),h=km(h,x,2),h!==null&&(xt(h,2),Xc(h))}function Rr(h,x,S){if(h.tag===3)kB(h,h,S);else for(;x!==null;){if(x.tag===3){kB(x,h,S);break}else if(x.tag===1){var E=x.stateNode;if(typeof x.type.getDerivedStateFromError=="function"||typeof E.componentDidCatch=="function"&&(Mm===null||!Mm.has(E))){h=fl(S,h),S=NU(2),E=km(x,S,2),E!==null&&(CU(S,E,x,h),xt(E,2),Xc(E));break}}x=x.return}}function kM(h,x,S){var E=h.pingCache;if(E===null){E=h.pingCache=new bce;var H=new Set;E.set(x,H)}else H=E.get(x),H===void 0&&(H=new Set,E.set(x,H));H.has(S)||(gM=!0,H.add(S),h=Sce.bind(null,h,x,S),x.then(h,h))}function Sce(h,x,S){var E=h.pingCache;E!==null&&E.delete(x),h.pingedLanes|=h.suspendedLanes&S,h.warmLanes&=~S,Xr===h&&(hr&S)===S&&(Da===4||Da===3&&(hr&62914560)===hr&&300>R()-JS?(Ar&2)===0&&Bg(h,0):bM|=S,zg===hr&&(zg=0)),Xc(h)}function NB(h,x){x===0&&(x=tt()),h=xp(h,x),h!==null&&(xt(h,x),Xc(h))}function _ce(h){var x=h.memoizedState,S=0;x!==null&&(S=x.retryLane),NB(h,S)}function kce(h,x){var S=0;switch(h.tag){case 31:case 13:var E=h.stateNode,H=h.memoizedState;H!==null&&(S=H.retryLane);break;case 19:E=h.stateNode;break;case 22:E=h.stateNode._retryCache;break;default:throw Error(r(314))}E!==null&&E.delete(x),NB(h,S)}function Nce(h,x){return he(h,x)}var s_=null,qg=null,NM=!1,o_=!1,CM=!1,Dm=0;function Xc(h){h!==qg&&h.next===null&&(qg===null?s_=qg=h:qg=qg.next=h),o_=!0,NM||(NM=!0,Pce())}function Qy(h,x){if(!CM&&o_){CM=!0;do for(var S=!1,E=s_;E!==null;){if(h!==0){var H=E.pendingLanes;if(H===0)var Z=0;else{var ke=E.suspendedLanes,Be=E.pingedLanes;Z=(1<<31-qe(42|h)+1)-1,Z&=H&~(ke&~Be),Z=Z&201326741?Z&201326741|1:Z?Z|2:0}Z!==0&&(S=!0,AB(E,Z))}else Z=hr,Z=Pe(E,E===Xr?Z:0,E.cancelPendingCommit!==null||E.timeoutHandle!==-1),(Z&3)===0||Me(E,Z)||(S=!0,AB(E,Z));E=E.next}while(S);CM=!1}}function Cce(){CB()}function CB(){o_=NM=!1;var h=0;Dm!==0&&Oce()&&(h=Dm);for(var x=R(),S=null,E=s_;E!==null;){var H=E.next,Z=PB(E,x);Z===0?(E.next=null,S===null?s_=H:S.next=H,H===null&&(qg=S)):(S=E,(h!==0||(Z&3)!==0)&&(o_=!0)),E=H}hi!==0&&hi!==5||Qy(h),Dm!==0&&(Dm=0)}function PB(h,x){for(var S=h.suspendedLanes,E=h.pingedLanes,H=h.expirationTimes,Z=h.pendingLanes&-62914561;0<Z;){var ke=31-qe(Z),Be=1<<ke,nt=H[ke];nt===-1?((Be&S)===0||(Be&E)!==0)&&(H[ke]=Ve(Be,x)):nt<=x&&(h.expiredLanes|=Be),Z&=~Be}if(x=Xr,S=hr,S=Pe(h,h===x?S:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),E=h.callbackNode,S===0||h===x&&(Fr===2||Fr===9)||h.cancelPendingCommit!==null)return E!==null&&E!==null&&fe(E),h.callbackNode=null,h.callbackPriority=0;if((S&3)===0||Me(h,S)){if(x=S&-S,x===h.callbackPriority)return x;switch(E!==null&&fe(E),en(S)){case 2:case 8:S=we;break;case 32:S=ye;break;case 268435456:S=ve;break;default:S=ye}return E=TB.bind(null,h),S=he(S,E),h.callbackPriority=x,h.callbackNode=S,x}return E!==null&&E!==null&&fe(E),h.callbackPriority=2,h.callbackNode=null,2}function TB(h,x){if(hi!==0&&hi!==5)return h.callbackNode=null,h.callbackPriority=0,null;var S=h.callbackNode;if(i_()&&h.callbackNode!==S)return null;var E=hr;return E=Pe(h,h===Xr?E:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),E===0?null:(cB(h,E,x),PB(h,R()),h.callbackNode!=null&&h.callbackNode===S?TB.bind(null,h):null)}function AB(h,x){if(i_())return null;cB(h,x,!0)}function Pce(){zce(function(){(Ar&6)!==0?he(xe,Cce):CB()})}function PM(){if(Dm===0){var h=Tg;h===0&&(h=ze,ze<<=1,(ze&261888)===0&&(ze=256)),Dm=h}return Dm}function MB(h){return h==null||typeof h=="symbol"||typeof h=="boolean"?null:typeof h=="function"?h:En(""+h)}function jB(h,x){var S=x.ownerDocument.createElement("input");return S.name=x.name,S.value=x.value,h.id&&S.setAttribute("form",h.id),x.parentNode.insertBefore(S,x),h=new FormData(h),S.parentNode.removeChild(S),h}function Tce(h,x,S,E,H){if(x==="submit"&&S&&S.stateNode===H){var Z=MB((H[Mt]||null).action),ke=E.submitter;ke&&(x=(x=ke[Mt]||null)?MB(x.formAction):ke.getAttribute("formAction"),x!==null&&(Z=x,ke=null));var Be=new fs("action","action",null,E,H);h.push({event:Be,listeners:[{instance:null,listener:function(){if(E.defaultPrevented){if(Dm!==0){var nt=ke?jB(H,ke):new FormData(H);WA(S,{pending:!0,data:nt,method:H.method,action:Z},null,nt)}}else typeof Z=="function"&&(Be.preventDefault(),nt=ke?jB(H,ke):new FormData(H),WA(S,{pending:!0,data:nt,method:H.method,action:Z},Z,nt))},currentTarget:H}]})}}for(var TM=0;TM<dA.length;TM++){var AM=dA[TM],Ace=AM.toLowerCase(),Mce=AM[0].toUpperCase()+AM.slice(1);dc(Ace,"on"+Mce)}dc(l5,"onAnimationEnd"),dc(c5,"onAnimationIteration"),dc(d5,"onAnimationStart"),dc("dblclick","onDoubleClick"),dc("focusin","onFocus"),dc("focusout","onBlur"),dc(Gle,"onTransitionRun"),dc(Wle,"onTransitionStart"),dc(Kle,"onTransitionCancel"),dc(u5,"onTransitionEnd"),Pt("onMouseEnter",["mouseout","mouseover"]),Pt("onMouseLeave",["mouseout","mouseover"]),Pt("onPointerEnter",["pointerout","pointerover"]),Pt("onPointerLeave",["pointerout","pointerover"]),bt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),bt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),bt("onBeforeInput",["compositionend","keypress","textInput","paste"]),bt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),bt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),bt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Zy="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(" "),jce=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Zy));function EB(h,x){x=(x&4)!==0;for(var S=0;S<h.length;S++){var E=h[S],H=E.event;E=E.listeners;e:{var Z=void 0;if(x)for(var ke=E.length-1;0<=ke;ke--){var Be=E[ke],nt=Be.instance,kt=Be.currentTarget;if(Be=Be.listener,nt!==Z&&H.isPropagationStopped())break e;Z=Be,H.currentTarget=kt;try{Z(H)}catch(Ot){SS(Ot)}H.currentTarget=null,Z=nt}else for(ke=0;ke<E.length;ke++){if(Be=E[ke],nt=Be.instance,kt=Be.currentTarget,Be=Be.listener,nt!==Z&&H.isPropagationStopped())break e;Z=Be,H.currentTarget=kt;try{Z(H)}catch(Ot){SS(Ot)}H.currentTarget=null,Z=nt}}}}function dr(h,x){var S=x[Wt];S===void 0&&(S=x[Wt]=new Set);var E=h+"__bubble";S.has(E)||(DB(x,h,2,!1),S.add(E))}function MM(h,x,S){var E=0;x&&(E|=4),DB(S,h,E,x)}var l_="_reactListening"+Math.random().toString(36).slice(2);function jM(h){if(!h[l_]){h[l_]=!0,Ze.forEach(function(S){S!=="selectionchange"&&(jce.has(S)||MM(S,!1,h),MM(S,!0,h))});var x=h.nodeType===9?h:h.ownerDocument;x===null||x[l_]||(x[l_]=!0,MM("selectionchange",!1,x))}}function DB(h,x,S,E){switch(l8(x)){case 2:var H=ide;break;case 8:H=sde;break;default:H=GM}S=H.bind(null,x,S,h),H=void 0,!Id||x!=="touchstart"&&x!=="touchmove"&&x!=="wheel"||(H=!0),E?H!==void 0?h.addEventListener(x,S,{capture:!0,passive:H}):h.addEventListener(x,S,!0):H!==void 0?h.addEventListener(x,S,{passive:H}):h.addEventListener(x,S,!1)}function EM(h,x,S,E,H){var Z=E;if((x&1)===0&&(x&2)===0&&E!==null)e:for(;;){if(E===null)return;var ke=E.tag;if(ke===3||ke===4){var Be=E.stateNode.containerInfo;if(Be===H)break;if(ke===4)for(ke=E.return;ke!==null;){var nt=ke.tag;if((nt===3||nt===4)&&ke.stateNode.containerInfo===H)return;ke=ke.return}for(;Be!==null;){if(ke=at(Be),ke===null)return;if(nt=ke.tag,nt===5||nt===6||nt===26||nt===27){E=Z=ke;continue e}Be=Be.parentNode}}E=E.return}Is(function(){var kt=Z,Ot=mm(S),zt=[];e:{var Tt=m5.get(h);if(Tt!==void 0){var Et=fs,pn=h;switch(h){case"keypress":if($i(S)===0)break e;case"keydown":case"keyup":Et=Kn;break;case"focusin":pn="focus",Et=Vc;break;case"focusout":pn="blur",Et=Vc;break;case"beforeblur":case"afterblur":Et=Vc;break;case"click":if(S.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Et=ul;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Et=mp;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Et=xs;break;case l5:case c5:case d5:Et=_y;break;case u5:Et=lc;break;case"scroll":case"scrollend":Et=up;break;case"wheel":Et=_a;break;case"copy":case"cut":case"paste":Et=pp;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Et=Mn;break;case"toggle":case"beforetoggle":Et=cc}var jn=(x&4)!==0,Ur=!jn&&(h==="scroll"||h==="scrollend"),ft=jn?Tt!==null?Tt+"Capture":null:Tt;jn=[];for(var st=kt,_t;st!==null;){var It=st;if(_t=It.stateNode,It=It.tag,It!==5&&It!==26&&It!==27||_t===null||ft===null||(It=ps(st,ft),It!=null&&jn.push(Jy(st,It,_t))),Ur)break;st=st.return}0<jn.length&&(Tt=new Et(Tt,pn,null,S,Ot),zt.push({event:Tt,listeners:jn}))}}if((x&7)===0){e:{if(Tt=h==="mouseover"||h==="pointerover",Et=h==="mouseout"||h==="pointerout",Tt&&S!==sc&&(pn=S.relatedTarget||S.fromElement)&&(at(pn)||pn[Qt]))break e;if((Et||Tt)&&(Tt=Ot.window===Ot?Ot:(Tt=Ot.ownerDocument)?Tt.defaultView||Tt.parentWindow:window,Et?(pn=S.relatedTarget||S.toElement,Et=kt,pn=pn?at(pn):null,pn!==null&&(Ur=s(pn),jn=pn.tag,pn!==Ur||jn!==5&&jn!==27&&jn!==6)&&(pn=null)):(Et=null,pn=kt),Et!==pn)){if(jn=ul,It="onMouseLeave",ft="onMouseEnter",st="mouse",(h==="pointerout"||h==="pointerover")&&(jn=Mn,It="onPointerLeave",ft="onPointerEnter",st="pointer"),Ur=Et==null?Tt:We(Et),_t=pn==null?Tt:We(pn),Tt=new jn(It,st+"leave",Et,S,Ot),Tt.target=Ur,Tt.relatedTarget=_t,It=null,at(Ot)===kt&&(jn=new jn(ft,st+"enter",pn,S,Ot),jn.target=_t,jn.relatedTarget=Ur,It=jn),Ur=It,Et&&pn)t:{for(jn=Ece,ft=Et,st=pn,_t=0,It=ft;It;It=jn(It))_t++;It=0;for(var _n=st;_n;_n=jn(_n))It++;for(;0<_t-It;)ft=jn(ft),_t--;for(;0<It-_t;)st=jn(st),It--;for(;_t--;){if(ft===st||st!==null&&ft===st.alternate){jn=ft;break t}ft=jn(ft),st=jn(st)}jn=null}else jn=null;Et!==null&&FB(zt,Tt,Et,jn,!1),pn!==null&&Ur!==null&&FB(zt,Ur,pn,jn,!0)}}e:{if(Tt=kt?We(kt):window,Et=Tt.nodeName&&Tt.nodeName.toLowerCase(),Et==="select"||Et==="input"&&Tt.type==="file")var kr=Qz;else if(ky(Tt))if(Zz)kr=qle;else{kr=Ble;var gn=Ule}else Et=Tt.nodeName,!Et||Et.toLowerCase()!=="input"||Tt.type!=="checkbox"&&Tt.type!=="radio"?kt&&pa(kt.elementType)&&(kr=Qz):kr=Hle;if(kr&&(kr=kr(h,kt))){Ny(zt,kr,S,Ot);break e}gn&&gn(h,Tt,kt),h==="focusout"&&kt&&Tt.type==="number"&&kt.memoizedProps.value!=null&&na(Tt,"number",Tt.value)}switch(gn=kt?We(kt):window,h){case"focusin":(ky(gn)||gn.contentEditable==="true")&&(vg=gn,oA=kt,Ty=null);break;case"focusout":Ty=oA=vg=null;break;case"mousedown":lA=!0;break;case"contextmenu":case"mouseup":case"dragend":lA=!1,s5(zt,S,Ot);break;case"selectionchange":if(Vle)break;case"keydown":case"keyup":s5(zt,S,Ot)}var Xn;if(Bs)e:{switch(h){case"compositionstart":var pr="onCompositionStart";break e;case"compositionend":pr="onCompositionEnd";break e;case"compositionupdate":pr="onCompositionUpdate";break e}pr=void 0}else Cn?Gc(h,S)&&(pr="onCompositionEnd"):h==="keydown"&&S.keyCode===229&&(pr="onCompositionStart");pr&&(uo&&S.locale!=="ko"&&(Cn||pr!=="onCompositionStart"?pr==="onCompositionEnd"&&Cn&&(Xn=pm()):(lo=Ot,hm="value"in lo?lo.value:lo.textContent,Cn=!0)),gn=c_(kt,pr),0<gn.length&&(pr=new ge(pr,h,null,S,Ot),zt.push({event:pr,listeners:gn}),Xn?pr.data=Xn:(Xn=bm(S),Xn!==null&&(pr.data=Xn)))),(Xn=la?Xz(h,S):vS(h,S))&&(pr=c_(kt,"onBeforeInput"),0<pr.length&&(gn=new ge("onBeforeInput","beforeinput",null,S,Ot),zt.push({event:gn,listeners:pr}),gn.data=Xn)),Tce(zt,h,kt,S,Ot)}EB(zt,x)})}function Jy(h,x,S){return{instance:h,listener:x,currentTarget:S}}function c_(h,x){for(var S=x+"Capture",E=[];h!==null;){var H=h,Z=H.stateNode;if(H=H.tag,H!==5&&H!==26&&H!==27||Z===null||(H=ps(h,S),H!=null&&E.unshift(Jy(h,H,Z)),H=ps(h,x),H!=null&&E.push(Jy(h,H,Z))),h.tag===3)return E;h=h.return}return[]}function Ece(h){if(h===null)return null;do h=h.return;while(h&&h.tag!==5&&h.tag!==27);return h||null}function FB(h,x,S,E,H){for(var Z=x._reactName,ke=[];S!==null&&S!==E;){var Be=S,nt=Be.alternate,kt=Be.stateNode;if(Be=Be.tag,nt!==null&&nt===E)break;Be!==5&&Be!==26&&Be!==27||kt===null||(nt=kt,H?(kt=ps(S,Z),kt!=null&&ke.unshift(Jy(S,kt,nt))):H||(kt=ps(S,Z),kt!=null&&ke.push(Jy(S,kt,nt)))),S=S.return}ke.length!==0&&h.push({event:x,listeners:ke})}var Dce=/\r\n?/g,Fce=/\u0000|\uFFFD/g;function RB(h){return(typeof h=="string"?h:""+h).replace(Dce,`
  9. `).replace(Fce,"")}function LB(h,x){return x=RB(x),RB(h)===x}function zr(h,x,S,E,H,Z){switch(S){case"children":typeof E=="string"?x==="body"||x==="textarea"&&E===""||Bi(h,E):(typeof E=="number"||typeof E=="bigint")&&x!=="body"&&Bi(h,""+E);break;case"className":Jt(h,"class",E);break;case"tabIndex":Jt(h,"tabindex",E);break;case"dir":case"role":case"viewBox":case"width":case"height":Jt(h,S,E);break;case"style":Hc(h,E,Z);break;case"data":if(x!=="object"){Jt(h,"data",E);break}case"src":case"href":if(E===""&&(x!=="a"||S!=="href")){h.removeAttribute(S);break}if(E==null||typeof E=="function"||typeof E=="symbol"||typeof E=="boolean"){h.removeAttribute(S);break}E=En(""+E),h.setAttribute(S,E);break;case"action":case"formAction":if(typeof E=="function"){h.setAttribute(S,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof Z=="function"&&(S==="formAction"?(x!=="input"&&zr(h,x,"name",H.name,H,null),zr(h,x,"formEncType",H.formEncType,H,null),zr(h,x,"formMethod",H.formMethod,H,null),zr(h,x,"formTarget",H.formTarget,H,null)):(zr(h,x,"encType",H.encType,H,null),zr(h,x,"method",H.method,H,null),zr(h,x,"target",H.target,H,null)));if(E==null||typeof E=="symbol"||typeof E=="boolean"){h.removeAttribute(S);break}E=En(""+E),h.setAttribute(S,E);break;case"onClick":E!=null&&(h.onclick=Vt);break;case"onScroll":E!=null&&dr("scroll",h);break;case"onScrollEnd":E!=null&&dr("scrollend",h);break;case"dangerouslySetInnerHTML":if(E!=null){if(typeof E!="object"||!("__html"in E))throw Error(r(61));if(S=E.__html,S!=null){if(H.children!=null)throw Error(r(60));h.innerHTML=S}}break;case"multiple":h.multiple=E&&typeof E!="function"&&typeof E!="symbol";break;case"muted":h.muted=E&&typeof E!="function"&&typeof E!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(E==null||typeof E=="function"||typeof E=="boolean"||typeof E=="symbol"){h.removeAttribute("xlink:href");break}S=En(""+E),h.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",S);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":E!=null&&typeof E!="function"&&typeof E!="symbol"?h.setAttribute(S,""+E):h.removeAttribute(S);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":E&&typeof E!="function"&&typeof E!="symbol"?h.setAttribute(S,""):h.removeAttribute(S);break;case"capture":case"download":E===!0?h.setAttribute(S,""):E!==!1&&E!=null&&typeof E!="function"&&typeof E!="symbol"?h.setAttribute(S,E):h.removeAttribute(S);break;case"cols":case"rows":case"size":case"span":E!=null&&typeof E!="function"&&typeof E!="symbol"&&!isNaN(E)&&1<=E?h.setAttribute(S,E):h.removeAttribute(S);break;case"rowSpan":case"start":E==null||typeof E=="function"||typeof E=="symbol"||isNaN(E)?h.removeAttribute(S):h.setAttribute(S,E);break;case"popover":dr("beforetoggle",h),dr("toggle",h),Zt(h,"popover",E);break;case"xlinkActuate":Nn(h,"http://www.w3.org/1999/xlink","xlink:actuate",E);break;case"xlinkArcrole":Nn(h,"http://www.w3.org/1999/xlink","xlink:arcrole",E);break;case"xlinkRole":Nn(h,"http://www.w3.org/1999/xlink","xlink:role",E);break;case"xlinkShow":Nn(h,"http://www.w3.org/1999/xlink","xlink:show",E);break;case"xlinkTitle":Nn(h,"http://www.w3.org/1999/xlink","xlink:title",E);break;case"xlinkType":Nn(h,"http://www.w3.org/1999/xlink","xlink:type",E);break;case"xmlBase":Nn(h,"http://www.w3.org/XML/1998/namespace","xml:base",E);break;case"xmlLang":Nn(h,"http://www.w3.org/XML/1998/namespace","xml:lang",E);break;case"xmlSpace":Nn(h,"http://www.w3.org/XML/1998/namespace","xml:space",E);break;case"is":Zt(h,"is",E);break;case"innerText":case"textContent":break;default:(!(2<S.length)||S[0]!=="o"&&S[0]!=="O"||S[1]!=="n"&&S[1]!=="N")&&(S=jt.get(S)||S,Zt(h,S,E))}}function DM(h,x,S,E,H,Z){switch(S){case"style":Hc(h,E,Z);break;case"dangerouslySetInnerHTML":if(E!=null){if(typeof E!="object"||!("__html"in E))throw Error(r(61));if(S=E.__html,S!=null){if(H.children!=null)throw Error(r(60));h.innerHTML=S}}break;case"children":typeof E=="string"?Bi(h,E):(typeof E=="number"||typeof E=="bigint")&&Bi(h,""+E);break;case"onScroll":E!=null&&dr("scroll",h);break;case"onScrollEnd":E!=null&&dr("scrollend",h);break;case"onClick":E!=null&&(h.onclick=Vt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!rt.hasOwnProperty(S))e:{if(S[0]==="o"&&S[1]==="n"&&(H=S.endsWith("Capture"),x=S.slice(2,H?S.length-7:void 0),Z=h[Mt]||null,Z=Z!=null?Z[S]:null,typeof Z=="function"&&h.removeEventListener(x,Z,H),typeof E=="function")){typeof Z!="function"&&Z!==null&&(S in h?h[S]=null:h.hasAttribute(S)&&h.removeAttribute(S)),h.addEventListener(x,E,H);break e}S in h?h[S]=E:E===!0?h.setAttribute(S,""):Zt(h,S,E)}}}function Yi(h,x,S){switch(x){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":dr("error",h),dr("load",h);var E=!1,H=!1,Z;for(Z in S)if(S.hasOwnProperty(Z)){var ke=S[Z];if(ke!=null)switch(Z){case"src":E=!0;break;case"srcSet":H=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,x));default:zr(h,x,Z,ke,S,null)}}H&&zr(h,x,"srcSet",S.srcSet,S,null),E&&zr(h,x,"src",S.src,S,null);return;case"input":dr("invalid",h);var Be=Z=ke=H=null,nt=null,kt=null;for(E in S)if(S.hasOwnProperty(E)){var Ot=S[E];if(Ot!=null)switch(E){case"name":H=Ot;break;case"type":ke=Ot;break;case"checked":nt=Ot;break;case"defaultChecked":kt=Ot;break;case"value":Z=Ot;break;case"defaultValue":Be=Ot;break;case"children":case"dangerouslySetInnerHTML":if(Ot!=null)throw Error(r(137,x));break;default:zr(h,x,E,Ot,S,null)}}Rn(h,Z,Be,nt,kt,ke,H,!1);return;case"select":dr("invalid",h),E=ke=Z=null;for(H in S)if(S.hasOwnProperty(H)&&(Be=S[H],Be!=null))switch(H){case"value":Z=Be;break;case"defaultValue":ke=Be;break;case"multiple":E=Be;default:zr(h,x,H,Be,S,null)}x=Z,S=ke,h.multiple=!!E,x!=null?ra(h,!!E,x,!1):S!=null&&ra(h,!!E,S,!0);return;case"textarea":dr("invalid",h),Z=H=E=null;for(ke in S)if(S.hasOwnProperty(ke)&&(Be=S[ke],Be!=null))switch(ke){case"value":E=Be;break;case"defaultValue":H=Be;break;case"children":Z=Be;break;case"dangerouslySetInnerHTML":if(Be!=null)throw Error(r(91));break;default:zr(h,x,ke,Be,S,null)}In(h,E,H,Z);return;case"option":for(nt in S)S.hasOwnProperty(nt)&&(E=S[nt],E!=null)&&(nt==="selected"?h.selected=E&&typeof E!="function"&&typeof E!="symbol":zr(h,x,nt,E,S,null));return;case"dialog":dr("beforetoggle",h),dr("toggle",h),dr("cancel",h),dr("close",h);break;case"iframe":case"object":dr("load",h);break;case"video":case"audio":for(E=0;E<Zy.length;E++)dr(Zy[E],h);break;case"image":dr("error",h),dr("load",h);break;case"details":dr("toggle",h);break;case"embed":case"source":case"link":dr("error",h),dr("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(kt in S)if(S.hasOwnProperty(kt)&&(E=S[kt],E!=null))switch(kt){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,x));default:zr(h,x,kt,E,S,null)}return;default:if(pa(x)){for(Ot in S)S.hasOwnProperty(Ot)&&(E=S[Ot],E!==void 0&&DM(h,x,Ot,E,S,void 0));return}}for(Be in S)S.hasOwnProperty(Be)&&(E=S[Be],E!=null&&zr(h,x,Be,E,S,null))}function Rce(h,x,S,E){switch(x){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var H=null,Z=null,ke=null,Be=null,nt=null,kt=null,Ot=null;for(Et in S){var zt=S[Et];if(S.hasOwnProperty(Et)&&zt!=null)switch(Et){case"checked":break;case"value":break;case"defaultValue":nt=zt;default:E.hasOwnProperty(Et)||zr(h,x,Et,null,E,zt)}}for(var Tt in E){var Et=E[Tt];if(zt=S[Tt],E.hasOwnProperty(Tt)&&(Et!=null||zt!=null))switch(Tt){case"type":Z=Et;break;case"name":H=Et;break;case"checked":kt=Et;break;case"defaultChecked":Ot=Et;break;case"value":ke=Et;break;case"defaultValue":Be=Et;break;case"children":case"dangerouslySetInnerHTML":if(Et!=null)throw Error(r(137,x));break;default:Et!==zt&&zr(h,x,Tt,Et,E,zt)}}mi(h,ke,Be,nt,kt,Ot,Z,H);return;case"select":Et=ke=Be=Tt=null;for(Z in S)if(nt=S[Z],S.hasOwnProperty(Z)&&nt!=null)switch(Z){case"value":break;case"multiple":Et=nt;default:E.hasOwnProperty(Z)||zr(h,x,Z,null,E,nt)}for(H in E)if(Z=E[H],nt=S[H],E.hasOwnProperty(H)&&(Z!=null||nt!=null))switch(H){case"value":Tt=Z;break;case"defaultValue":Be=Z;break;case"multiple":ke=Z;default:Z!==nt&&zr(h,x,H,Z,E,nt)}x=Be,S=ke,E=Et,Tt!=null?ra(h,!!S,Tt,!1):!!E!=!!S&&(x!=null?ra(h,!!S,x,!0):ra(h,!!S,S?[]:"",!1));return;case"textarea":Et=Tt=null;for(Be in S)if(H=S[Be],S.hasOwnProperty(Be)&&H!=null&&!E.hasOwnProperty(Be))switch(Be){case"value":break;case"children":break;default:zr(h,x,Be,null,E,H)}for(ke in E)if(H=E[ke],Z=S[ke],E.hasOwnProperty(ke)&&(H!=null||Z!=null))switch(ke){case"value":Tt=H;break;case"defaultValue":Et=H;break;case"children":break;case"dangerouslySetInnerHTML":if(H!=null)throw Error(r(91));break;default:H!==Z&&zr(h,x,ke,H,E,Z)}jr(h,Tt,Et);return;case"option":for(var pn in S)Tt=S[pn],S.hasOwnProperty(pn)&&Tt!=null&&!E.hasOwnProperty(pn)&&(pn==="selected"?h.selected=!1:zr(h,x,pn,null,E,Tt));for(nt in E)Tt=E[nt],Et=S[nt],E.hasOwnProperty(nt)&&Tt!==Et&&(Tt!=null||Et!=null)&&(nt==="selected"?h.selected=Tt&&typeof Tt!="function"&&typeof Tt!="symbol":zr(h,x,nt,Tt,E,Et));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 jn in S)Tt=S[jn],S.hasOwnProperty(jn)&&Tt!=null&&!E.hasOwnProperty(jn)&&zr(h,x,jn,null,E,Tt);for(kt in E)if(Tt=E[kt],Et=S[kt],E.hasOwnProperty(kt)&&Tt!==Et&&(Tt!=null||Et!=null))switch(kt){case"children":case"dangerouslySetInnerHTML":if(Tt!=null)throw Error(r(137,x));break;default:zr(h,x,kt,Tt,E,Et)}return;default:if(pa(x)){for(var Ur in S)Tt=S[Ur],S.hasOwnProperty(Ur)&&Tt!==void 0&&!E.hasOwnProperty(Ur)&&DM(h,x,Ur,void 0,E,Tt);for(Ot in E)Tt=E[Ot],Et=S[Ot],!E.hasOwnProperty(Ot)||Tt===Et||Tt===void 0&&Et===void 0||DM(h,x,Ot,Tt,E,Et);return}}for(var ft in S)Tt=S[ft],S.hasOwnProperty(ft)&&Tt!=null&&!E.hasOwnProperty(ft)&&zr(h,x,ft,null,E,Tt);for(zt in E)Tt=E[zt],Et=S[zt],!E.hasOwnProperty(zt)||Tt===Et||Tt==null&&Et==null||zr(h,x,zt,Tt,E,Et)}function OB(h){switch(h){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Lce(){if(typeof performance.getEntriesByType=="function"){for(var h=0,x=0,S=performance.getEntriesByType("resource"),E=0;E<S.length;E++){var H=S[E],Z=H.transferSize,ke=H.initiatorType,Be=H.duration;if(Z&&Be&&OB(ke)){for(ke=0,Be=H.responseEnd,E+=1;E<S.length;E++){var nt=S[E],kt=nt.startTime;if(kt>Be)break;var Ot=nt.transferSize,zt=nt.initiatorType;Ot&&OB(zt)&&(nt=nt.responseEnd,ke+=Ot*(nt<Be?1:(Be-kt)/(nt-kt)))}if(--E,x+=8*(Z+ke)/(H.duration/1e3),h++,10<h)break}}if(0<h)return x/h/1e6}return navigator.connection&&(h=navigator.connection.downlink,typeof h=="number")?h:5}var FM=null,RM=null;function d_(h){return h.nodeType===9?h:h.ownerDocument}function IB(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 zB(h,x){if(h===0)switch(x){case"svg":return 1;case"math":return 2;default:return 0}return h===1&&x==="foreignObject"?0:h}function LM(h,x){return h==="textarea"||h==="noscript"||typeof x.children=="string"||typeof x.children=="number"||typeof x.children=="bigint"||typeof x.dangerouslySetInnerHTML=="object"&&x.dangerouslySetInnerHTML!==null&&x.dangerouslySetInnerHTML.__html!=null}var OM=null;function Oce(){var h=window.event;return h&&h.type==="popstate"?h===OM?!1:(OM=h,!0):(OM=null,!1)}var UB=typeof setTimeout=="function"?setTimeout:void 0,Ice=typeof clearTimeout=="function"?clearTimeout:void 0,BB=typeof Promise=="function"?Promise:void 0,zce=typeof queueMicrotask=="function"?queueMicrotask:typeof BB<"u"?function(h){return BB.resolve(null).then(h).catch(Uce)}:UB;function Uce(h){setTimeout(function(){throw h})}function Fm(h){return h==="head"}function HB(h,x){var S=x,E=0;do{var H=S.nextSibling;if(h.removeChild(S),H&&H.nodeType===8)if(S=H.data,S==="/$"||S==="/&"){if(E===0){h.removeChild(H),Wg(x);return}E--}else if(S==="$"||S==="$?"||S==="$~"||S==="$!"||S==="&")E++;else if(S==="html")ev(h.ownerDocument.documentElement);else if(S==="head"){S=h.ownerDocument.head,ev(S);for(var Z=S.firstChild;Z;){var ke=Z.nextSibling,Be=Z.nodeName;Z[De]||Be==="SCRIPT"||Be==="STYLE"||Be==="LINK"&&Z.rel.toLowerCase()==="stylesheet"||S.removeChild(Z),Z=ke}}else S==="body"&&ev(h.ownerDocument.body);S=H}while(S);Wg(x)}function qB(h,x){var S=h;h=0;do{var E=S.nextSibling;if(S.nodeType===1?x?(S._stashedDisplay=S.style.display,S.style.display="none"):(S.style.display=S._stashedDisplay||"",S.getAttribute("style")===""&&S.removeAttribute("style")):S.nodeType===3&&(x?(S._stashedText=S.nodeValue,S.nodeValue=""):S.nodeValue=S._stashedText||""),E&&E.nodeType===8)if(S=E.data,S==="/$"){if(h===0)break;h--}else S!=="$"&&S!=="$?"&&S!=="$~"&&S!=="$!"||h++;S=E}while(S)}function IM(h){var x=h.firstChild;for(x&&x.nodeType===10&&(x=x.nextSibling);x;){var S=x;switch(x=x.nextSibling,S.nodeName){case"HTML":case"HEAD":case"BODY":IM(S),Le(S);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(S.rel.toLowerCase()==="stylesheet")continue}h.removeChild(S)}}function Bce(h,x,S,E){for(;h.nodeType===1;){var H=S;if(h.nodeName.toLowerCase()!==x.toLowerCase()){if(!E&&(h.nodeName!=="INPUT"||h.type!=="hidden"))break}else if(E){if(!h[De])switch(x){case"meta":if(!h.hasAttribute("itemprop"))break;return h;case"link":if(Z=h.getAttribute("rel"),Z==="stylesheet"&&h.hasAttribute("data-precedence"))break;if(Z!==H.rel||h.getAttribute("href")!==(H.href==null||H.href===""?null:H.href)||h.getAttribute("crossorigin")!==(H.crossOrigin==null?null:H.crossOrigin)||h.getAttribute("title")!==(H.title==null?null:H.title))break;return h;case"style":if(h.hasAttribute("data-precedence"))break;return h;case"script":if(Z=h.getAttribute("src"),(Z!==(H.src==null?null:H.src)||h.getAttribute("type")!==(H.type==null?null:H.type)||h.getAttribute("crossorigin")!==(H.crossOrigin==null?null:H.crossOrigin))&&Z&&h.hasAttribute("async")&&!h.hasAttribute("itemprop"))break;return h;default:return h}}else if(x==="input"&&h.type==="hidden"){var Z=H.name==null?null:""+H.name;if(H.type==="hidden"&&h.getAttribute("name")===Z)return h}else return h;if(h=vl(h.nextSibling),h===null)break}return null}function Hce(h,x,S){if(x==="")return null;for(;h.nodeType!==3;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!S||(h=vl(h.nextSibling),h===null))return null;return h}function $B(h,x){for(;h.nodeType!==8;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!x||(h=vl(h.nextSibling),h===null))return null;return h}function zM(h){return h.data==="$?"||h.data==="$~"}function UM(h){return h.data==="$!"||h.data==="$?"&&h.ownerDocument.readyState!=="loading"}function qce(h,x){var S=h.ownerDocument;if(h.data==="$~")h._reactRetry=x;else if(h.data!=="$?"||S.readyState!=="loading")x();else{var E=function(){x(),S.removeEventListener("DOMContentLoaded",E)};S.addEventListener("DOMContentLoaded",E),h._reactRetry=E}}function vl(h){for(;h!=null;h=h.nextSibling){var x=h.nodeType;if(x===1||x===3)break;if(x===8){if(x=h.data,x==="$"||x==="$!"||x==="$?"||x==="$~"||x==="&"||x==="F!"||x==="F")break;if(x==="/$"||x==="/&")return null}}return h}var BM=null;function VB(h){h=h.nextSibling;for(var x=0;h;){if(h.nodeType===8){var S=h.data;if(S==="/$"||S==="/&"){if(x===0)return vl(h.nextSibling);x--}else S!=="$"&&S!=="$!"&&S!=="$?"&&S!=="$~"&&S!=="&"||x++}h=h.nextSibling}return null}function GB(h){h=h.previousSibling;for(var x=0;h;){if(h.nodeType===8){var S=h.data;if(S==="$"||S==="$!"||S==="$?"||S==="$~"||S==="&"){if(x===0)return h;x--}else S!=="/$"&&S!=="/&"||x++}h=h.previousSibling}return null}function WB(h,x,S){switch(x=d_(S),h){case"html":if(h=x.documentElement,!h)throw Error(r(452));return h;case"head":if(h=x.head,!h)throw Error(r(453));return h;case"body":if(h=x.body,!h)throw Error(r(454));return h;default:throw Error(r(451))}}function ev(h){for(var x=h.attributes;x.length;)h.removeAttributeNode(x[0]);Le(h)}var wl=new Map,KB=new Set;function u_(h){return typeof h.getRootNode=="function"?h.getRootNode():h.nodeType===9?h:h.ownerDocument}var eu=ee.d;ee.d={f:$ce,r:Vce,D:Gce,C:Wce,L:Kce,m:Yce,X:Qce,S:Xce,M:Zce};function $ce(){var h=eu.f(),x=n_();return h||x}function Vce(h){var x=Ce(h);x!==null&&x.tag===5&&x.type==="form"?uU(x):eu.r(h)}var $g=typeof document>"u"?null:document;function YB(h,x,S){var E=$g;if(E&&typeof x=="string"&&x){var H=On(x);H='link[rel="'+h+'"][href="'+H+'"]',typeof S=="string"&&(H+='[crossorigin="'+S+'"]'),KB.has(H)||(KB.add(H),h={rel:h,crossOrigin:S,href:x},E.querySelector(H)===null&&(x=E.createElement("link"),Yi(x,"link",h),Qe(x),E.head.appendChild(x)))}}function Gce(h){eu.D(h),YB("dns-prefetch",h,null)}function Wce(h,x){eu.C(h,x),YB("preconnect",h,x)}function Kce(h,x,S){eu.L(h,x,S);var E=$g;if(E&&h&&x){var H='link[rel="preload"][as="'+On(x)+'"]';x==="image"&&S&&S.imageSrcSet?(H+='[imagesrcset="'+On(S.imageSrcSet)+'"]',typeof S.imageSizes=="string"&&(H+='[imagesizes="'+On(S.imageSizes)+'"]')):H+='[href="'+On(h)+'"]';var Z=H;switch(x){case"style":Z=Vg(h);break;case"script":Z=Gg(h)}wl.has(Z)||(h=m({rel:"preload",href:x==="image"&&S&&S.imageSrcSet?void 0:h,as:x},S),wl.set(Z,h),E.querySelector(H)!==null||x==="style"&&E.querySelector(tv(Z))||x==="script"&&E.querySelector(nv(Z))||(x=E.createElement("link"),Yi(x,"link",h),Qe(x),E.head.appendChild(x)))}}function Yce(h,x){eu.m(h,x);var S=$g;if(S&&h){var E=x&&typeof x.as=="string"?x.as:"script",H='link[rel="modulepreload"][as="'+On(E)+'"][href="'+On(h)+'"]',Z=H;switch(E){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":Z=Gg(h)}if(!wl.has(Z)&&(h=m({rel:"modulepreload",href:h},x),wl.set(Z,h),S.querySelector(H)===null)){switch(E){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(S.querySelector(nv(Z)))return}E=S.createElement("link"),Yi(E,"link",h),Qe(E),S.head.appendChild(E)}}}function Xce(h,x,S){eu.S(h,x,S);var E=$g;if(E&&h){var H=Xe(E).hoistableStyles,Z=Vg(h);x=x||"default";var ke=H.get(Z);if(!ke){var Be={loading:0,preload:null};if(ke=E.querySelector(tv(Z)))Be.loading=5;else{h=m({rel:"stylesheet",href:h,"data-precedence":x},S),(S=wl.get(Z))&&HM(h,S);var nt=ke=E.createElement("link");Qe(nt),Yi(nt,"link",h),nt._p=new Promise(function(kt,Ot){nt.onload=kt,nt.onerror=Ot}),nt.addEventListener("load",function(){Be.loading|=1}),nt.addEventListener("error",function(){Be.loading|=2}),Be.loading|=4,m_(ke,x,E)}ke={type:"stylesheet",instance:ke,count:1,state:Be},H.set(Z,ke)}}}function Qce(h,x){eu.X(h,x);var S=$g;if(S&&h){var E=Xe(S).hoistableScripts,H=Gg(h),Z=E.get(H);Z||(Z=S.querySelector(nv(H)),Z||(h=m({src:h,async:!0},x),(x=wl.get(H))&&qM(h,x),Z=S.createElement("script"),Qe(Z),Yi(Z,"link",h),S.head.appendChild(Z)),Z={type:"script",instance:Z,count:1,state:null},E.set(H,Z))}}function Zce(h,x){eu.M(h,x);var S=$g;if(S&&h){var E=Xe(S).hoistableScripts,H=Gg(h),Z=E.get(H);Z||(Z=S.querySelector(nv(H)),Z||(h=m({src:h,async:!0,type:"module"},x),(x=wl.get(H))&&qM(h,x),Z=S.createElement("script"),Qe(Z),Yi(Z,"link",h),S.head.appendChild(Z)),Z={type:"script",instance:Z,count:1,state:null},E.set(H,Z))}}function XB(h,x,S,E){var H=(H=B.current)?u_(H):null;if(!H)throw Error(r(446));switch(h){case"meta":case"title":return null;case"style":return typeof S.precedence=="string"&&typeof S.href=="string"?(x=Vg(S.href),S=Xe(H).hoistableStyles,E=S.get(x),E||(E={type:"style",instance:null,count:0,state:null},S.set(x,E)),E):{type:"void",instance:null,count:0,state:null};case"link":if(S.rel==="stylesheet"&&typeof S.href=="string"&&typeof S.precedence=="string"){h=Vg(S.href);var Z=Xe(H).hoistableStyles,ke=Z.get(h);if(ke||(H=H.ownerDocument||H,ke={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},Z.set(h,ke),(Z=H.querySelector(tv(h)))&&!Z._p&&(ke.instance=Z,ke.state.loading=5),wl.has(h)||(S={rel:"preload",as:"style",href:S.href,crossOrigin:S.crossOrigin,integrity:S.integrity,media:S.media,hrefLang:S.hrefLang,referrerPolicy:S.referrerPolicy},wl.set(h,S),Z||Jce(H,h,S,ke.state))),x&&E===null)throw Error(r(528,""));return ke}if(x&&E!==null)throw Error(r(529,""));return null;case"script":return x=S.async,S=S.src,typeof S=="string"&&x&&typeof x!="function"&&typeof x!="symbol"?(x=Gg(S),S=Xe(H).hoistableScripts,E=S.get(x),E||(E={type:"script",instance:null,count:0,state:null},S.set(x,E)),E):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,h))}}function Vg(h){return'href="'+On(h)+'"'}function tv(h){return'link[rel="stylesheet"]['+h+"]"}function QB(h){return m({},h,{"data-precedence":h.precedence,precedence:null})}function Jce(h,x,S,E){h.querySelector('link[rel="preload"][as="style"]['+x+"]")?E.loading=1:(x=h.createElement("link"),E.preload=x,x.addEventListener("load",function(){return E.loading|=1}),x.addEventListener("error",function(){return E.loading|=2}),Yi(x,"link",S),Qe(x),h.head.appendChild(x))}function Gg(h){return'[src="'+On(h)+'"]'}function nv(h){return"script[async]"+h}function ZB(h,x,S){if(x.count++,x.instance===null)switch(x.type){case"style":var E=h.querySelector('style[data-href~="'+On(S.href)+'"]');if(E)return x.instance=E,Qe(E),E;var H=m({},S,{"data-href":S.href,"data-precedence":S.precedence,href:null,precedence:null});return E=(h.ownerDocument||h).createElement("style"),Qe(E),Yi(E,"style",H),m_(E,S.precedence,h),x.instance=E;case"stylesheet":H=Vg(S.href);var Z=h.querySelector(tv(H));if(Z)return x.state.loading|=4,x.instance=Z,Qe(Z),Z;E=QB(S),(H=wl.get(H))&&HM(E,H),Z=(h.ownerDocument||h).createElement("link"),Qe(Z);var ke=Z;return ke._p=new Promise(function(Be,nt){ke.onload=Be,ke.onerror=nt}),Yi(Z,"link",E),x.state.loading|=4,m_(Z,S.precedence,h),x.instance=Z;case"script":return Z=Gg(S.src),(H=h.querySelector(nv(Z)))?(x.instance=H,Qe(H),H):(E=S,(H=wl.get(Z))&&(E=m({},S),qM(E,H)),h=h.ownerDocument||h,H=h.createElement("script"),Qe(H),Yi(H,"link",E),h.head.appendChild(H),x.instance=H);case"void":return null;default:throw Error(r(443,x.type))}else x.type==="stylesheet"&&(x.state.loading&4)===0&&(E=x.instance,x.state.loading|=4,m_(E,S.precedence,h));return x.instance}function m_(h,x,S){for(var E=S.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),H=E.length?E[E.length-1]:null,Z=H,ke=0;ke<E.length;ke++){var Be=E[ke];if(Be.dataset.precedence===x)Z=Be;else if(Z!==H)break}Z?Z.parentNode.insertBefore(h,Z.nextSibling):(x=S.nodeType===9?S.head:S,x.insertBefore(h,x.firstChild))}function HM(h,x){h.crossOrigin==null&&(h.crossOrigin=x.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=x.referrerPolicy),h.title==null&&(h.title=x.title)}function qM(h,x){h.crossOrigin==null&&(h.crossOrigin=x.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=x.referrerPolicy),h.integrity==null&&(h.integrity=x.integrity)}var h_=null;function JB(h,x,S){if(h_===null){var E=new Map,H=h_=new Map;H.set(S,E)}else H=h_,E=H.get(S),E||(E=new Map,H.set(S,E));if(E.has(h))return E;for(E.set(h,null),S=S.getElementsByTagName(h),H=0;H<S.length;H++){var Z=S[H];if(!(Z[De]||Z[ht]||h==="link"&&Z.getAttribute("rel")==="stylesheet")&&Z.namespaceURI!=="http://www.w3.org/2000/svg"){var ke=Z.getAttribute(x)||"";ke=h+ke;var Be=E.get(ke);Be?Be.push(Z):E.set(ke,[Z])}}return E}function e8(h,x,S){h=h.ownerDocument||h,h.head.insertBefore(S,x==="title"?h.querySelector("head > title"):null)}function ede(h,x,S){if(S===1||x.itemProp!=null)return!1;switch(h){case"meta":case"title":return!0;case"style":if(typeof x.precedence!="string"||typeof x.href!="string"||x.href==="")break;return!0;case"link":if(typeof x.rel!="string"||typeof x.href!="string"||x.href===""||x.onLoad||x.onError)break;return x.rel==="stylesheet"?(h=x.disabled,typeof x.precedence=="string"&&h==null):!0;case"script":if(x.async&&typeof x.async!="function"&&typeof x.async!="symbol"&&!x.onLoad&&!x.onError&&x.src&&typeof x.src=="string")return!0}return!1}function t8(h){return!(h.type==="stylesheet"&&(h.state.loading&3)===0)}function tde(h,x,S,E){if(S.type==="stylesheet"&&(typeof E.media!="string"||matchMedia(E.media).matches!==!1)&&(S.state.loading&4)===0){if(S.instance===null){var H=Vg(E.href),Z=x.querySelector(tv(H));if(Z){x=Z._p,x!==null&&typeof x=="object"&&typeof x.then=="function"&&(h.count++,h=p_.bind(h),x.then(h,h)),S.state.loading|=4,S.instance=Z,Qe(Z);return}Z=x.ownerDocument||x,E=QB(E),(H=wl.get(H))&&HM(E,H),Z=Z.createElement("link"),Qe(Z);var ke=Z;ke._p=new Promise(function(Be,nt){ke.onload=Be,ke.onerror=nt}),Yi(Z,"link",E),S.instance=Z}h.stylesheets===null&&(h.stylesheets=new Map),h.stylesheets.set(S,x),(x=S.state.preload)&&(S.state.loading&3)===0&&(h.count++,S=p_.bind(h),x.addEventListener("load",S),x.addEventListener("error",S))}}var $M=0;function nde(h,x){return h.stylesheets&&h.count===0&&g_(h,h.stylesheets),0<h.count||0<h.imgCount?function(S){var E=setTimeout(function(){if(h.stylesheets&&g_(h,h.stylesheets),h.unsuspend){var Z=h.unsuspend;h.unsuspend=null,Z()}},6e4+x);0<h.imgBytes&&$M===0&&($M=62500*Lce());var H=setTimeout(function(){if(h.waitingForImages=!1,h.count===0&&(h.stylesheets&&g_(h,h.stylesheets),h.unsuspend)){var Z=h.unsuspend;h.unsuspend=null,Z()}},(h.imgBytes>$M?50:800)+x);return h.unsuspend=S,function(){h.unsuspend=null,clearTimeout(E),clearTimeout(H)}}:null}function p_(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)g_(this,this.stylesheets);else if(this.unsuspend){var h=this.unsuspend;this.unsuspend=null,h()}}}var f_=null;function g_(h,x){h.stylesheets=null,h.unsuspend!==null&&(h.count++,f_=new Map,x.forEach(rde,h),f_=null,p_.call(h))}function rde(h,x){if(!(x.state.loading&4)){var S=f_.get(h);if(S)var E=S.get(null);else{S=new Map,f_.set(h,S);for(var H=h.querySelectorAll("link[data-precedence],style[data-precedence]"),Z=0;Z<H.length;Z++){var ke=H[Z];(ke.nodeName==="LINK"||ke.getAttribute("media")!=="not all")&&(S.set(ke.dataset.precedence,ke),E=ke)}E&&S.set(null,E)}H=x.instance,ke=H.getAttribute("data-precedence"),Z=S.get(ke)||E,Z===E&&S.set(null,H),S.set(ke,H),this.count++,E=p_.bind(this),H.addEventListener("load",E),H.addEventListener("error",E),Z?Z.parentNode.insertBefore(H,Z.nextSibling):(h=h.nodeType===9?h.head:h,h.insertBefore(H,h.firstChild)),x.state.loading|=4}}var rv={$$typeof:k,Provider:null,Consumer:null,_currentValue:me,_currentValue2:me,_threadCount:0};function ade(h,x,S,E,H,Z,ke,Be,nt){this.tag=1,this.containerInfo=h,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ut(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ut(0),this.hiddenUpdates=ut(null),this.identifierPrefix=E,this.onUncaughtError=H,this.onCaughtError=Z,this.onRecoverableError=ke,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=nt,this.incompleteTransitions=new Map}function n8(h,x,S,E,H,Z,ke,Be,nt,kt,Ot,zt){return h=new ade(h,x,S,ke,nt,kt,Ot,zt,Be),x=1,Z===!0&&(x|=24),Z=Uo(3,null,null,x),h.current=Z,Z.stateNode=h,x=_A(),x.refCount++,h.pooledCache=x,x.refCount++,Z.memoizedState={element:E,isDehydrated:S,cache:x},PA(Z),h}function r8(h){return h?(h=_g,h):_g}function a8(h,x,S,E,H,Z){H=r8(H),E.context===null?E.context=H:E.pendingContext=H,E=_m(x),E.payload={element:S},Z=Z===void 0?null:Z,Z!==null&&(E.callback=Z),S=km(h,E,x),S!==null&&(go(S,h,x),Ry(S,h,x))}function i8(h,x){if(h=h.memoizedState,h!==null&&h.dehydrated!==null){var S=h.retryLane;h.retryLane=S!==0&&S<x?S:x}}function VM(h,x){i8(h,x),(h=h.alternate)&&i8(h,x)}function s8(h){if(h.tag===13||h.tag===31){var x=xp(h,67108864);x!==null&&go(x,h,67108864),VM(h,67108864)}}function o8(h){if(h.tag===13||h.tag===31){var x=Vo();x=Ut(x);var S=xp(h,x);S!==null&&go(S,h,x),VM(h,x)}}var b_=!0;function ide(h,x,S,E){var H=ae.T;ae.T=null;var Z=ee.p;try{ee.p=2,GM(h,x,S,E)}finally{ee.p=Z,ae.T=H}}function sde(h,x,S,E){var H=ae.T;ae.T=null;var Z=ee.p;try{ee.p=8,GM(h,x,S,E)}finally{ee.p=Z,ae.T=H}}function GM(h,x,S,E){if(b_){var H=WM(E);if(H===null)EM(h,x,E,x_,S),c8(h,E);else if(lde(H,h,x,S,E))E.stopPropagation();else if(c8(h,E),x&4&&-1<ode.indexOf(h)){for(;H!==null;){var Z=Ce(H);if(Z!==null)switch(Z.tag){case 3:if(Z=Z.stateNode,Z.current.memoizedState.isDehydrated){var ke=$e(Z.pendingLanes);if(ke!==0){var Be=Z;for(Be.pendingLanes|=2,Be.entangledLanes|=2;ke;){var nt=1<<31-qe(ke);Be.entanglements[1]|=nt,ke&=~nt}Xc(Z),(Ar&6)===0&&(e_=R()+500,Qy(0))}}break;case 31:case 13:Be=xp(Z,2),Be!==null&&go(Be,Z,2),n_(),VM(Z,2)}if(Z=WM(E),Z===null&&EM(h,x,E,x_,S),Z===H)break;H=Z}H!==null&&E.stopPropagation()}else EM(h,x,E,null,S)}}function WM(h){return h=mm(h),KM(h)}var x_=null;function KM(h){if(x_=null,h=at(h),h!==null){var x=s(h);if(x===null)h=null;else{var S=x.tag;if(S===13){if(h=o(x),h!==null)return h;h=null}else if(S===31){if(h=l(x),h!==null)return h;h=null}else if(S===3){if(x.stateNode.current.memoizedState.isDehydrated)return x.tag===3?x.stateNode.containerInfo:null;h=null}else x!==h&&(h=null)}}return x_=h,null}function l8(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 xe:return 2;case we:return 8;case ye:case Ae:return 32;case ve:return 268435456;default:return 32}default:return 32}}var YM=!1,Rm=null,Lm=null,Om=null,av=new Map,iv=new Map,Im=[],ode="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 c8(h,x){switch(h){case"focusin":case"focusout":Rm=null;break;case"dragenter":case"dragleave":Lm=null;break;case"mouseover":case"mouseout":Om=null;break;case"pointerover":case"pointerout":av.delete(x.pointerId);break;case"gotpointercapture":case"lostpointercapture":iv.delete(x.pointerId)}}function sv(h,x,S,E,H,Z){return h===null||h.nativeEvent!==Z?(h={blockedOn:x,domEventName:S,eventSystemFlags:E,nativeEvent:Z,targetContainers:[H]},x!==null&&(x=Ce(x),x!==null&&s8(x)),h):(h.eventSystemFlags|=E,x=h.targetContainers,H!==null&&x.indexOf(H)===-1&&x.push(H),h)}function lde(h,x,S,E,H){switch(x){case"focusin":return Rm=sv(Rm,h,x,S,E,H),!0;case"dragenter":return Lm=sv(Lm,h,x,S,E,H),!0;case"mouseover":return Om=sv(Om,h,x,S,E,H),!0;case"pointerover":var Z=H.pointerId;return av.set(Z,sv(av.get(Z)||null,h,x,S,E,H)),!0;case"gotpointercapture":return Z=H.pointerId,iv.set(Z,sv(iv.get(Z)||null,h,x,S,E,H)),!0}return!1}function d8(h){var x=at(h.target);if(x!==null){var S=s(x);if(S!==null){if(x=S.tag,x===13){if(x=o(S),x!==null){h.blockedOn=x,Ft(h.priority,function(){o8(S)});return}}else if(x===31){if(x=l(S),x!==null){h.blockedOn=x,Ft(h.priority,function(){o8(S)});return}}else if(x===3&&S.stateNode.current.memoizedState.isDehydrated){h.blockedOn=S.tag===3?S.stateNode.containerInfo:null;return}}}h.blockedOn=null}function y_(h){if(h.blockedOn!==null)return!1;for(var x=h.targetContainers;0<x.length;){var S=WM(h.nativeEvent);if(S===null){S=h.nativeEvent;var E=new S.constructor(S.type,S);sc=E,S.target.dispatchEvent(E),sc=null}else return x=Ce(S),x!==null&&s8(x),h.blockedOn=S,!1;x.shift()}return!0}function u8(h,x,S){y_(h)&&S.delete(x)}function cde(){YM=!1,Rm!==null&&y_(Rm)&&(Rm=null),Lm!==null&&y_(Lm)&&(Lm=null),Om!==null&&y_(Om)&&(Om=null),av.forEach(u8),iv.forEach(u8)}function v_(h,x){h.blockedOn===x&&(h.blockedOn=null,YM||(YM=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,cde)))}var w_=null;function m8(h){w_!==h&&(w_=h,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){w_===h&&(w_=null);for(var x=0;x<h.length;x+=3){var S=h[x],E=h[x+1],H=h[x+2];if(typeof E!="function"){if(KM(E||S)===null)continue;break}var Z=Ce(S);Z!==null&&(h.splice(x,3),x-=3,WA(Z,{pending:!0,data:H,method:S.method,action:E},E,H))}}))}function Wg(h){function x(nt){return v_(nt,h)}Rm!==null&&v_(Rm,h),Lm!==null&&v_(Lm,h),Om!==null&&v_(Om,h),av.forEach(x),iv.forEach(x);for(var S=0;S<Im.length;S++){var E=Im[S];E.blockedOn===h&&(E.blockedOn=null)}for(;0<Im.length&&(S=Im[0],S.blockedOn===null);)d8(S),S.blockedOn===null&&Im.shift();if(S=(h.ownerDocument||h).$$reactFormReplay,S!=null)for(E=0;E<S.length;E+=3){var H=S[E],Z=S[E+1],ke=H[Mt]||null;if(typeof Z=="function")ke||m8(S);else if(ke){var Be=null;if(Z&&Z.hasAttribute("formAction")){if(H=Z,ke=Z[Mt]||null)Be=ke.formAction;else if(KM(H)!==null)continue}else Be=ke.action;typeof Be=="function"?S[E+1]=Be:(S.splice(E,3),E-=3),m8(S)}}}function h8(){function h(Z){Z.canIntercept&&Z.info==="react-transition"&&Z.intercept({handler:function(){return new Promise(function(ke){return H=ke})},focusReset:"manual",scroll:"manual"})}function x(){H!==null&&(H(),H=null),E||setTimeout(S,20)}function S(){if(!E&&!navigation.transition){var Z=navigation.currentEntry;Z&&Z.url!=null&&navigation.navigate(Z.url,{state:Z.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var E=!1,H=null;return navigation.addEventListener("navigate",h),navigation.addEventListener("navigatesuccess",x),navigation.addEventListener("navigateerror",x),setTimeout(S,100),function(){E=!0,navigation.removeEventListener("navigate",h),navigation.removeEventListener("navigatesuccess",x),navigation.removeEventListener("navigateerror",x),H!==null&&(H(),H=null)}}}function XM(h){this._internalRoot=h}S_.prototype.render=XM.prototype.render=function(h){var x=this._internalRoot;if(x===null)throw Error(r(409));var S=x.current,E=Vo();a8(S,E,h,x,null,null)},S_.prototype.unmount=XM.prototype.unmount=function(){var h=this._internalRoot;if(h!==null){this._internalRoot=null;var x=h.containerInfo;a8(h.current,2,null,h,null,null),n_(),x[Qt]=null}};function S_(h){this._internalRoot=h}S_.prototype.unstable_scheduleHydration=function(h){if(h){var x=Ke();h={blockedOn:null,target:h,priority:x};for(var S=0;S<Im.length&&x!==0&&x<Im[S].priority;S++);Im.splice(S,0,h),S===0&&d8(h)}};var p8=e.version;if(p8!=="19.2.4")throw Error(r(527,p8,"19.2.4"));ee.findDOMNode=function(h){var x=h._reactInternals;if(x===void 0)throw typeof h.render=="function"?Error(r(188)):(h=Object.keys(h).join(","),Error(r(268,h)));return h=d(x),h=h!==null?u(h):null,h=h===null?null:h.stateNode,h};var dde={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:ae,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var __=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!__.isDisabled&&__.supportsFiber)try{Ee=__.inject(dde),Se=__}catch{}}return lv.createRoot=function(h,x){if(!i(h))throw Error(r(299));var S=!1,E="",H=wU,Z=SU,ke=_U;return x!=null&&(x.unstable_strictMode===!0&&(S=!0),x.identifierPrefix!==void 0&&(E=x.identifierPrefix),x.onUncaughtError!==void 0&&(H=x.onUncaughtError),x.onCaughtError!==void 0&&(Z=x.onCaughtError),x.onRecoverableError!==void 0&&(ke=x.onRecoverableError)),x=n8(h,1,!1,null,null,S,E,null,H,Z,ke,h8),h[Qt]=x.current,jM(h),new XM(x)},lv.hydrateRoot=function(h,x,S){if(!i(h))throw Error(r(299));var E=!1,H="",Z=wU,ke=SU,Be=_U,nt=null;return S!=null&&(S.unstable_strictMode===!0&&(E=!0),S.identifierPrefix!==void 0&&(H=S.identifierPrefix),S.onUncaughtError!==void 0&&(Z=S.onUncaughtError),S.onCaughtError!==void 0&&(ke=S.onCaughtError),S.onRecoverableError!==void 0&&(Be=S.onRecoverableError),S.formState!==void 0&&(nt=S.formState)),x=n8(h,1,!0,x,S??null,E,H,nt,Z,ke,Be,h8),x.context=r8(null),S=x.current,E=Vo(),E=Ut(E),H=_m(E),H.callback=null,km(S,H,E),S=E,x.current.lanes=S,xt(x,S),Xc(x),h[Qt]=x.current,jM(h),new S_(x)},lv.version="19.2.4",lv}var k8;function wde(){if(k8)return JM.exports;k8=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=vde(),JM.exports}var Sde=wde();const zn=t=>typeof t=="string",cv=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},N8=t=>t==null?"":""+t,_de=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},kde=/###/g,C8=t=>t&&t.indexOf("###")>-1?t.replace(kde,"."):t,P8=t=>!t||zn(t),a0=(t,e,n)=>{const r=zn(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(P8(t))return{};const s=C8(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return P8(t)?{}:{obj:t,k:C8(r[i])}},T8=(t,e,n)=>{const{obj:r,k:i}=a0(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),l=a0(t,o,Object);for(;l.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),l=a0(t,o,Object),l?.obj&&typeof l.obj[`${l.k}.${s}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${s}`]=n},Nde=(t,e,n,r)=>{const{obj:i,k:s}=a0(t,e,Object);i[s]=i[s]||[],i[s].push(n)},Gk=(t,e)=>{const{obj:n,k:r}=a0(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},Cde=(t,e,n)=>{const r=Gk(t,n);return r!==void 0?r:Gk(e,n)},yX=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?zn(t[r])||t[r]instanceof String||zn(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):yX(t[r],e[r],n):t[r]=e[r]);return t},Kg=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Pde={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Tde=t=>zn(t)?t.replace(/[&<>"'\/]/g,e=>Pde[e]):t;class Ade{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const Mde=[" ",",","?","!",";"],jde=new Ade(20),Ede=(t,e,n)=>{e=e||"",n=n||"";const r=Mde.filter(o=>e.indexOf(o)<0&&n.indexOf(o)<0);if(r.length===0)return!0;const i=jde.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!i.test(t);if(!s){const o=t.indexOf(n);o>0&&!i.test(t.substring(0,o))&&(s=!0)}return s},S3=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let o,l="";for(let c=s;c<r.length;++c)if(c!==s&&(l+=n),l+=r[c],o=i[l],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<r.length-1)continue;s+=c-s+1;break}i=o}return i},j0=t=>t?.replace("_","-"),Dde={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 Wk{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||Dde,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(zn(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Wk(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Wk(this.logger,e)}}var hd=new Wk;let yP=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i.apply(i,[e,...n])})}};class A8 extends yP{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.indexOf(".")>-1?l=e.split("."):(l=[e,n],r&&(Array.isArray(r)?l.push(...r):zn(r)&&s?l.push(...r.split(s)):l.push(r)));const c=Gk(this.data,l);return!c&&!n&&!r&&e.indexOf(".")>-1&&(e=l[0],n=l[1],r=l.slice(2).join(".")),c||!o||!zn(r)?c:S3(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let l=[e,n];r&&(l=l.concat(o?r.split(o):r)),e.indexOf(".")>-1&&(l=e.split("."),i=n,n=l[1]),this.addNamespaces(n),T8(this.data,l,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(zn(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,o={silent:!1,skipCopy:!1}){let l=[e,n];e.indexOf(".")>-1&&(l=e.split("."),i=r,r=n,n=l[1]),this.addNamespaces(n);let c=Gk(this.data,l)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?yX(c,r,s):c={...c,...r},T8(this.data,l,c),o.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var vX={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const wX=Symbol("i18next/PATH_KEY");function Fde(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===wX?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function _3(t,e){const{[wX]:n}=t(Fde());return n.join(e?.keySeparator??".")}const M8={},rj=t=>!zn(t)&&typeof t!="boolean"&&typeof t!="number";class Kk extends yP{constructor(e,n={}){super(),_de(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=hd.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=rj(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=r&&e.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Ede(e,r,i);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:zn(s)?[s]:s};const d=e.split(r);(r!==i||r===i&&this.options.ns.indexOf(d[0])>-1)&&(s=d.shift()),e=d.join(i)}return{key:e,namespaces:zn(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=_3(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 y=f?.res;const v=f?.usedKey||l,b=f?.exactUsedKey||l,g=["[object Number]","[object Function]","[object RegExp]"],_=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,P=i.count!==void 0&&!zn(i.count),N=Kk.hasDefaultValue(i),M=P?this.pluralResolver.getSuffix(m,i.count,i):"",A=i.ordinal&&P?this.pluralResolver.getSuffix(m,i.count,{ordinal:!1}):"",T=P&&!i.ordinal&&i.count===0,C=T&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${M}`]||i[`defaultValue${A}`]||i.defaultValue;let F=y;k&&!y&&N&&(F=C);const $=rj(F),I=Object.prototype.toString.apply(F);if(k&&F&&$&&g.indexOf(I)<0&&!(zn(_)&&Array.isArray(F))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const X=this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,F,{...i,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return s?(f.res=X,f.usedParams=this.getUsedParamsDetails(i),f):X}if(o){const X=Array.isArray(F),L=X?[]:{},te=X?b:v;for(const ae in F)if(Object.prototype.hasOwnProperty.call(F,ae)){const ee=`${te}${o}${ae}`;N&&!y?L[ae]=this.translate(ee,{...i,defaultValue:rj(C)?C[ae]:void 0,joinArrays:!1,ns:c}):L[ae]=this.translate(ee,{...i,joinArrays:!1,ns:c}),L[ae]===ee&&(L[ae]=F[ae])}y=L}}else if(k&&zn(_)&&Array.isArray(y))y=y.join(_),y&&(y=this.extendTranslation(y,e,i,r));else{let X=!1,L=!1;!this.isValidLookup(y)&&N&&(X=!0,y=C),this.isValidLookup(y)||(L=!0,y=l);const ae=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&L?void 0:y,ee=N&&C!==y&&this.options.updateMissing;if(L||X||ee){if(this.logger.log(ee?"updateKey":"missingKey",m,d,l,ee?C:y),o){const K=this.resolve(l,{...i,keySeparator:!1});K&&K.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 me=[];const le=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&le&&le[0])for(let K=0;K<le.length;K++)me.push(le[K]);else this.options.saveMissingTo==="all"?me=this.languageUtils.toResolveHierarchy(i.lng||this.language):me.push(i.lng||this.language);const ue=(K,ne,oe)=>{const be=N&&oe!==y?oe:ae;this.options.missingKeyHandler?this.options.missingKeyHandler(K,d,ne,be,ee,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(K,d,ne,be,ee,i),this.emit("missingKey",K,d,ne,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&P?me.forEach(K=>{const ne=this.pluralResolver.getSuffixes(K,i);T&&i[`defaultValue${this.options.pluralSeparator}zero`]&&ne.indexOf(`${this.options.pluralSeparator}zero`)<0&&ne.push(`${this.options.pluralSeparator}zero`),ne.forEach(oe=>{ue([K],l+oe,i[`defaultValue${oe}`]||C)})}):ue(me,l,C))}y=this.extendTranslation(y,e,i,f,r),L&&y===l&&this.options.appendNamespaceToMissingKey&&(y=`${d}${u}${l}`),(L||X)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,X?y:void 0,i))}return s?(f.res=y,f.usedParams=this.getUsedParamsDetails(i),f):y}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=zn(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(c){const m=e.match(this.interpolator.nestingRegexp);d=m&&m.length}let u=r.replace&&!zn(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),c){const m=e.match(this.interpolator.nestingRegexp),p=m&&m.length;d<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...m)=>s?.[0]===m[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${m[0]} in key: ${n[0]}`),null):this.translate(...m,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,l=zn(o)?[o]:o;return e!=null&&l?.length&&r.applyPostProcessor!==!1&&(e=vX.handle(l,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,o,l;return zn(e)&&(e=[e]),e.forEach(c=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(c,n),u=d.key;i=u;let m=d.namespaces;this.options.fallbackNS&&(m=m.concat(this.options.fallbackNS));const p=n.count!==void 0&&!zn(n.count),f=p&&!n.ordinal&&n.count===0,y=n.context!==void 0&&(zn(n.context)||typeof n.context=="number")&&n.context!=="",v=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);m.forEach(b=>{this.isValidLookup(r)||(l=b,!M8[`${v[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(l)&&(M8[`${v[0]}-${b}`]=!0,this.logger.warn(`key "${i}" for languages "${v.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),v.forEach(g=>{if(this.isValidLookup(r))return;o=g;const _=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(_,u,g,b,n);else{let P;p&&(P=this.pluralResolver.getSuffix(g,n.count,n));const N=`${this.options.pluralSeparator}zero`,M=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&P.indexOf(M)===0&&_.push(u+P.replace(M,this.options.pluralSeparator)),_.push(u+P),f&&_.push(u+N)),y){const A=`${u}${this.options.contextSeparator||"_"}${n.context}`;_.push(A),p&&(n.ordinal&&P.indexOf(M)===0&&_.push(A+P.replace(M,this.options.pluralSeparator)),_.push(A+P),f&&_.push(A+N))}}let k;for(;k=_.pop();)this.isValidLookup(r)||(s=k,r=this.getResource(g,b,k,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!zn(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&n===r.substring(0,n.length)&&e[r]!==void 0)return!0;return!1}}class j8{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=hd.create("languageUtils")}getScriptPartFromCode(e){if(e=j0(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=j0(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(zn(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),zn(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),i=[],s=o=>{o&&(this.isSupportedCode(o)?i.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return zn(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))):zn(e)&&s(this.formatLanguageCode(e)),r.forEach(o=>{i.indexOf(o)<0&&s(this.formatLanguageCode(o))}),i}}const E8={zero:0,one:1,two:2,few:3,many:4,other:5},D8={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Rde{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=hd.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=j0(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),D8;if(!e.match(/-|_/))return D8;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>E8[i]-E8[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const F8=(t,e,n,r=".",i=!0)=>{let s=Cde(t,e,n);return!s&&i&&zn(n)&&(s=S3(t,n,r),s===void 0&&(s=S3(e,n,r))),s},aj=t=>t.replace(/\$/g,"$$$$");class Lde{constructor(e={}){this.logger=hd.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:m,nestingPrefix:p,nestingPrefixEscaped:f,nestingSuffix:y,nestingSuffixEscaped:v,nestingOptionsSeparator:b,maxReplaces:g,alwaysFormat:_}=e.interpolation;this.escape=n!==void 0?n:Tde,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Kg(s):o||"{{",this.suffix=l?Kg(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":m||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=p?Kg(p):f||Kg("$t("),this.nestingSuffix=y?Kg(y):v||Kg(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=g||1e3,this.alwaysFormat=_!==void 0?_:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){let s,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=f=>{if(f.indexOf(this.formatSeparator)<0){const g=F8(n,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(g,void 0,r,{...i,...n,interpolationkey:f}):g}const y=f.split(this.formatSeparator),v=y.shift().trim(),b=y.join(this.formatSeparator).trim();return this.format(F8(n,c,v,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...i,...n,interpolationkey:v})};this.resetRegExp();const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,m=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>aj(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?aj(this.escape(f)):aj(f)}].forEach(f=>{for(l=0;s=f.regex.exec(e);){const y=s[1].trim();if(o=d(y),o===void 0)if(typeof u=="function"){const b=u(e,s,i);o=zn(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,y))o="";else if(m){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),o="";else!zn(o)&&!this.useRawValueToEscape&&(o=N8(o));const v=f.safeValue(o);if(e=e.replace(s[0],v),m?(f.regex.lastIndex+=o.length,f.regex.lastIndex-=s[0].length):f.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(c.indexOf(u)<0)return c;const m=c.split(new RegExp(`${u}[ ]*{`));let p=`{${m[1]}`;c=m[0],p=this.interpolate(p,o);const f=p.match(/'/g),y=p.match(/"/g);((f?.length??0)%2===0&&!y||y.length%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(v){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,v),`${c}${u}${p}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!zn(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&&!zn(s))return s;zn(s)||(s=N8(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((u,m)=>this.format(u,m,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Ode=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);e==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):e==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();n[u]||(n[u]=d),d==="false"&&(n[u]=!1),d==="true"&&(n[u]=!0),isNaN(d)||(n[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},R8=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=r+JSON.stringify(s);let l=e[o];return l||(l=t(j0(r),i),e[o]=l),l(n)}},Ide=t=>(e,n,r)=>t(j0(n),r)(e);class zde{constructor(e={}){this.logger=hd.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?R8:Ide;this.formats={number:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return l=>o.format(l)}),currency:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return l=>o.format(l)}),datetime:r((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return l=>o.format(l)}),relativetime:r((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return l=>o.format(l,s.range||"day")}),list:r((i,s)=>{const o=new Intl.ListFormat(i,{...s});return l=>o.format(l)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=R8(n)}format(e,n,r,i={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(l=>l.indexOf(")")>-1)){const l=s.findIndex(c=>c.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,l)].join(this.formatSeparator)}return s.reduce((l,c)=>{const{formatName:d,formatOptions:u}=Ode(c);if(this.formats[d]){let m=l;try{const p=i?.formatParams?.[i.interpolationkey]||{},f=p.locale||p.lng||i.locale||i.lng||r;m=this.formats[d](l,f,{...u,...i,...p})}catch(p){this.logger.warn(p)}return m}else this.logger.warn(`there was no format function for ${d}`);return l},e)}}const Ude=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Bde extends yP{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=hd.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(e,n,r,i){const s={},o={},l={},c={};return e.forEach(d=>{let u=!0;n.forEach(m=>{const p=`${d}|${m}`;!r.reload&&this.store.hasResourceBundle(d,m)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?o[p]===void 0&&(o[p]=!0):(this.state[p]=1,u=!1,o[p]===void 0&&(o[p]=!0),s[p]===void 0&&(s[p]=!0),c[m]===void 0&&(c[m]=!0)))}),u||(l[d]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const i=e.split("|"),s=i[0],o=i[1];n&&this.emit("failedLoading",s,o,n),!n&&r&&this.store.addResourceBundle(s,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const l={};this.queue.forEach(c=>{Nde(c.loaded,[s],o),Ude(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(m=>{l[d][m]===void 0&&(l[d][m]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,n,r,i=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:o});return}this.readingCalls++;const l=(d,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const m=this.waitingReads.shift();this.read(m.lng,m.ns,m.fcName,m.tried,m.wait,m.callback)}if(d&&u&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,r,i+1,s*2,o)},s);return}o(d,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const d=c(e,n);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,n,l)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();zn(e)&&(e=this.languageUtils.toResolveHierarchy(e)),zn(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,o),!o&&l&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,l),this.loaded(e,o,l)})}saveMissing(e,n,r,i,s,o={},l=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const c={...o,isUpdate:s},d=this.backend.create.bind(this.backend);if(d.length<6)try{let u;d.length===5?u=d(e,n,r,i,c):u=d(e,n,r,i),u&&typeof u.then=="function"?u.then(m=>l(null,m)).catch(l):l(null,u)}catch(u){l(u)}else d(e,n,r,i,l,c)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const L8=()=>({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]),zn(t[1])&&(e.defaultValue=t[1]),zn(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),O8=t=>(zn(t.ns)&&(t.ns=[t.ns]),zn(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),zn(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),N_=()=>{},Hde=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class i0 extends yP{constructor(e={},n){if(super(),this.options=O8(e),this.services={},this.logger=hd,this.modules={external:[]},Hde(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&&(zn(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const r=L8();this.options={...r,...this.options,...O8(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator);const i=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?hd.init(i(this.modules.logger),this.options):hd.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=zde;const u=new j8(this.options);this.store=new A8(this.options.resources,this.options);const m=this.services;m.logger=hd,m.resourceStore=this.store,m.languageUtils=u,m.pluralResolver=new Rde(u,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),d&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(m.formatter=i(d),m.formatter.init&&m.formatter.init(m,this.options),this.options.interpolation.format=m.formatter.format.bind(m.formatter)),m.interpolator=new Lde(this.options),m.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},m.backendConnector=new Bde(i(this.modules.backend),m.resourceStore,m,this.options),m.backendConnector.on("*",(f,...y)=>{this.emit(f,...y)}),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 Kk(this.services,this.options),this.translator.on("*",(f,...y)=>{this.emit(f,...y)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,n||(n=N_),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=cv(),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=N_){let r=n;const i=zn(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],o=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(d=>{d!=="cimode"&&s.indexOf(d)<0&&s.push(d)})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(l=>o(l)),this.services.backendConnector.load(s,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(e,n,r){const i=cv();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=N_),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&vX.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=cv();this.emit("languageChanging",e);const i=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},s=(l,c)=>{c?this.isLanguageChangingTo===e&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...d)=>this.t(...d)),n&&n(l,(...d)=>this.t(...d))},o=l=>{!e&&!l&&this.services.languageDetector&&(l=[]);const c=zn(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(zn(l)?[l]:l);d&&(this.language||i(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,u=>{s(u,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),r}getFixedT(e,n,r){const i=(s,o,...l)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([s,o].concat(l)):c={...o},c.lng=c.lng||i.lng,c.lngs=c.lngs||i.lngs,c.ns=c.ns||i.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||r||i.keyPrefix);const d=this.options.keySeparator||".";let u;return c.keyPrefix&&Array.isArray(s)?u=s.map(m=>(typeof m=="function"&&(m=_3(m,{...this.options,...o})),`${c.keyPrefix}${d}${m}`)):(typeof s=="function"&&(s=_3(s,{...this.options,...o})),u=c.keyPrefix?`${c.keyPrefix}${d}${s}`:s),this.t(u,c)};return zn(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=r,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(n.precheck){const l=n.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!i||o(s,e)))}loadNamespaces(e,n){const r=cv();return this.options.ns?(zn(e)&&(e=[e]),e.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=cv();zn(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(o=>i.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=i.concat(s),this.loadResources(o=>{r.resolve(),n&&n(o)}),r):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new j8(L8());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new i0(e,n);return r.createInstance=i0.createInstance,r}cloneInstance(e={},n=N_){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new i0(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(l=>{s[l]=this[l]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const l=Object.keys(this.store.data).reduce((c,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,m)=>(u[m]={...c[d][m]},u),c[d]),c),{});s.store=new A8(l,i),s.services.resourceStore=s.store}return s.translator=new Kk(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 oo=i0.createInstance();oo.createInstance;oo.dir;oo.init;oo.loadResources;oo.reloadResources;oo.use;oo.changeLanguage;oo.getFixedT;oo.t;oo.exists;oo.setDefaultNamespace;oo.hasLoadedNamespace;oo.loadNamespaces;oo.loadLanguages;const qde=(t,e,n,r)=>{const i=[n,{code:e,...r||{}}];if(t?.services?.logger?.forward)return t.services.logger.forward(i,"warn","react-i18next::",!0);Df(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),t?.services?.logger?.warn?t.services.logger.warn(...i):console?.warn&&console.warn(...i)},I8={},SX=(t,e,n,r)=>{Df(n)&&I8[n]||(Df(n)&&(I8[n]=new Date),qde(t,e,n,r))},_X=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},k3=(t,e,n)=>{t.loadNamespaces(e,_X(t,n))},z8=(t,e,n,r)=>{if(Df(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return k3(t,n,r);n.forEach(i=>{t.options.ns.indexOf(i)<0&&t.options.ns.push(i)}),t.loadLanguages(e,_X(t,r))},$de=(t,e,n={})=>!e.languages||!e.languages.length?(SX(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(r,i)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!i(r.isLanguageChangingTo,t))return!1}}),Df=t=>typeof t=="string",Vde=t=>typeof t=="object"&&t!==null,Gde=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Wde={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Kde=t=>Wde[t],Yde=t=>t.replace(Gde,Kde);let N3={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Yde,transDefaultProps:void 0};const Xde=(t={})=>{N3={...N3,...t}},Qde=()=>N3;let kX;const Zde=t=>{kX=t},Jde=()=>kX,eue={type:"3rdParty",init(t){Xde(t.options.react),Zde(t)}},tue=w.createContext();class nue{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var ij={exports:{}},sj={};var U8;function rue(){if(U8)return sj;U8=1;var t=og();function e(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,i=t.useEffect,s=t.useLayoutEffect,o=t.useDebugValue;function l(m,p){var f=p(),y=r({inst:{value:f,getSnapshot:p}}),v=y[0].inst,b=y[1];return s(function(){v.value=f,v.getSnapshot=p,c(v)&&b({inst:v})},[m,f,p]),i(function(){return c(v)&&b({inst:v}),m(function(){c(v)&&b({inst:v})})},[m]),o(f),f}function c(m){var p=m.getSnapshot;m=m.value;try{var f=p();return!n(m,f)}catch{return!0}}function d(m,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return sj.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,sj}var B8;function NX(){return B8||(B8=1,ij.exports=rue()),ij.exports}var GL=NX();const aue=(t,e)=>Df(e)?e:Vde(e)&&Df(e.defaultValue)?e.defaultValue:Array.isArray(t)?t[t.length-1]:t,iue={t:aue,ready:!1},sue=()=>()=>{},Lt=(t,e={})=>{const{i18n:n}=e,{i18n:r,defaultNS:i}=w.useContext(tue)||{},s=n||r||Jde();s&&!s.reportNamespaces&&(s.reportNamespaces=new nue),s||SX(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=w.useMemo(()=>({...Qde(),...s?.options?.react,...e}),[s,e]),{useSuspense:l,keyPrefix:c}=o,d=i||s?.options?.defaultNS,u=Df(d)?[d]:d||["translation"],m=w.useMemo(()=>u,u);s?.reportNamespaces?.addUsedNamespaces?.(m);const p=w.useRef(0),f=w.useCallback(C=>{if(!s)return sue;const{bindI18n:F,bindI18nStore:$}=o,I=()=>{p.current+=1,C()};return F&&s.on(F,I),$&&s.store.on($,I),()=>{F&&F.split(" ").forEach(X=>s.off(X,I)),$&&$.split(" ").forEach(X=>s.store.off(X,I))}},[s,o]),y=w.useRef(),v=w.useCallback(()=>{if(!s)return iue;const C=!!(s.isInitialized||s.initializedStoreOnce)&&m.every(te=>$de(te,s,o)),F=e.lng||s.language,$=p.current,I=y.current;if(I&&I.ready===C&&I.lng===F&&I.keyPrefix===c&&I.revision===$)return I;const L={t:s.getFixedT(F,o.nsMode==="fallback"?m:m[0],c),ready:C,lng:F,keyPrefix:c,revision:$};return y.current=L,L},[s,m,c,o,e.lng]),[b,g]=w.useState(0),{t:_,ready:k}=GL.useSyncExternalStore(f,v,v);w.useEffect(()=>{if(s&&!k&&!l){const C=()=>g(F=>F+1);e.lng?z8(s,e.lng,m,C):k3(s,m,C)}},[s,e.lng,m,k,l,b]);const P=s||{},N=w.useRef(null),M=w.useRef(),A=C=>{const F=Object.getOwnPropertyDescriptors(C);F.__original&&delete F.__original;const $=Object.create(Object.getPrototypeOf(C),F);if(!Object.prototype.hasOwnProperty.call($,"__original"))try{Object.defineProperty($,"__original",{value:C,writable:!1,enumerable:!1,configurable:!1})}catch{}return $},T=w.useMemo(()=>{const C=P,F=C?.language;let $=C;C&&(N.current&&N.current.__original===C?M.current!==F?($=A(C),N.current=$,M.current=F):$=N.current:($=A(C),N.current=$,M.current=F));const I=[_,$,k];return I.t=_,I.i18n=$,I.ready=k,I},[_,P,k,P.resolvedLanguage,P.language,P.languages]);if(s&&l&&!k)throw new Promise(C=>{const F=()=>C();e.lng?z8(s,e.lng,m,F):k3(s,m,F)});return T},{slice:oue,forEach:lue}=[];function cue(t){return lue.call(oue.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function due(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 H8=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,uue=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${i}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!H8.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!H8.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(s+="; Partitioned"),s},q8={create(t,e,n,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+n*60*1e3)),r&&(i.domain=r),document.cookie=uue(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let i=n[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var mue={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return q8.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&q8.create(n,t,r,i,s)}},hue={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const s=r.substring(1).split("&");for(let o=0;o<s.length;o++){const l=s[o].indexOf("=");l>0&&s[o].substring(0,l)===e&&(n=s[o].substring(l+1))}}return n}},pue={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const s=i.substring(1);if(e){const o=s.split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(r=o[l].substring(c+1))}}if(r)return r;if(!r&&n>-1){const o=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let Yg=null;const $8=()=>{if(Yg!==null)return Yg;try{if(Yg=typeof window<"u"&&window.localStorage!==null,!Yg)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Yg=!1}return Yg};var fue={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&$8())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&$8()&&window.localStorage.setItem(n,t)}};let Xg=null;const V8=()=>{if(Xg!==null)return Xg;try{if(Xg=typeof window<"u"&&window.sessionStorage!==null,!Xg)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Xg=!1}return Xg};var gue={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&V8())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&V8()&&window.sessionStorage.setItem(n,t)}},bue={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},xue={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},yue={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}},vue={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let CX=!1;try{document.cookie,CX=!0}catch{}const PX=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];CX||PX.splice(1,1);const wue=()=>({order:PX,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class TX{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=cue(n,this.options||{},wue()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(mue),this.addDetector(hue),this.addDetector(fue),this.addDetector(gue),this.addDetector(bue),this.addDetector(xue),this.addDetector(yue),this.addDetector(vue),this.addDetector(pue)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(r=>r!=null&&!due(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}TX.type="languageDetector";const Sue={nav:{printers:"Printers",archives:"Archives",queue:"Queue",stats:"Statistics",profiles:"Profiles",maintenance:"Maintenance",projects:"Projects",inventory:"Filament",files:"File Manager",notifications:"Notifications",settings:"Settings",system:"System",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",update:"Update",updateAvailable:"Update available: v{{version}}",updateAvailableBanner:"Version {{version}} is available!",viewUpdate:"View update",viewOnGithub:"View on GitHub",keyboardShortcuts:"Keyboard shortcuts (?)",switchToLight:"Switch to light mode",switchToDark:"Switch to dark mode",smartSwitches:"Smart Switches",logout:"Logout"},common:{save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",edit:"Edit",add:"Add",close:"Close",confirm:"Confirm",loading:"Loading...",error:"Error",success:"Success",warning:"Warning",enabled:"Enabled",disabled:"Disabled",yes:"Yes",no:"No",on:"On",off:"Off",all:"All",none:"None",search:"Search",filter:"Filter",sort:"Sort",refresh:"Refresh",download:"Download",upload:"Upload",uploading:"Uploading...",uploadFailed:"Upload failed",actions:"Actions",status:"Status",name:"Name",description:"Description",date:"Date",time:"Time",hours:"hours",minutes:"minutes",seconds:"seconds",days:"days",enable:"Enable",disable:"Disable",permissions:"Permissions",noPrinters:"No printers configured",noData:"No data available",linkNotFound:"Link not found",required:"Required",optional:"Optional",dismiss:"Dismiss",apply:"Apply",reset:"Reset",export:"Export",import:"Import",clear:"Clear",selectAll:"Select All",deselectAll:"Deselect All",noChange:"— No change —",unchanged:"Unchanged",unassigned:"Unassigned",unknown:"Unknown",unknownError:"Unknown error",today:"Today",tomorrow:"Tomorrow",asap:"ASAP",overdue:"Overdue",now:"Now",collapse:"Collapse",expand:"Expand",viewArchive:"View archive",viewInFileManager:"View in File Manager",addedBy:"Added by {{username}}",prints:"prints",more:"+{{count}} more",ascending:"Ascending",descending:"Descending",printer:"Printer",remove:"Remove",type:"Type",print:"Print",rename:"Rename",move:"Move",create:"Create",duplicate:"Duplicate",left:"Left",right:"Right"},printers:{title:"Printers",addPrinter:"Add Printer",editPrinter:"Edit Printer",deletePrinter:"Delete Printer",printerName:"Printer Name",serialNumber:"Serial Number",ipAddress:"IP Address / Hostname",accessCode:"Access Code",model:"Model",nozzleCount:"Nozzle Count",autoArchive:"Auto Archive",status:{available:"Available",idle:"Idle",printing:"Printing",paused:"Paused",offline:"Offline",problem:"Problem",error:"Error",finished:"Finished",unknown:"Unknown"},temperatures:{nozzle:"Nozzle",bed:"Bed",chamber:"Chamber"},progress:"{{percent}}% complete",timeRemaining:"{{time}} remaining",deleteConfirm:'Are you sure you want to delete "{{name}}"?',maintenanceOk:"Maintenance OK",maintenanceWarning:"{{count}} warning",maintenanceWarning_plural:"{{count}} warnings",maintenanceDue:"{{count}} due",maintenanceDue_plural:"{{count}} due",sort:{name:"Name",status:"Status",model:"Model",location:"Location",ascending:"Sort ascending",descending:"Sort descending"},cardSize:{small:"Small cards",medium:"Medium cards",large:"Large cards",extraLarge:"Extra large cards"},hideOffline:"Hide offline",nextAvailable:"Next available",powerOn:"Power On",offlinePrintersWithPlugs:"Offline printers with smart plugs",noPrintersConfigured:"No printers configured yet",search:"Search printers...",noSearchResults:"No printers match your search or filters",filter:{allStatuses:"All statuses",allLocations:"All locations"},readyToPrint:"Ready to print",external:"External",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Delete print archives",noLabel:"No label",printPreview:"Print preview",width:"Width",height:"Height",noObjectsFound:"No objects found",objectsLoadedOnPrintStart:"Objects are loaded when a print starts",willBeSkipped:"Will be skipped",name:"Name",serialCannotBeChanged:"Serial number cannot be changed",locationHelp:"Used to group printers and filter queue jobs",wifiSignal:{veryWeak:"Very weak",weak:"Weak",fair:"Fair",good:"Good",excellent:"Excellent"},maintenanceUpToDate:"All maintenance up to date - Click to view",chamberLightOn:"Turn on chamber light",chamberLightOff:"Turn off chamber light",files:"Files",browseFiles:"Browse printer files",autoOffAfterPrint:"Auto power-off after print",autoOffExecuted:"Auto-off was executed - turn printer on to reset",hmsErrors:"HMS Errors",viewHmsErrors:"View {{count}} HMS error(s)",resume:"Resume",pause:"Pause",stop:"Stop",camera:"Camera",skipObject:"Skip Object",reconnect:"Reconnect",mqttDebug:"MQTT Debug",printerInformation:"Printer Information",copyToClipboard:"Copy",copied:"Copied!",state:"State",wifiSignalLabel:"WiFi Signal",developerMode:"Developer Mode",enabled:"Enabled",disabled:"Disabled",addedOn:"Added",sdCard:"SD Card",inserted:"Inserted",notInserted:"Not inserted",totalPrintHours:"Print Hours",activeNozzle:"Active: {{nozzle}} nozzle",nozzleRack:"Nozzle Rack",nozzleDocked:"Docked",nozzleMounted:"Mounted",nozzleActive:"Active",nozzleIdle:"Idle",nozzleDiameter:"Diameter",nozzleType:"Type",nozzleStatus:"Status",nozzleFilament:"Filament",nozzleWear:"Wear",nozzleMaxTemp:"Max Temp",nozzleSerial:"Serial",nozzleHardenedSteel:"Hardened Steel",nozzleStainlessSteel:"Stainless Steel",nozzleTungstenCarbide:"Tungsten Carbide",nozzleFlow:"Flow",nozzleHighFlow:"High Flow",nozzleStandardFlow:"Standard",firmwareUpdate:"Firmware Update",firmwareInstructions:"On the printer's touchscreen, go to",firmwareNav:"Navigate to",settings:"Settings",firmware:"Firmware",discoverPrinters:"Discover Printers",searching:"Searching...",manualEntry:"Manual Entry",addFromCloud:"Add from Cloud",toast:{printerDeleted:"Printer deleted",missingSpoolAssignment:"Print started on {{printer}}. Missing spool assignment for: {{slots}}",printerAdded:"Printer added",printerUpdated:"Printer updated",failedToDelete:"Failed to delete printer",failedToAdd:"Failed to add printer",failedToUpdate:"Failed to update printer",commandSent:"Command sent",failedToSendCommand:"Failed to send command",turnedOn:"{{name}} turned on",failedToPowerOn:"Failed to power on {{name}}",scriptTriggered:"Script triggered",printStopped:"Print stopped",printPaused:"Print paused",printResumed:"Print resumed",referenceDeleted:"Reference deleted",detectionAreaSaved:"Detection area saved",failedToRunScript:"Failed to run script",failedToStopPrint:"Failed to stop print",failedToPausePrint:"Failed to pause print",failedToResumePrint:"Failed to resume print",failedToControlChamberLight:"Failed to control chamber light",failedToSetSpeed:"Failed to set print speed",failedToUpdateSetting:"Failed to update setting",failedToSkipObjects:"Failed to skip objects",failedToRereadRfid:"Failed to re-read RFID",failedToCheckPlate:"Failed to check plate",failedToUpdateLabel:"Failed to update label",failedToDeleteReference:"Failed to delete reference",failedToSaveDetectionArea:"Failed to save detection area",plateCheckEnabled:"Plate check enabled",plateCheckDisabled:"Plate check disabled",calibrationSaved:"Calibration saved!",calibrationFailed:"Calibration failed",rfidRereadInitiated:"RFID re-read initiated"},connection:{connected:"Connected",offline:"Offline"},queue:{inQueue:"{{count}} print in queue",inQueue_plural:"{{count}} prints in queue"},controls:"Controls",rfid:{reread:"Re-read RFID"},permission:{noAdd:"You do not have permission to add printers",noEdit:"You do not have permission to edit printers",noDelete:"You do not have permission to delete printers",noControl:"You do not have permission to control printers",noFiles:"You do not have permission to access printer files",noAmsRfid:"You do not have permission to re-read AMS RFID",noSmartPlugControl:"You do not have permission to control smart plugs",noCamera:"You do not have permission to view cameras"},modal:{addTitle:"Add Printer",editTitle:"Edit Printer",myPrinter:"My Printer",selectModel:"Select model...",locationGroup:"Location / Group (optional)",locationPlaceholder:"e.g., Workshop, Office, Basement",autoArchiveLabel:"Auto-archive completed prints",fromPrinterSettings:"From printer settings",modelOptional:"Model (optional)",saveChanges:"Save Changes"},skipObjects:{tooltip:"Skip objects",onlyWhilePrinting:"Skip objects (only while printing)",requiresMultiple:"Skip objects (requires 2+ objects)",title:"Skip Objects",matchIdsInfo:"Match IDs with your printer display",printerShowsIds:"The printer screen shows object IDs on the build plate",skipSelected:"Skip Selected",skipping:"Skipping...",noObjectsSelected:"No objects selected",selectObjectsToSkip:"Select objects you want to skip from the current print",skipped:"skipped",objectsSkipped:"Objects skipped",activeCount:"{{count}} active",waitForLayer:"Wait for layer 2+ to skip objects (currently layer {{layer}})",skip:"Skip",confirmTitle:"Skip Object?",confirmMessage:'Are you sure you want to skip "{{name}}"? This cannot be undone.'},confirm:{deleteTitle:"Delete Printer",deleteMessage:'Are you sure you want to delete "{{name}}"? This will remove all connection settings.',deleteArchivesNote:"All print history for this printer will be permanently deleted.",keepArchivesNote:"Print history will be kept but no longer associated with this printer.",stopTitle:"Stop Print",stopMessage:'Are you sure you want to stop the current print on "{{name}}"? This will cancel the print job.',stopButton:"Stop Print",pauseTitle:"Pause Print",pauseMessage:'Are you sure you want to pause the current print on "{{name}}"?',pauseButton:"Pause Print",resumeTitle:"Resume Print",resumeMessage:'Are you sure you want to resume the print on "{{name}}"?',resumeButton:"Resume Print",powerOnTitle:"Power On Printer",powerOnMessage:'Are you sure you want to turn ON the power for "{{name}}"?',powerOnButton:"Power On",powerOffTitle:"Power Off Printer",powerOffMessage:'Are you sure you want to turn OFF the power for "{{name}}"?',powerOffWarning:'WARNING: "{{name}}" is currently printing! Are you sure you want to turn OFF the power? This will interrupt the print and may damage the printer.',powerOffButton:"Power Off"},bulk:{select:"Select",selectAll:"Select All",selectByLocation:"Select by Location",selected:"{{count}} selected",actions:{stop:"Stop",pause:"Pause",resume:"Resume",clearPlate:"Clear Bed",clearHMS:"Clear Notifications"},confirm:{stopTitle:"Stop {{count}} Prints",stopMessage:"This will cancel active prints on {{count}} printer(s). This action cannot be undone.",stopButton:"Stop All",pauseTitle:"Pause {{count}} Prints",pauseMessage:"This will pause active prints on {{count}} printer(s).",pauseButton:"Pause All",clearPlateTitle:"Clear {{count}} Print Beds",clearPlateMessage:"This will clear the print bed on {{count}} printer(s) and may trigger queued jobs.",clearPlateButton:"Clear All"},success:"{{action}} completed on {{count}} printer(s)",partial:"{{succeeded}} succeeded, {{failed}} failed",noneApplicable:"No selected printers are in the right state for this action",selectByState:"Select by State"},discovery:{title:"Discover Printers",searching:"Searching...",scanning:"Scanning...",scanProgress:"Scanning... {{scanned}}/{{total}}",foundPrinters:"Found {{count}} printer(s)",noPrintersFound:"No printers found",noPrintersFoundSubnet:"No printers found in the specified subnet.",noPrintersFoundNetwork:"No printers found on the network.",allConfigured:"All discovered printers are already configured.",alreadyAdded:"Already added",select:"Select",manualEntry:"Manual Entry",addFromCloud:"Add from Cloud",subnetToScan:"Subnet to scan",dockerNote:"Docker detected. Enter your printer's subnet in CIDR notation. Requires network_mode: host in docker-compose.yml.",scanSubnet:"Scan Subnet for Printers",discoverNetwork:"Discover Printers on Network",scanningSubnet:"Scanning subnet for Bambu printers...",scanningNetwork:"Scanning network...",serialRequired:"Serial required",unknown:"Unknown",failedToStart:"Failed to start discovery"},drying:{start:"Start Drying",stop:"Stop Drying",temperature:"Temperature",duration:"Duration",hours:"hours",timeRemaining:"{{time}} left",active:"Drying",notSupported:"Drying not supported",powerRequired:"Connect AMS power adapter to enable drying",startingDrying:"Starting drying...",stoppingDrying:"Stopping drying...",rotateTray:"Rotate spool during drying"},filaments:"Filaments",openCameraOverlay:"Open camera overlay",openCameraWindow:"Open camera in new window",firmwareUpdateAvailable:"Firmware update available: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Up to date",firmwareUpdateButton:"Update",plateDetection:{noPermission:"You do not have permission to update printers",enabledClick:"Plate check enabled - Click to disable",disabledClick:"Plate check disabled - Click to enable",manageCalibration:"Manage plate detection calibration",calibrationRequired:"Calibration Required",calibrationInstructions:"Please ensure the build plate is <strong>completely empty</strong>, then click Calibrate.",calibrationDescription:"Calibration captures a reference image of the empty plate. Future checks will compare against this reference to detect objects.",calibrationTip:"<strong>Tip:</strong> You can store up to 5 calibrations for different plates. The system automatically uses the best match when checking.",plateEmpty:"Plate appears empty",objectsDetected:"Objects detected on plate",confidence:"Confidence",difference:"Difference",analysisPreview:"Analysis preview:",analysisLegend:"Green box = detection area, Red overlay = differences from calibration",savedReferences:"Saved References ({{count}}/{{max}})",deleteReference:"Delete reference",labelPlaceholder:"Label...",clickToEdit:"{{label}} - Click to edit",clickToAddLabel:"Click to add label"},speed:{title:"Print Speed",silent:"Silent (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},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."},accessCodePlaceholder:"Leave empty to keep current",roi:{title:"Detection Area (ROI)",xStart:"X Start",yStart:"Y Start",width:"Width",height:"Height",instruction:"Adjust the detection area to focus on the build plate. The green box in the preview shows the current area."},developerModeWarning:"Developer LAN mode is not enabled on: {{names}}. Some features may not work.",howToEnable:"How to enable",incompatibleFile:"This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",dropNotPrintable:"Only .gcode and .gcode.3mf files can be printed",dropToPrint:"Drop to print",cannotPrint:"Printer busy"},archives:{title:"Print Archives",searchPlaceholder:"Search archives...",filterByPrinter:"Filter by printer",filterByStatus:"Filter by status",sortBy:"Sort by",sortNewest:"Newest first",sortOldest:"Oldest first",sortName:"Name",sortDuration:"Duration",sortLargest:"Largest first",sortSmallest:"Smallest first",sortSize:"Size",noArchives:"No archives found",noArchivesSearch:"No archives match your search",originalPrintNotVisible:"Original print not visible - try clearing filters",noArchivesYet:"No archives yet",prints:"prints",pagination:{showing:"Showing",to:"to",of:"of",show:"Show",page:"Page",all:"All"},loadingArchives:"Loading archives...",releaseToUpload:"Release to upload",showAll:"Show all",showFavoritesOnly:"Show favorites only",gridView:"Grid view",listView:"List view",calendarView:"Calendar view",logView:"Print Log",manageTags:"Manage Tags",showFailedPrints:"Show failed prints",hideFailedPrints:"Hide failed prints",hideDuplicates:"Hide Duplicates",viewOriginalPrint:"Click to view original print (#{{id}})",printTime:"Print Time",filamentUsed:"Filament Used",cost:"Cost",reprint:"Reprint",preview:"Preview",deleteArchive:"Delete Archive",deleteConfirm:"Are you sure you want to delete this archive?",favorite:"Favorite",unfavorite:"Remove from favorites",viewDetails:"View Details",status:{completed:"Completed",failed:"Failed",stopped:"Stopped"},toast:{source3mfAttached:"Source 3MF attached: {{filename}}",failedUploadSource3mf:"Failed to upload source 3MF",source3mfRemoved:"Source 3MF removed",failedRemoveSource3mf:"Failed to remove source 3MF",f3dAttached:"F3D attached: {{filename}}",failedUploadF3d:"Failed to upload F3D",f3dRemoved:"F3D removed",failedRemoveF3d:"Failed to remove F3D",timelapseAttached:"Timelapse attached: {{filename}}",timelapseAlreadyAttached:"Timelapse already attached",noMatchingTimelapse:"No matching timelapse found",failedScanTimelapse:"Failed to scan for timelapse",failedAttachTimelapse:"Failed to attach timelapse",timelapseRemoved:"Timelapse removed",failedRemoveTimelapse:"Failed to remove timelapse",timelapseUploaded:"Timelapse uploaded: {{filename}}",failedUploadTimelapse:"Failed to upload timelapse",archiveDeleted:"Archive deleted",failedDeleteArchive:"Failed to delete archive",addedToFavorites:"Added to favorites",removedFromFavorites:"Removed from favorites",projectUpdated:"Project updated",failedUpdateProject:"Failed to update project",linkCopied:"Link copied to clipboard",failedCopyLink:"Failed to copy link",photoDeleted:"Photo deleted",failedDeletePhoto:"Failed to delete photo",failedDeleteArchives:"Failed to delete archives",failedUpdateFavorites:"Failed to update favorites",exportDownloaded:"Export downloaded",exportFailed:"Export failed"},menu:{print:"Print",schedule:"Schedule",openInBambuStudio:"Open in Slicer",slice:"Slice",externalLink:"External Link",viewOnMakerWorld:"View on MakerWorld",preview3d:"3D Preview",viewTimelapse:"View Timelapse",scanForTimelapse:"Scan for Timelapse",uploadTimelapse:"Upload Timelapse",removeTimelapse:"Remove Timelapse",downloadSource3mf:"Download Source 3MF",uploadSource3mf:"Upload Source 3MF",replaceSource3mf:"Replace Source 3MF",removeSource3mf:"Remove Source 3MF",uploadF3d:"Upload F3D",replaceF3d:"Replace F3D",downloadF3d:"Download F3D",removeF3d:"Remove F3D",download:"Download",copyDownloadLink:"Copy Download Link",qrCode:"QR Code",viewPhotos:"View Photos",viewPhotosCount:"View Photos ({{count}})",projectPage:"Project Page",addToFavorites:"Add to Favorites",removeFromFavorites:"Remove from Favorites",edit:"Edit",goToProject:"Go to Project: {{name}}",addToProject:"Add to Project",removeFromProject:"Remove from Project",loading:"Loading...",noProjectsAvailable:"No projects available",select:"Select",deselect:"Deselect",delete:"Delete"},permission:{noReprint:"You do not have permission to reprint this archive",noAddToQueue:"You do not have permission to add to queue",noUpdateArchives:"You do not have permission to update archives",noUploadFiles:"You do not have permission to upload files",noDownload:"You do not have permission to download archives",noCopyLink:"You do not have permission to copy download links",noDelete:"You do not have permission to delete this archive",noCreate:"You do not have permission to create archives"},card:{previousPlate:"Previous plate",nextPlate:"Next plate",plateNumber:"Plate {{index}}",moreOptions:"Right-click for more options",addToFavorites:"Add to favorites",removeFromFavorites:"Remove from favorites",cancelled:"cancelled",failed:"failed",duplicate:"duplicate",duplicateTitle:"This model has been printed before",openSource3mf:"Open source 3MF in Bambu Studio (right-click for more options)",downloadF3d:"Download Fusion 360 design file",viewTimelapse:"View timelapse",viewPhoto:"View 1 photo",viewPhotos:"View {{count}} photos",openFolder:"Open folder: {{name}}",slicedFile:"Sliced file - ready to print",sourceFile:"Source file only - no AMS mapping available",gcode:"GCODE",source:"SOURCE",project:"Project: {{name}}",estimated:"Estimated: {{time}}",actual:"Actual: {{time}}",accuracy:"Accuracy: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} layer",layers:"{{count}} layers",object:"{{count}} object",objects:"{{count}} objects",slicedFor:"Sliced for {{model}}",uploadedBy:"Uploaded By",noPermissionReprint:"You do not have permission to reprint",noFileForReprint:"No 3MF file available — the file could not be downloaded from the printer when the print was recorded",noPermissionEdit:"You do not have permission to edit archives",noPermissionDelete:"You do not have permission to delete archives",reprint:"Reprint",schedulePrint:"Schedule Print",schedule:"Schedule",openInBambuStudio:"Open in Slicer",openInBambuStudioToSlice:"Open in Slicer to slice",slice:"Slice",externalLink:"External Link",makerWorld:"MakerWorld: {{designer}}",viewProject:"View project",noExternalLink:"No external link",preview3d:"3D Preview",download:"Download",edit:"Edit",delete:"Delete"},modal:{deleteArchive:"Delete Archive",deleteConfirm:'Are you sure you want to delete "{{name}}"? This action cannot be undone.',deleteButton:"Delete",removeSource3mf:"Remove Source 3MF",removeSource3mfConfirm:'Are you sure you want to remove the source 3MF file from "{{name}}"? This will delete the original slicer project file.',removeButton:"Remove",removeF3d:"Remove F3D",removeF3dConfirm:'Are you sure you want to remove the Fusion 360 design file from "{{name}}"?',removeTimelapse:"Remove Timelapse",removeTimelapseConfirm:'Are you sure you want to remove the timelapse video from "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Select Timelapse",selectTimelapseDesc:"No auto-match found. Select the timelapse for this print:",deleteArchives:"Delete Archives",deleteArchivesConfirm:"Are you sure you want to delete {{count}} archive(s)? This action cannot be undone.",deleteCount:"Delete {{count}}"},page:{title:"Archives",printsCount:"{{filtered}} of {{total}} prints",dropFilesHere:"Drop .3mf files here",releaseToUpload:"Release to upload",only3mfSupported:"Only .3mf files are supported",close:"Close",selected:"{{count}} selected",selectAll:"Select All",tags:"Tags",project:"Project",favorite:"Favorite",delete:"Delete",toggledFavorites:"Toggled favorites for {{count}} archive(s)",failedUpdateFavorites:"Failed to update favorites",archivesDeleted:"{{count}} archive(s) deleted",failedDeleteArchives:"Failed to delete archives",photoDeleted:"Photo deleted",failedDeletePhoto:"Failed to delete photo"},list:{name:"Name",printer:"Printer",date:"Date",size:"Size",actions:"Actions",hasTimelapse:"Has timelapse"},log:{date:"Date",printName:"Print Name",printer:"Printer",user:"User",status:"Status",duration:"Duration",filament:"Filament",allPrinters:"All Printers",allUsers:"All Users",allStatuses:"All Statuses",cancelled:"Cancelled",skipped:"Skipped",dateFrom:"From",dateTo:"To",noEntries:"No print log entries found",showing:"Showing {{count}} of {{total}} entries",rowsPerPage:"Rows",page:"Page",prev:"Prev",next:"Next",clearLog:"Clear Log",clearLogTitle:"Clear Print Log",clearLogConfirm:"All print log entries will be permanently deleted. Archives and queue items are not affected. This action cannot be undone. Are you sure?",clearLogButton:"Clear All",cleared:"{{count}} log entries cleared",clearFailed:"Failed to clear print log"}},queue:{title:"Print Queue",subtitle:"Schedule and manage your print jobs",addToQueue:"Add to Queue",print:"Print",reprint:"Re-print",schedulePrint:"Schedule Print",editQueueItem:"Edit Queue Item",printToPrinters:"Print to {{count}} Printers",queueToPrinters:"Queue to {{count}} Printers",queueSelectedPlates:"Queue {{count}} Plates",selectAllPlates:"Select All {{count}} Plates",deselectAll:"Deselect All",printQueued:"Print queued",itemsQueued:"{{count}} items queued",sending:"Sending...",sendingProgress:"Sending {{current}}/{{total}}...",adding:"Adding...",addingProgress:"Adding {{current}}/{{total}}...",savingProgress:"Saving {{current}}/{{total}}...",clearQueue:"Clear Queue",clearHistory:"Clear History",emptyQueue:"Queue is empty",position:"Position",scheduledTime:"Scheduled Time",moveUp:"Move Up",moveDown:"Move Down",startNow:"Start Now",printingInProgress:"Printing in progress...",viewArchive:"View archive",viewInFileManager:"View in File Manager",itemCount:"{{count}} item",itemCount_plural:"{{count}} items",dragToReorder:"Drag to reorder (ASAP only)",reorderHint:"Position only affects ASAP items. Scheduled items run at their set time.",sjf:{label:"SJF",tooltip:"Shortest Job First — scheduler prioritizes shorter prints"},addedBy:"Added by {{name}}",nextInQueue:"Next in queue",clearPlate:"Clear Plate & Start Next",clearPlateSuccess:"Plate cleared — ready for next print",plateReady:"Plate cleared — ready for next print",plateNumber:"Plate {{index}}",quantity:"Quantity",quantityHint:"Creates {{count}} queue items",activeBatches:"Active Batches",batchProgress:"{{completed}} of {{total}} completed",cancelBatch:"Cancel Remaining",batchCancelled:"Remaining batch items cancelled",cancelBatchConfirmTitle:"Cancel Batch",cancelBatchConfirmMessage:"Cancel all remaining pending items in this batch?",batch:"Batch",sections:{currentlyPrinting:"Currently Printing",queued:"Queued",history:"History"},status:{pending:"Pending",waiting:"Waiting",printing:"Printing",paused:"Paused",completed:"Completed",failed:"Failed",skipped:"Skipped",cancelled:"Cancelled"},summary:{printing:"Printing",queued:"Queued",totalTime:"Total Queue Time",totalWeight:"Total Queue Weight",history:"History"},filter:{allPrinters:"All Printers",unassigned:"Unassigned",allStatus:"All Status",allLocations:"All Locations",any:"Any"},sort:{byPosition:"Sort by Position",byName:"Sort by Name",byPrinter:"Sort by Printer",bySchedule:"Sort by Schedule",byDate:"Sort by Date",ascendingOldest:"Ascending (oldest first)",descendingNewest:"Descending (newest first)"},badges:{staged:"Staged",requiresPrevious:"Requires previous success",autoPowerOff:"Auto power off",gcodeInjection:"G-code"},empty:{title:"No prints scheduled",description:'Schedule a print from the Archives page using the "Schedule" option in the context menu, or drag and drop files to get started.'},time:{asap:"ASAP",overdue:"Overdue",now:"Now",lessThanMinute:"In less than a minute",inMinutes:"In {{count}} min",inHours:"In {{count}} hours"},actions:{stopPrint:"Stop Print",startPrint:"Start Print",requeue:"Re-queue"},bulkEdit:{title:"Edit {{count}} Item",title_plural:"Edit {{count}} Items",description:"Only changed settings will be applied to selected items.",printer:"Printer",noChange:"— No change —",queueOptions:"Queue Options",staged:"Staged (manual start)",autoPowerOff:"Auto power off after print",requirePrevious:"Require previous success",printOptions:"Print Options",bedLevelling:"Bed levelling",flowCalibration:"Flow calibration",vibrationCalibration:"Vibration calibration",layerInspection:"First layer inspection",timelapse:"Timelapse",useAms:"Use AMS",applyChanges:"Apply Changes",selectAll:"Select All",deselectAll:"Deselect All",selected:"{{count}} selected",editSelected:"Edit Selected",cancelSelected:"Cancel Selected"},confirm:{cancelTitle:"Cancel Scheduled Print",cancelMessage:'Are you sure you want to cancel "{{name}}"?',stopTitle:"Stop Print",stopMessage:'Are you sure you want to stop the current print "{{name}}"? This will cancel the print job on the printer.',removeTitle:"Remove from History",removeMessage:'Are you sure you want to remove "{{name}}" from the queue history?',clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to remove all {{count}} item(s) from the history?",cancelButton:"Cancel Print",stopButton:"Stop Print",thisPrint:"this print",thisItem:"this item"},toast:{cancelled:"Queue item cancelled",cancelFailed:"Failed to cancel item",removed:"Queue item removed",removeFailed:"Failed to remove item",stopped:"Print stopped",stopFailed:"Failed to stop print",released:"Print released to queue",startFailed:"Failed to start print",reorderFailed:"Failed to reorder queue",historyCleared:"Cleared {{count}} history item(s)",clearHistoryFailed:"Failed to clear history",updateFailed:"Failed to update items",bulkCancelled:"Cancelled {{count}} item(s)",bulkCancelFailed:"Failed to cancel items"},timeline:{listView:"List",timelineView:"Timeline",unassigned:"Unassigned",noData:"No scheduled prints for this day",allDoneBy:"All prints estimated done by {{time}}",staged:"Staged",filterAll:"Show All",filterPrinting:"Printing",filterQueued:"Queued",time:{anyMoment:"any moment",minutesLeft:"{{minutes}}m left",hoursLeft:"{{hours}}h left",hoursMinutesLeft:"{{hours}}h {{minutes}}m left"},day:{previous:"Previous day",next:"Next day",today:"Today"}},permissions:{noStopPrint:"You do not have permission to stop prints",noStartPrint:"You do not have permission to start prints",noEdit:"You do not have permission to edit this queue item",noCancel:"You do not have permission to cancel this queue item",noRequeue:"You do not have permission to re-queue items",noRemove:"You do not have permission to remove this queue item",noClearHistory:"You do not have permission to clear all history",noEditItems:"You do not have permission to edit queue items",noCancelItems:"You do not have permission to cancel queue items"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded",printStartedRemaining:"{{completed}} print(s) started, {{remaining}} more sending..."}},stats:{title:"Dashboard",subtitle:"Drag widgets to rearrange. Click the eye icon to hide.",overview:"Overview",totalPrints:"Total Prints",successRate:"Success Rate",totalPrintTime:"Total Print Time",printTime:"Print Time",totalFilament:"Total Filament Used",filamentUsed:"Filament Used",filamentCost:"Filament Cost",totalCost:"Total Cost",energyUsed:"Energy Used",energyCost:"Energy Cost",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",users:"Authentication",backup:"Backup",emailAuth:"Email Authentication",ldap:"LDAP"},ldap:{title:"LDAP Authentication",enabledDesc:"LDAP authentication is enabled",disabledDesc:"LDAP authentication is disabled",disabledHint:"Configure and save LDAP settings below, then enable.",enabled:"LDAP authentication enabled",disabled:"LDAP authentication disabled",feature1:"Users can login with LDAP credentials",feature2:"Local admin account remains as fallback",feature3:"LDAP groups are mapped to BamBuddy groups on login",serverConfig:"LDAP Server Configuration",serverUrl:"Server URL",serverUrlHint:"Use ldaps:// for SSL or ldap:// with StartTLS",security:"Security",securityHint:"StartTLS upgrades a plain connection to TLS. LDAPS uses TLS from the start.",bindDn:"Bind DN (Service Account)",bindPassword:"Bind Password",searchBase:"Search Base DN",userFilter:"User Search Filter",userFilterHint:"{username} is replaced with the login username. Use (uid={username}) for OpenLDAP.",autoProvision:"Auto-provision users",autoProvisionHint:"Automatically create a BamBuddy account on first LDAP login",defaultGroup:"Default group",defaultGroupNone:"— None (no fallback) —",defaultGroupHint:"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped LDAP group. Leave empty to leave unmapped users without permissions.",groupMapping:"Group Mapping (JSON)",groupMappingHint:"Map LDAP group DNs to BamBuddy groups. Available groups: ",testConnection:"Test Connection",settingsSaved:"LDAP settings saved",errors:{serverRequired:"LDAP server URL is required",searchBaseRequired:"Search base DN is required",enableAuthFirst:"Enable authentication first",configureLdapFirst:"Save LDAP settings first"}},email:{smtpSettings:"SMTP Configuration",smtpHost:"SMTP Server",smtpPort:"SMTP Port",security:"Security",authentication:"Authentication",username:"Username",password:"Password",fromEmail:"From Email",fromName:"From Name",testConnection:"Test SMTP Connection",testRecipient:"Test Recipient Email",sendTest:"Send Test Email",sending:"Sending...",save:"Save Settings",saving:"Saving...",advancedAuth:"Advanced Authentication",advancedAuthEnabled:"Advanced Authentication is enabled",advancedAuthEnabledDesc:"Email-based user management features are active. New users will receive auto-generated passwords via email, and users can reset their passwords through the forgot password feature.",advancedAuthDisabled:"Advanced Authentication is disabled",advancedAuthDisabledDesc:"Enable advanced authentication to activate email-based features for user management.",enable:"Enable",disable:"Disable",feature1:"Passwords are auto-generated and emailed to new users",feature2:"Users can login with username or email",feature3:"Forgot password feature is available",feature4:"Admins can reset user passwords via email",errors:{requiredFields:"Please fill in all required fields",usernameRequired:"Username is required when authentication is enabled",enterTestEmail:"Please enter a test email address",smtpServerAndEmail:"Please fill in SMTP Server and From Email before testing",usernamePasswordRequired:"Username and Password are required when authentication is enabled",configureSmtpFirst:"Please configure and test SMTP settings first",enableAuthFirst:"Please enable authentication first to use email-based features."},success:{settingsSaved:"SMTP settings saved successfully"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"None (Port 25)"},authOptions:{enabled:"Enabled",disabled:"Disabled"}},appearance:"Appearance",notifications:"Notifications",smartPlugs:"Smart Plugs",spoolman:"Spoolman",updates:"Updates",language:"Language",languageDescription:"Select your preferred language",theme:"Theme",themeLight:"Light",themeDark:"Dark",themeSystem:"System",defaultView:"Default View",defaultViewDescription:"Page to show when opening the app",checkForUpdates:"Check for Updates",autoUpdate:"Auto Update",currentVersion:"Current Version",latestVersion:"Latest Version",upToDate:"You are up to date",updateAvailable:"Update available",notificationLanguage:"Notification Language",notificationLanguageDescription:"Language for push notifications",bedCooledThreshold:"Bed Cooled Threshold",bedCooledThresholdDescription:"Temperature below which the bed is considered cooled after a print",userNotificationsEnabled:"User Notifications",userNotificationsEnabledDescription:"Enable the user notifications menu and email notifications for print job events. Requires Advanced Authentication.",userNotificationsDisabledHint:"Enable Advanced Authentication to use user notifications.",notificationProviders:"Notification Providers",addProvider:"Add Provider",editProvider:"Edit Provider",providerType:"Provider Type",testNotification:"Test Notification",testSuccess:"Test notification sent successfully",testFailed:"Failed to send test notification",quietHours:"Quiet Hours",quietHoursDescription:"Do not disturb during these hours",quietHoursStart:"Start",quietHoursEnd:"End",events:{title:"Notification Events",printStart:"Print Started",printComplete:"Print Completed",printFailed:"Print Failed",printStopped:"Print Stopped",printProgress:"Progress Milestones",printProgressDescription:"Notify at 25%, 50%, 75%",printerOffline:"Printer Offline",printerError:"Printer Error",filamentLow:"Low Filament",maintenanceDue:"Maintenance Due",maintenanceDueDescription:"Notify when maintenance is needed"},smartPlug:{title:"Smart Plugs",add:"Add Smart Plug",edit:"Edit Smart Plug",name:"Name",ipAddress:"IP Address",linkedPrinter:"Linked Printer",autoOn:"Auto Power On",autoOnDescription:"Turn on when print starts",autoOff:"Auto Power Off",autoOffDescription:"Turn off after print completes",offDelay:"Off Delay",offDelayMinutes:"Minutes after print",offDelayTemp:"When nozzle below temperature",currentState:"Current State",turnOn:"Turn On",turnOff:"Turn Off"},filamentTracking:"Filament Tracking",filamentTrackingDesc:"Choose how to track your filament spools. You can use the built-in inventory or connect an external Spoolman server.",filamentChecks:"Filament checks",disableFilamentWarnings:"Disable filament warnings",disableFilamentWarningsDesc:"Don't show warnings about insufficient filament when printing or queueing",preferLowestFilament:"Prefer lowest remaining filament",preferLowestFilamentDesc:"When multiple spools match, use the one with the least filament remaining",trackingModeBuiltIn:"Built-in Inventory",trackingModeBuiltInDesc:"RFID auto-matching and usage tracking included",trackingModeSpoolmanDesc:"External filament management server",builtInFeatureRfid:"Automatically detects Bambu Lab RFID spools in AMS",builtInFeatureUsage:"Tracks filament consumption per print",builtInFeatureCatalog:"Manage spools, colors, and K-factor profiles",builtInFeatureThirdParty:"Third-party spools can be assigned to inventory spools",amsSyncButton:"Sync Weights from AMS",amsSyncTitle:"Sync Spool Weights from AMS",amsSyncMessage:"This will overwrite all inventory spool weights with the current AMS remain% values from connected printers. Use this to recover from corrupted weight data. Printers must be online.",amsSyncing:"Syncing...",amsSyncSuccess:"{{synced}} spool(s) synced, {{skipped}} skipped",amsSyncError:"Failed to sync weights from AMS",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL of your Spoolman server (e.g., http://localhost:7912)",spoolmanConnected:"Connected",spoolmanDisconnected:"Disconnected",status:"Status",connect:"Connect",disconnect:"Disconnect",howSyncWorks:"How Sync Works",syncInfoRfidOnly:"Only official Bambu Lab spools with RFID are synced",syncInfoAutoCreate:"New spools are auto-created in Spoolman on first sync",syncInfoThirdPartySkipped:"Non-Bambu Lab spools (third-party, refilled) are skipped",linkingExistingSpools:"Linking Existing Spools",linkingExistingSpoolsDesc:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".',syncMode:"Sync Mode",syncModeAuto:"Automatic",syncModeManual:"Manual Only",syncModeAutoDesc:"AMS data syncs automatically when changes are detected",syncModeManualDesc:"Only sync when manually triggered",syncAmsData:"Sync AMS Data",syncAmsDataDesc:"Manually sync printer AMS data to Spoolman",allPrinters:"All Printers",noDefaultPrinter:"No default (ask each time)",sidebarOrder:"Sidebar order",saveThumbnails:"Save thumbnails",captureFinishPhoto:"Capture finish photo",noPrintersConfigured:"No printers configured",archiveMode:{always:"Always create archive entry",never:"Never create archive entry",ask:"Ask each time"},checkForUpdatesLabel:"Check for updates",checkPrinterFirmware:"Check printer firmware",includeBetaUpdates:"Include beta versions",includeBetaUpdatesDesc:"Notify about beta and prerelease versions when checking for updates",enableRetry:"Enable retry",homeAssistantDescription:"Control smart plugs via Home Assistant",environmentManagedLabel:"(Environment Managed)",autoEnabledViaEnv:"Automatically enabled via environment variables",urlFromEnvReadOnly:"Value set by HA_URL environment variable (read-only)",tokenFromEnvReadOnly:"Value set by HA_TOKEN environment variable (read-only)",mqttConnectedTo:"Connected to",prometheusDescription:"Expose printer data in Prometheus format",noSmartPlugsTitle:"No smart plugs configured",noSmartPlugsDescription:"Add a Tasmota-based smart plug to track energy usage and automate power control.",noProvidersTitle:"No providers configured",noProvidersDescription:"Add a provider to receive alerts.",noTemplatesAvailable:"No templates available. Restart the backend to seed default templates.",apiPermissionView:"View printer status and queue",apiPermissionEdit:"Add and remove items from print queue",apiKeysEmptyTitle:"No API keys",apiKeysEmptyDescription:"Create an API key to integrate with external services.",noUsersFound:"No users found",noGroupsFound:"No groups found",noGroupsAvailable:"No groups available",passwordsDoNotMatch:"Passwords do not match",systemGroupWarning:"System group names cannot be changed",authDisabledTitle:"Authentication is Disabled",authDisabledFeature1:"Require login to access the system",authDisabledFeature2:"Create multiple users with group-based permissions",authDisabledFeature3:"Control access with 50+ granular permissions",userHasCreated:"This user has created:",userItemsQuestion:"What would you like to do with these items?",deleteUserConfirm:"Are you sure you want to delete this user?",actionCannotBeUndone:"This action cannot be undone.",addFirstSmartPlug:"Add Your First Smart Plug",providers:"Providers",log:"Log",testAll:"Test All",testResults:"Test Results",testPassedCount:"{{count}} passed",testFailedCount:"{{count}} failed",messageTemplates:"Message Templates",messageTemplatesDescription:"Customize notification messages for each event.",apiKeys:"API Keys",apiKeysDescription:"Create API keys for external integrations and webhooks.",createKey:"Create Key",apiKeyCreated:"API Key Created Successfully",apiKeyCopyWarning:"Copy this key now - it won't be shown again!",useInApiBrowser:"Use in API Browser",createNewApiKey:"Create New API Key",keyName:"Key Name",keyNamePlaceholder:"e.g., Home Assistant, OctoPrint",readStatus:"Read Status",readStatusDescription:"View printer status and queue",manageQueue:"Manage Queue",manageQueueDescription:"Add and remove items from print queue",controlPrinter:"Control Printer",controlPrinterDescription:"Pause, resume, and stop prints",unnamedKey:"Unnamed Key",lastUsed:"Last used",read:"Read",control:"Control",createFirstKey:"Create Your First Key",webhookEndpoints:"Webhook Endpoints",webhookApiKeyHint:"Use your API key in the X-API-Key header.",webhook:{getAllStatus:"Get all printer status",getSpecificStatus:"Get specific printer status",addToQueue:"Add to print queue",pausePrint:"Pause print",resumePrint:"Resume print",stopPrint:"Stop print"},apiBrowser:"API Browser",apiBrowserDescription:"Explore and test all available API endpoints.",apiKeyForTesting:"API Key for Testing",apiKeyPlaceholder:"Paste your API key here to test authenticated endpoints...",apiKeyHint:"This key will be sent as X-API-Key header with requests.",deleteApiKeyTitle:"Delete API Key",deleteApiKeyMessage:"Are you sure you want to delete this API key? Any integrations using this key will stop working.",deleteKey:"Delete Key",amsDisplayThresholds:"AMS Display Thresholds",amsThresholdsDescription:"Configure color thresholds for AMS humidity and temperature indicators.",humidity:"Humidity",goodGreen:"Good (green)",fairOrange:"Fair (orange)",aboveFairBad:"Above fair threshold shows as red (bad)",fairAlsoDryingThreshold:"This threshold is also used to trigger auto-drying when enabled",temperature:"Temperature",goodBlue:"Good (blue)",aboveFairHot:"Above fair threshold shows as red (hot)",historyRetention:"History Retention",keepSensorHistory:"Keep sensor history for",historyRetentionDescription:"Older humidity and temperature data will be automatically deleted",defaultPrintOptions:"Default Print Options",defaultPrintOptionsDescription:"Set default values for print options when starting new prints. These can be overridden per print in the print dialog.",defaultBedLevelling:"Bed Levelling",defaultBedLevellingDesc:"Auto-level bed before print",defaultFlowCali:"Flow Calibration",defaultFlowCaliDesc:"Calibrate extrusion flow",defaultVibrationCali:"Vibration Calibration",defaultVibrationCaliDesc:"Reduce ringing artifacts",defaultLayerInspect:"First Layer Inspection",defaultLayerInspectDesc:"AI inspection of first layer",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Record timelapse video",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Plate-Clear Confirmation",requirePlateClear:"Require plate-clear confirmation",requirePlateClearDescription:"When enabled, the scheduler waits for per-printer plate-clear confirmation before starting queued prints on printers with finished jobs. Disable for farm workflows where plates are verified physically.",gcodeInjection:"G-code Injection",gcodeInjectionDescription:'Configure custom G-code to inject at the start and/or end of prints for auto-print systems like Farmloop, SwapMod, AutoClear, and Printflow 3D. Snippets are configured per printer model and applied when "Inject G-code" is enabled on a queue item.',gcodeInjectionNoPrinters:"No printers found. Add printers to configure G-code snippets.",gcodeStartLabel:"Start G-code",gcodeEndLabel:"End G-code",gcodeStartPlaceholder:"G-code prepended before the print starts...",gcodeEndPlaceholder:"G-code appended after the print ends...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Queue Auto-Drying",queueDryingDescription:"Automatically dry AMS filament when printer is idle between queued prints. Uses humidity threshold above to trigger drying.",queueDryingEnabled:"Enable auto-drying",queueDryingEnabledDescription:"Start AMS drying automatically when printer is idle and humidity is above threshold",queueDryingBlock:"Wait for drying to complete",queueDryingBlockDescription:"Block the print queue until drying finishes. When off, prints take priority over drying.",ambientDryingEnabled:"Ambient drying",ambientDryingEnabledDescription:"Automatically dry filament on idle printers when humidity exceeds threshold, even without queued prints.",dryingPresets:"Drying Presets",dryingPresetsDescription:"Temperature and duration per filament type. AMS 2 Pro uses lower temps, AMS-HT supports higher temps.",dryingFilament:"Filament",printModal:"Print Modal",expandCustomMapping:"Expand custom mapping by default",expandCustomMappingDescription:"When printing to multiple printers, show per-printer AMS mapping expanded",authentication:"Authentication",authEnabledDescription:"Your instance is secured with user authentication",authDisabledDescription:"Enable to require login and manage user access",authDisabledMessage:"Enable authentication to create user accounts, manage permissions, and secure your Bambuddy instance.",enableAuthentication:"Enable Authentication",currentUser:"Current User",changePassword:"Change Password",admin:"Admin",users:"Users",addUser:"Add User",groups:"Groups",addGroup:"Add Group",system:"System",noDescription:"No description",userCount:"{{count}} users",permissionCount:"{{count}} permissions",createUser:"Create User",username:"Username",enterUsername:"Enter username",password:"Password",enterPassword:"Enter password (min 6 characters)",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm password",viewReleaseOnGitHub:"View release on GitHub",turnAllPlugsOn:"Turn all plugs on",turnAllPlugsOff:"Turn all plugs off",clearNotificationLogs:"Clear Notification Logs",clearLogsMessage:"This will permanently delete all notification logs older than 30 days. This action cannot be undone.",clearLogs:"Clear Logs",resetUiPreferences:"Reset UI Preferences",resetUiPreferencesMessage:"This will reset all UI preferences to defaults: sidebar order, theme, dashboard layout, view modes, and sorting preferences. Your printers, archives, and server settings will NOT be affected. The page will reload after clearing.",resetPreferences:"Reset Preferences",deleteGroupTitle:"Delete Group",deleteGroupMessage:"Are you sure you want to delete this group? Users in this group will lose these permissions.",deleteGroup:"Delete Group",disableAuthenticationTitle:"Disable Authentication",disableAuthenticationMessage:"Are you sure you want to disable authentication? This will make your Bambuddy instance accessible without login. All users will remain in the database but authentication will be disabled.",disableAuthentication:"Disable Authentication",configureBambuddy:"Configure Bambuddy",systemDefault:"System Default",archiveSettings:"Archive Settings",newWindow:"New Window",embeddedOverlay:"Embedded Overlay",preferredSlicer:"Preferred Slicer",preferredSlicerDescription:"Choose which slicer application to open files with",externalCameras:"External Cameras",costTracking:"Cost Tracking",printsOnly:"Prints Only",totalConsumption:"Total Consumption",dataManagement:"Data Management",storageUsage:"Storage Usage",storageUsageDescription:"Breakdown of data usage by category",storageUsageTotal:"Total",storageUsageErrors:"Errors",storageUsageOtherBreakdown:"Other (includes static assets, scripts, and configuration files)",storageUsageSystem:"System",storageUsageData:"Data",storageUsageUnavailable:"Storage usage information unavailable",clearNotificationLogsDescription:"Delete notification logs older than 30 days",resetUiPreferencesDescription:"Reset sidebar order, theme, view modes, and layout preferences. Printers, archives, and settings are not affected.",enableHomeAssistant:"Enable Home Assistant",enableMqtt:"Enable MQTT",useTls:"Use TLS",enableMetricsEndpoint:"Enable Metrics Endpoint",availableMetrics:"Available Metrics",editUser:"Edit User",deleteUserTitle:"Delete User",groupName:"Group Name",leaveEmptyForAnonymous:"Leave empty for anonymous",leaveEmptyForNoAuth:"Leave empty for no authentication",enterNewPassword:"Enter new password",confirmNewPassword:"Confirm new password",enterGroupName:"Enter group name",enterDescriptionOptional:"Enter description (optional)",enterCurrentPassword:"Enter current password",enterNewPasswordMin6:"Enter new password (min 6 characters)",toast:{keyCopied:"Key copied to clipboard",copyFailed:"Failed to copy key",keyAddedToBrowser:"Key added to API Browser",clearLogsFailed:"Failed to clear logs",uiPreferencesReset:"UI preferences reset. Refreshing...",authDisabled:"Authentication disabled successfully",authDisableFailed:"Failed to disable authentication",apiKeyCreated:"API key created",apiKeyDeleted:"API key deleted",userCreated:"User created successfully",userUpdated:"User updated successfully",userDeleted:"User deleted successfully",groupCreated:"Group created successfully",groupUpdated:"Group updated successfully",groupDeleted:"Group deleted successfully",fillRequiredFields:"Please fill in all required fields",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters",enterGroupName:"Please enter a group name",settingsSaved:"Settings saved",cameraSettingsSaved:"Camera settings saved",enterCameraUrl:"Please enter a camera URL",passwordChanged:"Password changed successfully",connectionFailed:"Connection failed",testFailed:"Test failed",cameraConnected:"Camera connected{{resolution}}"},testConnection:"Test Connection",catalog:{spoolCatalog:"Spool Catalog",spoolCatalogDescription:"Empty spool weights by brand/type. Used for automatic weight lookup when adding spools.",searchCatalog:"Search catalog...",addNewEntry:"Add New Entry",namePlaceholder:"Name (e.g., Bambu Lab - Plastic)",weight:"Weight",type:"Type",default:"Default",custom:"Custom",noMatch:"No entries match your search",empty:"No entries in catalog",deleteEntry:"Delete Entry",deleteConfirm:'Are you sure you want to delete "{{name}}"?',resetCatalog:"Reset Catalog",resetConfirm:"Reset catalog to defaults? This will remove all custom entries.",loadFailed:"Failed to load spool catalog",nameWeightRequired:"Name and weight are required",entryAdded:"Entry added",addFailed:"Failed to add entry",entryUpdated:"Entry updated",updateFailed:"Failed to update entry",entryDeleted:"Entry deleted",deleteFailed:"Failed to delete entry",resetSuccess:"Catalog reset to defaults",resetFailed:"Failed to reset catalog",exported:"Exported {{count}} entries",imported:"Imported {{added}} entries ({{skipped}} skipped)",importFailed:"Failed to import: invalid JSON format",exportTooltip:"Export catalog to JSON",importTooltip:"Import catalog from JSON",resetTooltip:"Reset to defaults",selectedCount:"{{count}} selected",deleteSelected:"Delete Selected",bulkDeleteConfirm:"Are you sure you want to delete {{count}} entries?",bulkDeleted:"Deleted {{count}} entries",bulkDeleteFailed:"Failed to delete entries"},colorCatalog:{title:"Color Catalog",description:"Filament colors by manufacturer/material. Used for automatic color lookup when adding spools.",searchColors:"Search colors...",allManufacturers:"All manufacturers",addNewColor:"Add New Color",manufacturer:"Manufacturer",colorName:"Color Name",hex:"Hex",materialOptional:"Material (optional)",showing:"Showing {{filtered}} of {{total}} colors",noMatch:"No colors match your search",empty:"No colors in catalog",deleteColor:"Delete Color",deleteConfirm:'Are you sure you want to delete "{{name}}"?',resetCatalog:"Reset Color Catalog",resetConfirm:"Reset catalog to defaults? This will remove all custom colors.",sync:"Sync",starting:"Starting...",syncTooltip:"Sync from FilamentColors.xyz (2000+ colors, may take a minute)",loadFailed:"Failed to load color catalog",fieldsRequired:"Manufacturer, color name, and hex color are required",colorAdded:"Color added",addFailed:"Failed to add color",colorUpdated:"Color updated",updateFailed:"Failed to update color",colorDeleted:"Color deleted",deleteFailed:"Failed to delete color",resetSuccess:"Color catalog reset to defaults",resetFailed:"Failed to reset catalog",syncUpToDate:"Already up to date ({{count}} colors checked)",syncComplete:"Added {{added}} new colors ({{skipped}} already existed)",syncError:"Sync error",syncFailed:"Failed to sync from FilamentColors.xyz",exported:"Exported {{count}} colors",imported:"Imported {{added}} colors ({{skipped}} skipped)",importFailed:"Failed to import: invalid JSON format",selectedCount:"{{count}} selected",deleteSelected:"Delete Selected",bulkDeleteConfirm:"Are you sure you want to delete {{count}} colors?",bulkDeleted:"Deleted {{count}} colors",bulkDeleteFailed:"Failed to delete colors"},dateFormat:"Date Format",dateFormatUs:"US (MM/DD/YYYY)",dateFormatEu:"EU (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"Time Format",timeFormat12:"12-hour (3:30 PM)",timeFormat24:"24-hour (15:30)",defaultPrinter:"Default Printer",defaultPrinterDescription:"Pre-select this printer for uploads, reprints, and other operations.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Drag items in the sidebar to reorder. Reset to default order here.",setDefault:"Set Default",sidebarOrderSetDefaultHint:"Set default applies the current menu order to users who haven't customized theirs.",sidebarDefaultSet:"Default menu order has been set.",sidebarDefaultCleared:"Default menu order cleared.",sidebarDefaultFailed:"Failed to set default menu order.",reset:"Reset",darkMode:"Dark Mode",lightMode:"Light Mode",active:"(active)",background:"Background",accent:"Accent",style:"Style",bgNeutral:"Neutral",bgWarm:"Warm",bgCool:"Cool",bgOled:"OLED Black",bgSlate:"Slate Blue",bgForest:"Forest Green",accentGreen:"Green",accentTeal:"Teal",accentBlue:"Blue",accentOrange:"Orange",accentPurple:"Purple",accentRed:"Red",styleClassic:"Classic",styleGlow:"Glow",styleVibrant:"Vibrant",themeToggleHint:"Toggle between dark and light mode using the sun/moon icon in the sidebar.",autoArchivePrints:"Auto-archive prints",autoArchiveDescription:"Automatically save 3MF files when prints complete",saveThumbnailsDescription:"Extract and save preview images from 3MF files",captureFinishPhotoDescription:"Take a photo from printer camera when print completes",ffmpegNotInstalled:"ffmpeg not installed",ffmpegRequired:"Camera capture requires ffmpeg. Install it via <brew>brew install ffmpeg</brew> (macOS) or <apt>apt install ffmpeg</apt> (Linux).",camera:"Camera",cameraViewMode:"Camera View Mode",cameraOverlayDescription:"Camera opens in a resizable overlay on the main screen",cameraWindowDescription:"Camera opens in a separate browser window",externalCamerasDescription:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos.",cameraPlaceholderUsb:"Device path (/dev/video0)",cameraPlaceholderUrl:"Camera URL (rtsp://... or http://...)",cameraTypeMjpeg:"MJPEG Stream",cameraTypeRtsp:"RTSP Stream",cameraTypeSnapshot:"HTTP Snapshot",cameraTypeUsb:"USB Camera (V4L2)",cameraRotation:"Rotation",test:"Test",connected:"Connected",disconnected:"Disconnected",currency:"Currency",defaultFilamentCost:"Default filament cost (per kg)",electricityCost:"Electricity cost per kWh",energyDisplayMode:"Energy display mode",energyModePrintDescription:"Dashboard shows sum of energy used during prints",energyModeTotalDescription:"Dashboard shows lifetime energy from smart plugs",fileManager:"File Manager",createArchiveEntry:"Create Archive Entry When Printing",createArchiveEntryDescription:"When printing from File Manager, optionally create an archive entry",lowDiskSpaceWarning:"Low Disk Space Warning",lowDiskSpaceDescription:"Show warning when free disk space falls below this threshold",printerFirmware:"Printer Firmware",checkFirmwareDescription:"Check for printer firmware updates from Bambu Lab",bambuddySoftware:"Bambuddy Software",autoCheckDescription:"Automatically check for new versions on startup",checkNow:"Check now",updateAvailableVersion:"Update available: v{{version}}",releaseNotes:"Release Notes",updateViaDocker:"Update via Docker Compose:",installUpdate:"Install Update",latestVersionRunning:"You're running the latest version",failedToCheckUpdates:"Failed to check for updates: {{error}}",backupRestore:"Backup & Restore",backupRestoreDescription:"Export/import settings and configure GitHub backup",goToBackup:"Go to Backup",externalUrl:"External URL",externalUrlDescription:"The external URL where Bambuddy is accessible. Used for notification images and external integrations.",bambuddyUrl:"Bambuddy URL",externalUrlHint:"Include protocol and port (e.g., http://192.168.1.100:8000)",ftpRetry:"FTP Retry",ftpRetryDescription:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates.",autoRetryDescription:"Automatically retry failed FTP operations",retryAttempts:"Retry attempts",retryDelay:"Retry delay",connectionTimeout:"Connection timeout",time_one:"{{count}} time",time_other:"{{count}} times",second_one:"{{count}} second",second_other:"{{count}} seconds",nSeconds:"{{count}} seconds",increaseForWeakWifi:"Increase for printers with weak WiFi",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities.",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"Long-Lived Access Token",haTokenHint:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token",connectionSuccessful:"Connection Successful",connectionFailed:"Connection Failed",haConnectionSuccess:"Successfully connected to Home Assistant.",haConnectionFailed:"Failed to connect to Home Assistant.",mqttPublishing:"MQTT Publishing",mqttDescription:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems.",mqttEnableDescription:"Publish events to external MQTT broker",brokerHostname:"Broker hostname",port:"Port",usernameOptional:"Username (optional)",passwordOptional:"Password (optional)",topicPrefix:"Topic prefix",topicPrefixHint:"Topics will be: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Prometheus Metrics",prometheusEndpointDescription:"Expose printer metrics at <code>/api/v1/metrics</code> for Prometheus/Grafana monitoring.",bearerTokenOptional:"Bearer Token (optional)",bearerTokenHint:"If set, requests must include <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Connection status",metricsPrinterState:"Printer state (idle/printing/etc)",metricsPrintProgress:"Print progress 0-100%",metricsBedTemp:"Bed temperature",metricsNozzleTemp:"Nozzle temperature",metricsPrintsTotal:"Total prints by result",metricsMore:"...and more (layers, fans, queue, filament usage)",smartPlugsDescription:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers.",allOn:"All On",allOff:"All Off",addSmartPlug:"Add Smart Plug",energySummary:"Energy Summary",currentPower:"Current Power",plugsOnline:"{{reachable}}/{{total}} plugs online",today:"Today",yesterday:"Yesterday",total:"Total",enablePlugsForSummary:"Enable plugs to see energy summary",addNotificationProvider:"Add",systemBadge:"(System)",creating:"Creating...",changing:"Changing...",deleteUserAndItems:"Delete user AND their items",deleteUserKeepItems:"Delete user, keep items (become ownerless)",ok:"OK"},notification:{printStarted:{title:"Print Started",body:"{{printer}}: {{filename}} has started printing"},printCompleted:{title:"Print Completed",body:"{{printer}}: {{filename}} completed successfully"},printFailed:{title:"Print Failed",body:"{{printer}}: {{filename}} has failed"},printStopped:{title:"Print Stopped",body:"{{printer}}: {{filename}} was stopped"},printProgress:{title:"Print Progress",body:"{{printer}}: {{filename}} is {{percent}}% complete"},printerOffline:{title:"Printer Offline",body:"{{printer}} is offline"},printerError:{title:"Printer Error",body:"{{printer}}: {{error}}"},filamentLow:{title:"Low Filament",body:"{{printer}}: Filament is running low"},maintenanceDue:{title:"Maintenance Due",body:"{{printer}}: {{items}} need attention"}},errors:{generic:"Something went wrong",networkError:"Network error. Please check your connection.",notFound:"Not found",unauthorized:"Unauthorized",serverError:"Server error",validationError:"Please check your input",printerConnectionFailed:"Failed to connect to printer",saveFailed:"Failed to save changes",deleteFailed:"Failed to delete",loadFailed:"Failed to load data"},hmsErrors:{title:"Errors - {{name}}",noErrors:"No errors",viewOnWiki:"View on Bambu Lab Wiki",clearInstructions:"Clear errors on the printer to dismiss them here.",clearErrors:"Clear Errors",clearSuccess:"HMS errors cleared",clearFailed:"Failed to clear HMS errors"},mqttDebug:{title:"MQTT Debug Log",searchPlaceholder:"Search topic or payload...",noMessages:"No messages logged yet",startLoggingHint:'Click "Start Logging" to begin capturing MQTT messages',noMessagesMatch:"No messages match your filter",adjustFilterHint:"Try adjusting your search or filter criteria",incoming:"Incoming",outgoing:"Outgoing",loggingStopped:"Logging stopped",loggingActive:"Logging active - messages will auto-refresh",startLogging:"Start Logging",stopLogging:"Stop Logging",clearLog:"Clear Log",topic:"Topic",timestamp:"Timestamp",direction:"Direction",all:"All"},printerFiles:{title:"File Manager",storageUsed:"Used:",storageFree:"Free:",filterPlaceholder:"Filter files...",deleteButton:"Delete",deleteFiles:"Delete {{count}} Files",deleteFileConfirm:'Delete "{{name}}"? This cannot be undone.',deleteFilesConfirm:"Delete {{count}} selected files? This cannot be undone.",noFiles:"No files on printer",loadingFiles:"Loading files...",failedToLoad:"Failed to load files",toast:{filesDeleted:"Deleted {{count}} file(s)",deleteFailed:"Delete failed: {{error}}"}},confirm:{delete:"Are you sure you want to delete this?",unsavedChanges:"You have unsaved changes. Are you sure you want to leave?",clearQueue:"Are you sure you want to clear the queue?"},login:{title:"Bambuddy Login",subtitle:"Sign in to your account",username:"Username",usernamePlaceholder:"Enter your username",usernameOrEmail:"Username or Email",usernameOrEmailPlaceholder:"Username or @ Email",password:"Password",passwordPlaceholder:"Enter your password",signIn:"Sign in",signingIn:"Logging in...",forgotPassword:"Forgot your password?",loginSuccess:"Logged in successfully",loginFailed:"Login failed",enterCredentials:"Please enter username and password",forgotPasswordTitle:"Forgot Password",forgotPasswordMessage:"If you've forgotten your password, please contact your system administrator to reset it.",forgotPasswordEmailMessage:"Enter your email address and we'll send you a new password.",emailAddress:"Email Address",emailPlaceholder:"your.email@example.com",cancel:"Cancel",sending:"Sending...",sendResetEmail:"Send Reset Email",howToReset:"How to reset your password:",resetStep1:"Contact your Bambuddy administrator",resetStep2:"Ask them to reset your password in User Management",resetStep3:"They can set a new temporary password for you",resetStep4:"Log in with the new password and change it in Settings",gotIt:"Got it"},setup:{title:"Bambuddy Setup",subtitle:"Configure authentication for your Bambuddy instance",enableAuth:"Enable Authentication",adminAccount:"Admin Account",adminAccountDesc:"If admin users already exist, authentication will be enabled using the existing admin accounts. Leave the fields below empty to use existing admins, or enter new credentials to create a new admin user.",adminUsername:"Admin Username",adminPassword:"Admin Password",optionalIfAdminExists:"(optional if admin users exist)",adminUsernamePlaceholder:"Enter admin username (optional)",adminPasswordPlaceholder:"Enter admin password (optional)",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm admin password",settingUp:"Setting up...",completeSetup:"Complete Setup",toast:{authEnabledAdminCreated:"Authentication enabled and admin user created",authEnabledExistingAdmins:"Authentication enabled using existing admin users",setupCompleted:"Setup completed",enterBothCredentials:"Please enter both admin username and password, or leave both empty to use existing admin users",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters"}},changePassword:{title:"Change Password",currentPassword:"Current Password",currentPasswordPlaceholder:"Enter current password",newPassword:"New Password",newPasswordPlaceholder:"Enter new password (min 6 characters)",confirmPassword:"Confirm New Password",confirmPasswordPlaceholder:"Confirm new password",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters",changing:"Changing...",success:"Password changed successfully",failed:"Failed to change password"},plateAlert:{title:"Print Paused!",message:"Objects detected on build plate. The print has been automatically paused. Please clear the plate and resume the print.",understand:"I Understand"},camera:{title:"Camera View",invalidPrinterId:"Invalid printer ID",live:"Live",snapshot:"Snapshot",restartStream:"Restart stream",refreshSnapshot:"Refresh snapshot",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",connectingToCamera:"Connecting to camera...",capturingSnapshot:"Capturing snapshot...",connectionLost:"Connection lost",connectionFailed:"Camera connection failed",reconnecting:"Reconnecting in {{countdown}}s... (attempt {{attempt}}/{{max}})",reconnectNow:"Reconnect now",cameraUnavailable:"Camera unavailable",cameraUnavailableDesc:"Make sure the printer is powered on and connected.",noCamera:"No camera available",retry:"Retry",cameraStream:"Camera stream",zoomOut:"Zoom out",zoomIn:"Zoom in",resetZoom:"Reset zoom",recording:"Recording",startRecording:"Start Recording",stopRecording:"Stop Recording",chamberLight:"Toggle chamber light"},groups:{title:"Group Management",subtitle:"Manage permission groups for access control",backToSettings:"Back to Settings",createGroup:"Create Group",noPermission:"You do not have permission to access this page.",system:"System",noDescription:"No description",usersCount:"{{count}} users",permissionsCount:"{{count}} permissions",edit:"Edit",delete:"Delete",toast:{created:"Group created successfully",updated:"Group updated successfully",deleted:"Group deleted successfully",enterGroupName:"Please enter a group name"},modal:{editGroup:"Edit Group",createGroup:"Create Group",cancel:"Cancel",saving:"Saving...",creating:"Creating...",saveChanges:"Save Changes"},form:{groupName:"Group Name",groupNamePlaceholder:"Enter group name",systemGroupWarning:"System group names cannot be changed",description:"Description",descriptionPlaceholder:"Enter description (optional)",permissions:"Permissions ({{count}} selected)"},deleteModal:{title:"Delete Group",message:"Are you sure you want to delete this group? Users in this group will lose these permissions.",confirm:"Delete Group"},editor:{title:"Edit Group",createTitle:"Create Group",search:"Search permissions...",selectAll:"Select All",clearAll:"Clear All",permissionsSelected:"{{count}} selected",noResults:"No permissions match your search"}},users:{title:"User Management",subtitle:"Manage users and their access to your Bambuddy instance",backToSettings:"Back to Settings",createUser:"Create User",noPermission:"You do not have permission to access this page.",admin:"Admin",noGroups:"No groups",active:"Active",inactive:"Inactive",edit:"Edit",delete:"Delete",system:"System",noGroupsAvailable:"No groups available",table:{username:"Username",groups:"Groups",status:"Status",actions:"Actions"},toast:{created:"User created successfully",updated:"User updated successfully",deleted:"User deleted successfully",fillRequired:"Please fill in all required fields",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters"},modal:{createUser:"Create User",editUser:"Edit User",cancel:"Cancel",creating:"Creating...",saving:"Saving...",saveChanges:"Save Changes",advancedAuthSubtitle:"with Advanced Authentication"},form:{username:"Username",usernamePlaceholder:"Enter username",email:"Email",emailPlaceholder:"user@example.com",password:"Password",passwordPlaceholder:"Enter password",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm password",newPasswordPlaceholder:"Enter new password",confirmNewPasswordPlaceholder:"Confirm new password",leaveBlankToKeep:"leave blank to keep current",groups:"Groups",optional:"optional",autoGeneratedPassword:"A secure password will be automatically generated and emailed to the user.",passwordManagedByAdvancedAuth:'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.',resetPassword:"Reset Password",resettingPassword:"Resetting Password..."},deleteModal:{title:"Delete User",message:"Are you sure you want to delete this user? This action cannot be undone.",confirm:"Delete User"}},streamOverlay:{title:"Stream Overlay",invalidPrinterId:"Invalid printer ID",cameraStream:"Camera stream",progress:"Progress",eta:"ETA",printerIdle:"Printer is idle",printerOffline:"Printer offline",status:{printing:"Printing",paused:"Paused",finished:"Finished",failed:"Failed",idle:"Idle",unknown:"Unknown"}},profiles:{title:"Profiles",subtitle:"Manage your slicer presets and pressure advance calibrations",tabs:{cloud:"Cloud Profiles",local:"Local Profiles",kprofiles:"K-Profiles"},localProfiles:{title:"Local Profiles",subtitle:"Import and manage slicer presets from OrcaSlicer",import:"Import Profiles",importDesc:"Drop .bbscfg, .bbsflmt, .orca_filament, .zip, or .json files here",importing:"Importing...",search:"Search local presets...",noPresets:"No local presets yet",badge:"Local",edit:"Edit",delete:"Delete",cancel:"Cancel",deleteConfirmTitle:"Delete Preset",deleteConfirm:"Are you sure you want to delete this preset? This cannot be undone.",source:"Source",inheritsFrom:"Inherits",filamentType:"Type",vendor:"Vendor",compatiblePrinters:"Printers",nozzleTemp:"Nozzle Temp",cost:"Cost",density:"Density",pressureAdvance:"Pressure Advance",filament:"Filament",process:"Process",printer:"Printer",toast:{importSuccess:"{{count}} preset(s) imported",importSkipped:"{{count}} preset(s) skipped (duplicates)",importError:"{{count}} error(s) during import",deleted:"Preset deleted",updated:"Preset updated"}},connectedAs:"Connected as",logout:"Logout",noLogoutPermission:"You do not have permission to logout",failedToLoad:"Failed to load profiles",retry:"Retry",time:{justNow:"Just now",minsAgo:"{{count}}m ago",hoursAgo:"{{count}}h ago",daysAgo:"{{count}}d ago"},toast:{loggedOut:"Logged out"},login:{title:"Connect to Bambu Cloud",subtitle:"Sync your slicer presets across devices",email:"Email",password:"Password",region:"Region",regionGlobal:"Global",regionChina:"China",verificationCode:"Verification Code",totpCode:"Authenticator Code",checkEmail:"Check your email ({{email}}) for a 6-digit code",enterTotpHint:"Enter the 6-digit code from your authenticator app",accessToken:"Access Token",accessTokenHint:"Paste your Bambu Lab access token (from Bambu Studio)",back:"Back",loginButton:"Login",verifyButton:"Verify",setTokenButton:"Set Token",useToken:"Use access token instead",useEmail:"Login with email instead",toast:{loggedIn:"Logged in successfully",codeSent:"Verification code sent to your email",enterTotp:"Enter code from your authenticator app",tokenSet:"Token set successfully"}},presets:{myPreset:"My preset (editable)",duplicate:"Duplicate",editable:"Editable",failedToLoadDetails:"Failed to load preset details",deleteConfirm:"Delete this preset?",deleteWarning:'This will permanently delete "{{name}}" from Bambu Cloud. This cannot be undone.',noDuplicatePermission:"You do not have permission to duplicate presets",noEditPermission:"You do not have permission to edit presets",noDeletePermission:"You do not have permission to delete presets",types:{filament:"Filament preset",printer:"Printer preset",process:"Process preset"},toast:{deleted:"Preset deleted",created:"Preset created",updated:"Preset updated",duplicated:"Preset duplicated",fieldAdded:'Field "{{key}}" added',exported:"Preset exported"},baseLabel:"Base: {{name}}",currentLabel:"Current: {{name}}",newPreset:"New Preset",editPreset:"Edit Preset",duplicatePreset:"Duplicate Preset",createNewPreset:"Create New Preset",customizeSettings:"Customize settings for your new preset",compareWithBase:"Compare with base preset",compare:"Compare",basePreset:"Base Preset",selectBasePreset:"Select base preset...",presetName:"Preset Name",myCustomPreset:"My custom preset",inheritsFrom:"Inherits from",dropJsonToImport:"Drop JSON to import",tabs:{common:"Common",allFields:"All Fields"},availableFields:"Available Fields",searchFieldsPlaceholder:"Search fields...",noMatchingFields:"No matching fields",allFieldsAdded:"All fields added",addCustomField:"Add custom field",yourOverrides:"Your Overrides",noOverridesYet:"No overrides yet",clickFieldsToAdd:"Click fields on the left to add them",saveAsTemplate:"Save as template",jsonTip:"Tip: Drag & drop a .json file anywhere on this modal to import settings"},cloudView:{searchPlaceholder:"Search presets...",templates:"Templates",refresh:"Refresh",newPreset:"New Preset",clearFilters:"Clear filters",compareMode:"Compare Mode",selectAnotherPreset:"Select another {{type}} preset",clickTwoPresets:"Click two presets of the same type to compare",selectFirst:"1. Select first",selectSecond:"2. Select second",compareNow:"Compare Now",lastSynced:"Last synced:",showingCount:"Showing {{showing}} of {{total}} presets",noPresetsFound:"No presets found",columns:{filament:"Filament",process:"Process",printer:"Printer"},noFilamentPresets:"No filament presets",noProcessPresets:"No process presets",noPrinterPresets:"No printer presets",filters:{type:"Type",owner:"Owner",printer:"Printer",nozzle:"Nozzle",filament:"Filament",layer:"Layer",all:"All",myPresets:"My Presets",builtIn:"Built-in",process:"Process"},noTemplatesPermission:"You do not have permission to manage templates",noRefreshPermission:"You do not have permission to refresh profiles",noCreatePermission:"You do not have permission to create presets"},templates:{title:"Quick Templates",noTemplates:"No templates yet",createFirst:"Create templates from the preset editor",typeFilter:"Type:",deleteTitle:"Delete Template",deleteWarning:"This action cannot be undone",deleteConfirm:'Are you sure you want to delete "{{name}}"?',namePlaceholder:"Template name",descriptionPlaceholder:"Description",settingsJson:"Settings (JSON)",fieldsCount:"{{count}} fields",shownInModals:"Shown in modals",hiddenInModals:"Hidden in modals",apply:"Apply",toast:{deleted:"Template deleted",updated:"Template updated",created:"Template created",applied:"Template applied"}}},support:{debugLoggingActive:"Debug logging is active",manageLogs:"Manage",collectItem7:"Printer connectivity and firmware versions",collectItem8:"Integration status (Spoolman, MQTT, HA)",collectItem9:"Network interfaces (subnets only)",collectItem10:"Python package versions",collectItem11:"Database health checks",collectItem12:"Docker environment details"},fileManager:{title:"File Manager",subtitle:"Organize and manage your print files",uploadFiles:"Upload Files",newFolder:"New Folder",folderName:"Folder Name",folderNamePlaceholder:"e.g., Functional Parts",renameFile:"Rename File",renameFolder:"Rename Folder",moveFiles:"Move {{count}} File(s)",rootNoFolder:"Root (No Folder)",current:"current",linkFolder:"Link Folder",linkFolderDescription:'Link "{{name}}" to a project or archive for quick access.',project:"Project",archive:"Archive",noProjectsFound:"No projects found",noArchivesFound:"No archives found",unlink:"Unlink",link:"Link",dragDropFiles:"Drag & drop files here",dropFilesHere:"Drop files here",orClickToBrowse:"or click to browse",allFileTypesSupported:"All file types supported. ZIP files will be extracted.",zipFilesDetected:"ZIP files detected",zipExtractOptions:"ZIP files will be extracted. Choose how to handle folder structure:",preserveZipStructure:"Preserve folder structure from ZIP",createFolderFromZip:"Create folder from ZIP filename",stlThumbnailGeneration:"STL thumbnail generation",zipMayContainStl:"ZIP files may contain STL files. Thumbnails can be generated during extraction.",thumbnailsCanBeGenerated:"Thumbnails can be generated for STL files. Large models may take longer to process.",generateThumbnailsForStl:"Generate thumbnails for STL files",threemfDetected:"3MF files detected",threemfExtractionInfo:"Printer model, material, color, and print settings will be automatically extracted from 3MF files.",willBeExtracted:"Will be extracted",filesExtracted:"{{count}} files extracted",uploadComplete:"Upload complete: {{succeeded}} succeeded",uploadFailed:"Upload failed",zipFilesFailed:"{{count}} files failed",uploading:"Uploading...",changeLink:"Change Link...",linkTo:"Link to...",linkToProjectOrArchive:"Link to project or archive",addToQueue:"Add to Queue",schedulePrint:"Schedule",generateThumbnail:"Generate Thumbnail",generateThumbnails:"Generate Thumbnails",generateThumbnailsForMissing:"Generate thumbnails for STL files missing them",gridView:"Grid view",listView:"List view",lowDiskSpaceWarning:"Low disk space warning",lowDiskSpaceDetails:"Only {{free}} free of {{total}} total. Threshold is set to {{threshold}} GB in settings.",files:"Files",folders:"Folders",size:"Size",free:"Free",allFiles:"All Files",wrap:"Wrap",enableTextWrapping:"Enable text wrapping",disableTextWrapping:"Disable text wrapping",dragToResizeTooltip:"Drag to resize, double-click to reset",searchFiles:"Search files...",allTypes:"All types",prints:"Prints",ascending:"Ascending",descending:"Descending",resultsCount:"{{showing}} of {{total}} files",selectAll:"Select All",deselectAll:"Deselect All",selected:"{{count}} selected",adding:"Adding...",loadingFiles:"Loading files...",folderIsEmpty:"Folder is empty",noFilesYet:"No files yet",folderEmptyDescription:"Upload files or move files into this folder to get started.",noFilesDescription:"Upload files to start organizing your print-related files.",noMatchingFiles:"No matching files",noMatchingFilesDescription:"No files match your current search or filter criteria.",clearFilters:"Clear filters",printedCount:"Printed {{count}}x",uploadedBy:"Uploaded By",deleteFolder:"Delete Folder",deleteFile:"Delete File",deleteFilesCount:"Delete {{count}} Files",deleteFolderConfirm:"Are you sure you want to delete this folder? All files inside will also be deleted.",deleteFileConfirm:"Are you sure you want to delete this file?",deleteFilesConfirm:"Are you sure you want to delete {{count}} selected files? This action cannot be undone.",deleting:"Deleting...",noPermissionRenameFolder:"You do not have permission to rename folders",noPermissionLinkFolder:"You do not have permission to link folders",noPermissionDeleteFolder:"You do not have permission to delete folders",noPermissionPrint:"You do not have permission to print",noPermissionAddToQueue:"You do not have permission to add to queue",noPermissionDownload:"You do not have permission to download files",noPermissionRenameFile:"You do not have permission to rename this file",noPermissionGenerateThumbnail:"You do not have permission to generate thumbnails",noPermissionDeleteFile:"You do not have permission to delete this file",noPermissionCreateFolder:"You do not have permission to create folders",noPermissionUpload:"You do not have permission to upload files",noPermissionMoveFiles:"You do not have permission to move files",noPermissionDeleteFiles:"You do not have permission to delete files",linkExternal:"Link External",linkExternalFolder:"Link External Folder",linkExternalFolderDescription:"Mount a host directory (NAS, USB, network share) into the File Manager. Files are not copied — they are accessed directly from the original path.",externalFolderNamePlaceholder:"e.g., NAS Prints",externalPath:"Host Path",externalPathHelp:"Absolute path to the directory on the Docker host. Must be bind-mounted into the container.",readOnly:"Read Only",readOnlyHelp:"prevents uploads and deletions",showHiddenFiles:"Show hidden files (dotfiles)",externalFolder:"External Folder",scanFolder:"Scan",toast:{folderCreated:"Folder created",folderDeleted:"Folder deleted",fileDeleted:"File deleted",filesDeleted:"Deleted {{count}} files",filesMoved:"Files moved",folderLinked:"Folder linked",folderUnlinked:"Folder unlinked",externalFolderLinked:"External folder linked and scanned",folderScanned:"Scan complete: {{added}} added, {{removed}} removed",addedToQueue:"Added {{count}} file(s) to queue",addedToQueuePartial:"Added {{added}} file(s), {{failed}} failed",failedToAddToQueue:"Failed to add files: {{error}}",fileRenamed:"File renamed",folderRenamed:"Folder renamed",thumbnailsGenerated:"Generated {{count}} thumbnail(s)",thumbnailsGeneratedPartial:"Generated {{succeeded}} thumbnail(s), {{failed}} failed",noStlMissingThumbnails:"No STL files missing thumbnails",failedToGenerateThumbnails:"Failed to generate thumbnails: {{error}}",thumbnailGenerated:"Thumbnail generated",failedToGenerateThumbnail:"Failed to generate thumbnail: {{error}}"}},projects:{title:"Projects",subtitle:"Organize and track your 3D printing projects",newProject:"New Project",editProject:"Edit Project",deleteProject:"Delete Project",projectName:"Project Name",description:"Description",noProjects:"No projects yet",noProjectsFiltered:"No {{status}} projects",noProjectsFilteredHelp:"You don't have any {{status}} projects. Projects will appear here when their status changes.",createFirst:"Create your first project to start organizing related prints, tracking progress, and managing your builds.",createFirstButton:"Create Your First Project",create:"Create",files:"Files",prints:"Prints",plates:"plates",parts:"parts",lastModified:"Last Modified",deleteConfirm:"Are you sure you want to delete this project? Archives and queue items will be unlinked but not deleted.",addFiles:"Add Files",removeFile:"Remove File",viewDetails:"View Details",namePlaceholder:"e.g., Voron 2.4 Build",descriptionPlaceholder:"Optional description...",color:"Color",targetPlates:"Target Plates",targetPlatesPlaceholder:"e.g., 25",targetPlatesHelp:"Number of print jobs",targetParts:"Target Parts",targetPartsPlaceholder:"e.g., 150",targetPartsHelp:"Total objects needed",tagsLabel:"Tags (comma-separated)",tagsPlaceholder:"e.g., voron, functional, gift",dueDate:"Due Date",priority:"Priority",priorityLow:"Low",priorityNormal:"Normal",priorityHigh:"High",priorityUrgent:"Urgent",statusActive:"Active",statusCompleted:"Completed",statusArchived:"Archived",done:"Done",completed:"completed",failed:"failed",inQueue:"in queue",noPrintsYet:"No prints yet",printJobs:"Print jobs (plates)",partsPrinted:"Parts printed",failedParts:"Failed parts",import:"Import",export:"Export",importProject:"Import project",exportAll:"Export all projects",loading:"Loading projects...",noEditPermission:"You do not have permission to edit projects",noDeletePermission:"You do not have permission to delete projects",noCreatePermission:"You do not have permission to create projects",noImportPermission:"You do not have permission to import projects",noExportPermission:"You do not have permission to export projects",toast:{created:"Project created",updated:"Project updated",deleted:"Project deleted",imported:"Project imported",multipleImported:"{{count}} projects imported",importFailed:"Import failed",exported:"Projects exported (metadata only)"}},projectDetail:{notFound:"Project not found",backToProjects:"Back to Projects",export:"Export",exportProject:"Export project",noExportPermission:"You do not have permission to export projects",noEditPermission:"You do not have permission to edit projects",partOf:"Part of:",priorityLabel:"Priority:",noPrints:"No prints in this project yet",status:{active:"Active",completed:"Completed",archived:"Archived"},priority:{low:"Low",normal:"Normal",high:"High",urgent:"Urgent"},dueDate:{overdue:"Overdue",today:"Due today",daysLeft:"{{count}} days left"},progress:{platesProgress:"Plates Progress",partsProgress:"Parts Progress",printJobs:"print jobs",parts:"parts",percentComplete:"{{percent}}% complete",remaining:"{{count}} remaining"},stats:{printJobs:"Print Jobs",total:"total",failed:"{{count}} failed",partsPrinted:"{{count}} parts printed",printTime:"Print Time",filamentUsed:"Filament Used"},cost:{title:"Cost Tracking",filamentCost:"Filament Cost",energy:"Energy",totalCost:"Total Cost",total:"Total",includesBom:"incl. BOM",budget:"Budget",remaining:"Remaining"},subProjects:{title:"Sub-projects ({{count}})"},notes:{title:"Notes",noEditPermission:"You do not have permission to edit notes",placeholder:"Add notes about this project...",empty:"No notes yet. Click Edit to add notes."},files:{title:"Files",linkFolders:"Link folders from the File Manager",forQuickAccess:"to this project for quick access.",fileCount:"{{count}} file(s)",empty:"No folders linked. Go to File Manager and link a folder to this project."},bom:{title:"Bill of Materials",acquired:"{{completed}}/{{total}} acquired",showAll:"Show all",hideDone:"Hide done",addPart:"Add Part",noAddPermission:"You do not have permission to add parts",partNamePlaceholder:"Part name (e.g., M3x8 screws)",partName:"Part name",qty:"Qty",price:"Price ({{currency}})",sourcingUrlPlaceholder:"Sourcing URL (optional)",remarksPlaceholder:"Remarks (optional)",deletePart:"Delete Part",deleteConfirm:'Are you sure you want to delete "{{name}}"?',noUpdatePermission:"You do not have permission to update parts",noEditPermission:"You do not have permission to edit parts",noDeletePermission:"You do not have permission to delete parts",totalCost:"Total cost:",empty:"No parts in the bill of materials. Add hardware, electronics, or other components to track what needs to be sourced."},timeline:{title:"Activity Timeline",empty:"No activity yet."},template:{saveAsTemplate:"Save as Template",noCreatePermission:"You do not have permission to create templates"},queue:{title:"Queue",viewAll:"View all",printing:"{{count}} printing",queued:"{{count}} queued"},prints:{title:"Prints ({{count}})"},toast:{projectUpdated:"Project updated",partAdded:"Part added",partRemoved:"Part removed",exportFailed:"Export failed",projectExported:"Project exported",templateCreated:"Template created"}},system:{title:"System Information",version:"Version",uptime:"Uptime",cpuUsage:"CPU Usage",memoryUsage:"Memory Usage",diskUsage:"Disk Usage",networkInfo:"Network Info",logs:"Logs",debugMode:"Debug Mode",enableDebug:"Enable Debug Logging",disableDebug:"Disable Debug Logging",downloadLogs:"Download Logs",clearLogs:"Clear Logs",dockerInfo:"Docker Info",containerName:"Container Name",imageName:"Image Name",platform:"Platform",architecture:"Architecture"},library:{title:"Filament Library",addFilament:"Add Filament",editFilament:"Edit Filament",deleteFilament:"Delete Filament",vendor:"Vendor",material:"Material",color:"Color",kFactor:"K Factor",temperature:"Temperature",noFilaments:"No filaments in library",deleteConfirm:"Are you sure you want to delete this filament?",importFromPrinter:"Import from Printer",exportToFile:"Export to File"},spoolman:{title:"Spoolman Integration",enabled:"Spoolman Enabled",url:"Spoolman URL",connected:"Connected",disconnected:"Not Connected",testConnection:"Test Connection",sync:"Sync",syncing:"Syncing...",lastSync:"Last Sync",linkToSpoolman:"Link to Spoolman",openInSpoolman:"Open in Spoolman",unlinkSpool:"Unlink Spool",unlinkConfirmTitle:"Unlink Spool?",unlinkConfirmMessage:"This will disconnect the spool from Spoolman. The spool data in Spoolman will remain unchanged.",selectSpool:"Select Spool",noUnlinkedSpools:"No unlinked spools available",linkSuccess:"Spool linked to Spoolman successfully",linkFailed:"Failed to link spool",unlinkSuccess:"Spool unlinked from Spoolman successfully",unlinkFailed:"Failed to unlink spool",spoolId:"Spool ID",fillSourceLabel:"(Spoolman)",weight:"Weight",remaining:"Remaining",disableWeightSync:"Disable AMS Estimated Weight Sync",disableWeightSyncDesc:"Don't update remaining capacity from AMS estimates. Use this if you prefer Spoolman's usage tracking over AMS percentage-based estimates. New spools will still use the AMS estimate as their initial weight.",reportPartialUsage:"Report Partial Usage for Failed Prints",reportPartialUsageDesc:"When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress."},inventory:{title:"Spool Inventory",addSpool:"Add Spool",editSpool:"Edit Spool",material:"Material",selectMaterial:"Select material...",subtype:"Subtype",brand:"Brand",searchBrand:"Search brand...",useCustomBrand:'Use "{{brand}}"',useCustomMaterial:"Use custom material: {{material}}",colorName:"Color Name",colorNamePlaceholder:"Jade White, Fire Red...",color:"Color",hexColor:"Hex Color",pickColor:"Pick custom color",labelWeight:"Label Weight",coreWeight:"Empty Spool Weight",searchSpoolWeight:"Search spool weight...",weightUsed:"Used",currentWeight:"Remaining Weight",measuredWeight:"Measured Weight",spoolName:"Spool",costPerKg:"Cost per kg",measuredWeightError:"Measured weight must be between {{min}}g and {{max}}g.",slicerFilament:"Slicer Filament",slicerFilamentName:"Slicer Preset Name",slicerPreset:"Slicer Preset",searchPresets:"Search filament presets...",selectedPreset:"Selected",noPresetsFound:"No presets found",tempOverrides:"Temperature Overrides",note:"Note",notePlaceholder:"Any additional notes about this spool...",archive:"Archive",restore:"Restore",noSpools:"No spools yet. Add your first spool to get started.",noManualSpools:"No manually added spools available. Add a spool to your inventory first.",kProfiles:"K-Profiles",addKProfile:"Add K-Profile",assignSpool:"Assign Spool",unassignSpool:"Unassign",assignSuccess:"Spool assigned and AMS slot configured",assignFailed:"Failed to assign spool",selectSpool:"Select a spool to assign to this slot",assigned:"Assigned",assigning:"Assigning...",searchSpools:"Search spools...",showAllSpools:"Show all spools",allMaterials:"All Materials",filterByBrand:"Filter by brand...",showArchived:"Show archived",quickAdd:"Quick Add (Stock)",quantity:"Quantity",stock:"Stock",configured:"Configured",spoolsCreated:"{{count}} spools created",spoolCreated:"Spool created",spoolUpdated:"Spool updated",spoolDeleted:"Spool deleted",spoolArchived:"Spool archived",spoolRestored:"Spool restored",deleteConfirm:"Are you sure you want to delete this spool? This cannot be undone.",archiveConfirm:"Are you sure you want to archive this spool?",advancedSettings:"Advanced Settings",filamentInfoTab:"Filament Info",paProfileTab:"PA Profile",filamentInfo:"Filament",additional:"Additional",loadingPresets:"Loading cloud presets...",cloudConnected:"Cloud connected",cloudNotConnected:"Cloud not connected (using defaults)",recentColors:"Recent",searchColors:"Search colors...",searchResults:"Search results",allColors:"All colors",commonColors:"Common colors",showLess:"Show less",showAll:"Show all",noColorsFound:"No colors match your search",noResults:"No matches found",selectMaterialFirst:"Please select a material first in the Filament Info tab.",noPrintersConfigured:"No printers configured. Add printers to use PA profiles.",matchingFilter:"Matching",anyBrand:"Any brand",anyVariant:"Any variant",autoSelect:"Auto-select",matches:"matches",match:"match",noMatches:"No matches",connected:"Connected",offline:"Offline",printerOffline:"Printer is offline. Connect to view calibration profiles.",noKProfilesMatch:"No K-profiles match the selected filament.",leftNozzle:"Left Nozzle",rightNozzle:"Right Nozzle",profilesSelected:"calibration profile(s) selected",totalInventory:"Total Inventory",totalConsumed:"Total Consumed",byMaterial:"By Material",inPrinter:"In Printer",lowStock:"Low Stock",sinceTracking:"Since tracking started",loadedInAms:"Loaded in AMS/Ext",remaining:"Remaining",weightCheck:"Weight Check",lastWeighed:"Last weighed",neverWeighed:"Never weighed",search:"Search spools...",showing:"Showing",to:"to",of:"of",show:"Show",spools:"spools",spool:"spool",page:"Page",noSpoolsMatch:"No results found",noSpoolsMatchDesc:"Try adjusting your search or filters to find what you're looking for.",active:"Active",archived:"Archived",all:"All",used:"Used",new:"New",clearFilters:"Clear filters",table:"Table",cards:"Cards",net:"Net",groupSimilar:"Group",groupedSpools:"{{count}} identical spools",groupedRows:"rows",columns:"Columns",configureColumns:"Configure Columns",configureColumnsDesc:"Drag to reorder columns or use arrows. Toggle visibility with the eye icon.",visible:"visible",reset:"Reset",cancel:"Cancel",applyChanges:"Apply Changes",moveUp:"Move up",moveDown:"Move down",hideColumn:"Hide column",showColumn:"Show column",linkToSpool:"Link to Spool",tagLinked:"Tag linked to spool",tagLinkFailed:"Failed to link tag",tagAlreadyLinked:"Tag already linked to another spool",unknownTag:"Unknown RFID tag detected",usageHistory:"Usage History",noUsageHistory:"No usage recorded yet",printName:"Print Name",weightConsumed:"Weight Consumed",clearHistory:"Clear",historyCleared:"Usage history cleared",fillSourceLabel:"(Inv)",lowStockThresholdError:"Threshold must be between 0.1 and 99.9",assignMismatchTitle:"Material mismatch",assignMismatchMessage:'The selected spool material "{{spoolMaterial}}" does not match the tray material "{{trayMaterial}}" for {{location}}. Assign anyway?',assignMismatchConfirm:"Assign Anyway",assignPartialMismatchMessage:'The spool material "{{spoolMaterial}}" is similar to but not exactly matching "{{trayMaterial}}" in {{location}}. Do you want to proceed?',assignProfileMismatchMessage:'The spool profile "{{spoolProfile}}" does not match the tray profile "{{trayProfile}}" in {{location}}. Do you want to proceed?'},timelapse:{title:"Timelapse",create:"Create Timelapse",download:"Download",delete:"Delete",preview:"Preview",frameRate:"Frame Rate",quality:"Quality",processing:"Processing...",noTimelapses:"No timelapses available"},ams:{title:"AMS",slot:"Slot",empty:"Empty",emptySlot:"Empty slot",unknown:"Unknown",humidity:"Humidity",temperature:"Temperature",filamentType:"Filament Type",filamentColor:"Color",remaining:"Remaining",history:"AMS History",noHistory:"No history available",configureSlot:"Configure Slot",externalSpool:"External Spool",profile:"Profile",kFactor:"K Factor",fill:"Fill",configure:"Configure",used:"used",remainingUnit:"remaining"},printModal:{title:"Start Print",selectPrinter:"Select Printer",selectPlate:"Select Plate",filamentMapping:"Filament Mapping",totalCost:"Total cost:",slotRemainingShort:" - {{grams}}g left",printSettings:"Print Settings",bedLeveling:"Bed Leveling",flowCalibration:"Flow Calibration",vibrationCalibration:"Vibration Calibration",layerInspection:"First Layer Inspection",timelapse:"Timelapse",startPrint:"Start Print",addToQueue:"Add to Queue",cancel:"Cancel",noPrintersAvailable:"No printers available",printerBusy:"Printer is busy",printerOffline:"Printer is offline",sameTypeDifferentColor:"Same type, different color",filamentTypeNotLoaded:"Filament type not loaded",openCalendar:"Open calendar",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Left nozzle",rightNozzleTooltip:"Right nozzle",filamentOverride:"Filament Override",filamentOverrideHint:"Optionally override filaments for model-based assignment. The scheduler will match against your selected filaments instead of the original 3MF values.",originalFilament:"Original",overrideWith:"Override with",resetToOriginal:"Reset to original",insufficientFilamentTitle:"Not enough filament",insufficientFilamentMessage:"Some assigned spools have less filament remaining than this print needs:",insufficientFilamentLine:"{{printer}} - {{slot}}: needs {{required}}g, remaining {{remaining}}g",printAnyway:"Print anyway",forceColorMatch:"Force color match",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Stagger to {{count}} printers",gcodeInjection:"Inject auto-print G-code"},backup:{title:"Backup & Restore",createBackup:"Create Backup",restoreBackup:"Restore Backup",restoreDescription:"Replace all data from a backup file",downloadBackup:"Download Backup",uploadBackup:"Upload Backup",lastBackup:"Last Backup",autoBackup:"Auto Backup",backupNow:"Backup Now",restoreWarning:"Warning: Restoring a backup will overwrite all current data.",includeArchives:"Include Archives",includeSettings:"Include Settings",includeProfiles:"Include Profiles",backupSuccess:"Backup created successfully",restoreSuccess:"Backup restored successfully",backupFailed:"Backup failed",restoreFailed:"Restore failed",restoreNote:"Virtual Printer will be stopped during restore",githubBackup:"GitHub Backup",enabled:"Enabled",cloudLoginRequired:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup.",cloudLoginRequiredShort:"Cloud login required",githubDescription:"Automatically sync your profiles to a private GitHub repository for backup and version history.",repositoryUrl:"Repository URL",personalAccessToken:"Personal Access Token",tokenSaved:"(saved)",enterNewToken:"Enter new token to update",tokenHint:"Fine-grained token with Contents read/write permission",branch:"Branch",manualOnly:"Manual only",hourly:"Hourly",daily:"Daily",weekly:"Weekly",includeInBackup:"Include in backup",kProfiles:"K-Profiles",kProfilesDescription:"Pressure advance calibration from connected printers",noPrintersConnected:"No printers connected",printersConnected:"{{connected}}/{{total}} connected",cloudProfiles:"Cloud Profiles",cloudProfilesDescription:"Filament, printer, and process presets from Bambu Cloud",appSettings:"App Settings",appSettingsDescription:"Bambuddy configuration (complete database)",spoolInventory:"Spool Inventory",spoolInventoryDescription:"Filament spools, usage history, and cost tracking",printArchives:"Print Archives",printArchivesDescription:"Print history metadata (no gcode/3MF files)",lastBackupAt:"Last backup:",noBackupsYet:"No backups yet",next:"Next:",startingBackup:"Starting backup...",test:"Test",enableBackup:"Enable Backup",testConnection:"Test Connection",enterRepoUrl:"Enter repository URL",enterRepoAndToken:"Enter repository URL and access token",repoRequired:"Repository URL is required",tokenRequired:"Access token is required",githubBackupEnabled:"GitHub backup enabled",tokenUpdated:"Token updated",settingsSaved:"Settings saved",failedToSave:"Failed to save: {{message}}",backupCompleteFiles:"Backup complete - {{count}} files updated",backupSkippedNoChanges:"Backup skipped - no changes",backupFailed2:"Backup failed: {{message}}",clearedLogs:"Cleared {{count}} logs",failedToClearLogs:"Failed to clear logs: {{message}}",history:"History",clear:"Clear",date:"Date",status:"Status",commit:"Commit",localBackup:"Local Backup",localBackupDescription:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files.",downloadBackupLabel:"Download Backup",completeBackupZip:"Complete backup: database + all files (ZIP)",download:"Download",preparingBackup:"Preparing backup...",creatingArchive:"Creating backup archive... This may take a while for large archives.",downloadingFile:"Downloading backup file...",backupDownloaded:"Backup downloaded successfully",failedToCreateBackup:"Failed to create backup: {{message}}",restore:"Restore",restoreReplacesAll:"Restore replaces all data.",restoreReplacesAllDetail:"Your current database and files will be completely replaced. A restart is required after restore.",restoreConfirmTitle:"Restore Backup",restoreConfirmMessage:'Are you sure you want to restore from "{{filename}}"? This will completely replace your current database and all files. The application will need to be restarted after restore.',restoreConfirmButton:"Restore Backup",uploadingFile:"Uploading backup file...",backupRestoredRestart:"Backup restored. Please restart Bambuddy.",failedToRestore:"Failed to restore backup. Please check the file format.",reloadNow:"Reload Now",creatingBackup:"Creating Backup",restoringBackup:"Restoring Backup",preparing:"Preparing...",processing:"Processing...",doNotClosePage:"Please do not close this page or navigate away. This operation may take several minutes for large backups.",restoring:"Restoring...",restoreComplete:"Restore Complete",restoreFailed2:"Restore Failed",importSettings:"Import settings from a backup file",pleaseWaitRestoring:"Please wait while your data is being restored",selectBackupFile:"Click to select backup file (.json or .zip)",duplicateHandling:"How duplicate handling works:",matchPrinters:"Printers",matchPrintersBy:"matched by serial number",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"matched by IP address",matchNotificationProviders:"Notification Providers",matchNotificationProvidersBy:"matched by name",matchFilaments:"Filaments",matchFilamentsBy:"matched by name + type + brand",matchArchives:"Archives",matchArchivesBy:"matched by content hash (always skipped)",matchPendingUploads:"Pending Uploads",matchPendingUploadsBy:"matched by filename",matchSettingsTemplates:"Settings & Templates",matchSettingsTemplatesBy:"always overwritten",replaceExisting:"Replace existing data",keepExisting:"Keep existing data",overwriteDescription:"Overwrite items that already exist with backup data",keepDescription:"Only restore items that don't already exist",overwriteCaution:"Caution:",overwriteWarning:"Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security.",cancel:"Cancel",processingBackup:"Processing backup file...",itemsRestored:"Items Restored",itemsSkipped:"Items Skipped",restored:"Restored",skippedAlreadyExist:"Skipped (already exist)",filesCategory:"Files (3MF, thumbnails, etc.)",andMore:"...and {{count}} more",newApiKeysGenerated:"New API Keys Generated",keysShownOnce:"These keys are only shown once. Copy them now!",copy:"Copy",noDataFound:"No data was found to restore in the backup file.",close:"Close",categories:{settings:"Settings",notification_providers:"Notification Providers",notification_templates:"Notification Templates",smart_plugs:"Smart Plugs",printers:"Printers",filaments:"Filaments",maintenance_types:"Maintenance Types",archives:"Archives",projects:"Projects",pending_uploads:"Pending Uploads",external_links:"External Links",api_keys:"API Keys"}},tags:{title:"Tags",addTag:"Add Tag",editTag:"Edit Tag",deleteTag:"Delete Tag",tagName:"Tag Name",tagColor:"Tag Color",noTags:"No tags",deleteConfirm:"Are you sure you want to delete this tag?",manageTags:"Manage Tags"},uploadModal:{title:"Upload 3MF Files",dragDrop:"Drag & drop .3mf files here",or:"or",browseFiles:"Browse Files",extractionInfo:"The printer model will be automatically extracted from the 3MF file metadata.",uploaded:"uploaded",failed:"failed",uploading:"Uploading...",upload:"Upload",uploadFailed:"Upload failed"},editArchive:{title:"Edit Archive",name:"Name",namePlaceholder:"Print name",printer:"Printer",noPrinter:"No printer",project:"Project",noProject:"No project",itemsPrinted:"Items Printed",itemsPrintedHelp:"Number of items produced in this print job",notes:"Notes",notesPlaceholder:"Add notes about this print...",externalLink:"External Link",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link to Printables, Thingiverse, or other source",tags:"Tags",tagsPlaceholder:"Add tags...",addMoreTags:"Add more tags...",matchingTags:'Matching "{{query}}"',existingTags:"Existing tags",clickToAdd:"(click to add)",status:"Status",failureReason:"Failure Reason",selectReason:"Select reason...",photos:"Photos of Printed Result",photosHelp:"Click + to add photos of your printed result",printResult:"Print result",saving:"Saving...",failureReasons:{adhesionFailure:"Adhesion failure",spaghettiDetached:"Spaghetti / Detached",layerShift:"Layer shift",cloggedNozzle:"Clogged nozzle",filamentRunout:"Filament runout",warping:"Warping",stringing:"Stringing",underExtrusion:"Under-extrusion",powerFailure:"Power failure",userCancelled:"User cancelled",other:"Other"},statuses:{completed:"Completed",failed:"Failed",aborted:"Cancelled",printing:"Printing"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"No Printers Configured",addPrinterInSettings:"Add a printer in Settings to manage K-profiles",noActivePrinters:"No Active Printers",enablePrinterConnection:"Enable a printer connection to view its K-profiles",loadingProfiles:"Loading K-Profiles...",printerOffline:"Printer Offline",printerOfflineDesc:"The selected printer is not connected. Power it on to view K-profiles.",noMatchingProfiles:"No Matching Profiles",noMatchingProfilesDesc:"No profiles match your search criteria",noKProfiles:"No K-Profiles",noKProfilesDesc:"No pressure advance profiles found for {{diameter}}mm nozzle",createFirstProfile:"Create First Profile",printer:"Printer",nozzle:"Nozzle",refresh:"Refresh",addProfile:"Add Profile",export:"Export",import:"Import",select:"Select",selectAll:"Select All",delete:"Delete",searchPlaceholder:"Search by name or filament...",allExtruders:"All Extruders",leftOnly:"Left Only",rightOnly:"Right Only",allFlow:"All Flow",hfOnly:"HF Only",sOnly:"S Only",sortName:"Sort: Name",sortKValue:"Sort: K-Value",sortFilament:"Sort: Filament",leftExtruder:"Left Extruder",rightExtruder:"Right Extruder",modal:{addTitle:"Add K-Profile",editTitle:"Edit K-Profile",profileName:"Profile Name",profileNamePlaceholder:"My PLA Profile",kValue:"K-Value",kValuePlaceholder:"0.020",kValueHelp:"Typical range: 0.01 - 0.06 for PLA, 0.02 - 0.10 for PETG",filament:"Filament",selectFilament:"Select filament...",noFilamentsHelp:"No filaments found. Create a K-profile in Bambu Studio first.",flowType:"Flow Type",highFlow:"High Flow",standard:"Standard",nozzleSize:"Nozzle Size",extruder:"Extruder",extruders:"Extruders",left:"Left",right:"Right",notes:"Notes (stored locally)",notesPlaceholder:"Add notes about this profile...",notesHelp:"Notes are saved in Bambuddy, not on the printer",syncing:"Syncing with printer...",savingExtruder:"Saving to extruder {{current}}/{{total}}...",pleaseWait:"Please wait"},deleteConfirm:{title:"Delete Profile",cannotUndo:"This cannot be undone",message:'Are you sure you want to delete "{{name}}" from the printer?'},bulkDelete:{title:"Delete Profiles",cannotUndo:"This cannot be undone",message:"Are you sure you want to delete {{count}} selected profiles from the printer?"},toast:{profileSaved:"K-profile saved",profilesSaved:"K-profile saved to {{count}} extruders",selectAtLeastOneExtruder:"Please select at least one extruder",profileDeleted:"K-profile deleted",profilesDeleted:"Deleted {{count}} profiles",exportedProfiles:"Exported {{count}} profiles",importedProfiles:"Imported {{count}} of {{total}} profiles",noProfilesToExport:"No profiles to export",invalidFileFormat:"Invalid file format",failedToParseImport:"Failed to parse import file",failedToSaveBatch:"Failed to save K-profiles",noteSaved:"Note saved",failedToSaveNote:"Failed to save note"},permission:{noRead:"You do not have permission to refresh profiles",noCreate:"You do not have permission to add profiles",noUpdate:"You do not have permission to update K-profiles",noDelete:"You do not have permission to delete K-profiles",noExport:"You do not have permission to export profiles",noImport:"You do not have permission to import profiles"}},virtualPrinter:{title:"Virtual Printer",running:"Running",stopped:"Stopped",description:{default:"Enable a virtual printer that appears in Bambu Studio and OrcaSlicer. Files sent to this printer will be archived directly without printing.",proxy:"Enable a proxy that relays slicer traffic to a real printer, allowing remote printing over any network."},enable:{title:"Enable Virtual Printer",visibleInSlicer:'Visible as "Bambuddy" in slicer discovery',proxyingTo:"Proxying to {{name}}",notActive:"Not active"},model:{title:"Printer Model",description:"Select which printer model to emulate.",restartWarning:"Changing the model will restart the virtual printer"},accessCode:{title:"Access Code",isSet:"Access code is set",notSet:"No access code set - required to enable",placeholder:"Enter 8-char code",placeholderChange:"Enter new code to change",hint:"Must be exactly 8 characters. Used by slicers to authenticate.",charCount:"({{count}}/8)"},targetPrinter:{title:"Target Printer",configured:"Proxy target configured",notConfigured:"No target printer selected - required for proxy mode",placeholder:"Select a printer...",hint:"Select the printer to proxy slicer traffic to. The printer must be in LAN mode.",noPrinters:"No printers configured. Add a printer first to use proxy mode."},remoteInterface:{title:"Network Interface Override",configured:"Interface override active",optional:"Optional - use if auto-detected IP is wrong (e.g. multiple NICs, Docker, VPN)",placeholder:"Auto-detect (default)...",hint:"Override the IP address advertised via SSDP and used in the TLS certificate. Useful when Bambuddy has multiple network interfaces."},mode:{title:"Mode",archive:"Archive",archiveDesc:"Archive files immediately",review:"Review",reviewDesc:"Review before archiving",queue:"Queue",queueDesc:"Archive and add to queue",proxy:"Proxy",proxyDesc:"Relay to real printer"},autoDispatch:{title:"Auto-dispatch",description:"Automatically start prints when added to queue. When off, prints wait for manual dispatch."},setupRequired:{title:"Setup Required",description:"The virtual printer feature requires additional system configuration before it will work. This includes port forwarding, firewall rules, and platform-specific settings.",readGuide:"Read the setup guide before enabling"},howItWorks:{title:"How it works",step1:"On the same LAN, virtual printers appear in your slicer (Bambu Studio / OrcaSlicer) automatically via discovery. From other networks, add them manually by IP address and access code.",step2:'In Archive, Review, and Queue modes, use the "Send" button in your slicer to upload 3MF files to Bambuddy. The slicer will show "Print success" — the file is stored, not printed.',step3:"In Proxy mode, the virtual printer relays all traffic to a real printer — prints start immediately as if connected directly."},status:{title:"Status Details",printerName:"Printer Name",model:"Model",serialNumber:"Serial Number",mode:"Mode",pendingFiles:"Pending Files",targetPrinter:"Target Printer",ftpPort:"FTP Port",mqttPort:"MQTT Port",ftpConnections:"FTP Connections",mqttConnections:"MQTT Connections"},toast:{updated:"Virtual printer settings updated",failedToUpdate:"Failed to update settings",accessCodeRequired:"Please set an access code first",targetPrinterRequired:"Please select a target printer first",bindIpRequired:"Please set a bind IP first",accessCodeEmpty:"Access code cannot be empty",accessCodeLength:"Access code must be exactly 8 characters",created:"Virtual printer created",failedToCreate:"Failed to create virtual printer",deleted:"Virtual printer deleted",failedToDelete:"Failed to delete virtual printer"},list:{title:"Virtual Printers",add:"Add",addFirst:"Add Virtual Printer",empty:"No virtual printers configured. Add one to get started."},bindIp:{title:"Bind Interface",placeholder:"Select interface...",hint:"Network interface for this virtual printer to bind to. Must be unique per printer."},proxy:{accessCodeHint:"In proxy mode, use your target printer's access code in the slicer. The connection is forwarded transparently to the real printer."},addDialog:{title:"Add Virtual Printer",name:"Name",hint:"You can configure access code, target printer, and other settings after creating.",create:"Create"},deleteConfirm:{title:"Delete Virtual Printer",message:'Are you sure you want to delete "{{name}}"? This will stop all services for this printer.'}},modelViewer:{openInSlicer:"Open in Slicer",tabs:{model:"3D Model",gcode:"G-code Preview"},notAvailable:"not available",notSliced:"not sliced",plates:"Plates",allPlates:"All Plates",plateNumber:"Plate {{number}}",plateCount:"{{count}} plate",plateCount_other:"{{count}} plates",objectCount:"{{count}} object",objectCount_other:"{{count}} objects",filamentCount:"{{count}} filament",filamentCount_other:"{{count}} filaments",eta:"ETA {{minutes}} min",noPreview:"No preview available for this file",pagination:{pageOf:"Page {{current}} of {{total}}",prev:"Prev",next:"Next"},errors:{failedToLoad:"Failed to load file",noMeshes:"No meshes found in 3MF file",unsupportedFormat:"Unsupported file format"}},maintenanceDescriptions:{lubricateCarbonRods:"Apply lubricant to carbon rods for smooth motion",lubricateRails:"Apply lubricant to linear rails for smooth motion",cleanNozzle:"Clean hotend and nozzle to prevent clogs",checkBelts:"Verify belt tension for accurate prints",cleanBuildPlate:"Clean build plate for better adhesion",checkExtruder:"Inspect extruder gears for wear",checkCooling:"Ensure cooling fans are working properly",generalInspection:"General printer inspection",cleanCarbonRods:"Clean carbon rods to reduce friction",lubricateSteelRods:"Apply lubricant to steel rods for smooth motion",cleanSteelRods:"Clean steel rods to reduce friction",cleanLinearRails:"Wipe linear rails to remove dust and debris",checkPtfeTube:"Inspect PTFE tube for wear or damage",replaceHepaFilter:"Replace HEPA filter for air quality",replaceCarbonFilter:"Replace activated carbon filter",lubricateLeftNozzleRail:"Lubricate left nozzle rail (H2 series)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Open plug admin page",deleteSmartPlug:"Delete Smart Plug",turnOnSmartPlug:"Turn On Smart Plug",turnOffSmartPlug:"Turn Off Smart Plug",turnOn:"Turn On",turnOff:"Turn Off",addSmartPlug:{scanningNetwork:"Scanning network...",chooseEntity:"Choose an entity...",connectionFailed:"Connection failed",searchEntities:"Search entities...",searchPowerSensors:"Search power sensors...",searchEnergySensors:"Search energy sensors...",placeholders:{plugName:"Living Room Plug",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Same as power topic, or different"}},linkedTo:"Linked to:",monitorOnly:"Monitor Only",alerts:"Alerts",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Power",kwhToday:"kWh Today",settings:"Settings",automationSettings:"Automation Settings",showInSwitchbar:"Show in Switchbar",quickAccessSidebar:"Quick access from sidebar",enabled:"Enabled",enableAutomation:"Enable automation for this plug",autoOn:"Auto On",autoOnDescription:"Turn on when print starts",autoOff:"Auto Off",autoOffDescription:"Turn off when print completes (one-shot)",autoOffPersistent:"Keep Enabled",autoOffPersistentDescription:"Stay enabled between prints instead of one-shot",turnOffDelayMode:"Turn Off Delay Mode",time:"Time",temp:"Temp",delayMinutes:"Delay (minutes)",tempThreshold:"Temperature threshold (°C)",tempThresholdDescription:"Turns off when nozzle cools below this temperature",edit:"Edit",deleteConfirm:'Are you sure you want to delete "{{name}}"? This cannot be undone.',turnOnConfirm:'Are you sure you want to turn on "{{name}}"?',turnOffConfirm:'Are you sure you want to turn off "{{name}}"? This will cut power to the connected device.',failedToTurn:'Failed to turn {{action}} "{{name}}"',unknown:"Unknown",addTitle:"Add Smart Plug",editTitle:"Edit Smart Plug",stopScanning:"Stop Scanning",discoverTasmota:"Discover Tasmota Devices",foundDevices:"Found {{count}} device(s) - click to select:",noDevicesFound:"No Tasmota devices found on your network",haNotConfigured:"Home Assistant is not configured. Set it up in",haSettingsPath:"Settings → Network → Home Assistant",selectEntity:"Select Entity *",ipAddress:"IP Address *",nameLabel:"Name *",username:"Username",password:"Password",authHint:"Leave empty if your Tasmota device doesn't require authentication",linkToPrinter:"Link to Printer",noPrinter:"No printer (manual control only)",linkingDescription:"Linking enables automatic on/off when prints start/complete",powerAlerts:"Power Alerts",alertAbove:"Alert if above (W)",alertBelow:"Alert if below (W)",alertDescription:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction.",dailySchedule:"Daily Schedule",turnOnAt:"Turn On at",turnOffAt:"Turn Off at",scheduleDescription:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action.",showOnPrinterCard:"Show on Printer Card",displayOnPrinterCard:"Display button on printer card",connectedResult:"Connected!",deviceLabel:"Device: {{name}} - ",stateLabel:"State: {{state}}",test:"Test",delete:"Delete",save:"Save",add:"Add",cancel:"Cancel",failedToStartScan:"Failed to start scan",nameRequired:"Name is required",entityRequired:"Entity is required for Home Assistant plugs",mqttTopicRequired:"At least one MQTT topic must be configured for power, energy, or state monitoring",loadingEntities:"Loading entities...",loading:"Loading...",failedToLoadEntities:"Failed to load entities: {{error}}",noEntitiesMatching:'No entities found matching "{{search}}"',noEntitiesAvailable:"No entities available",searchingEntities:"Searching all entities ({{count}} found)",showingEntities:"Showing switch, light, input_boolean ({{count}} available)",energyMonitoringOptional:"Energy Monitoring (Optional)",energyMonitoringHint:"Search and select sensors that provide power/energy data.",powerSensorW:"Power Sensor (W)",energyTodayKwh:"Energy Today (kWh)",totalEnergyKwh:"Total Energy (kWh)",noMatchingSensors:"No matching sensors",none:"None",mqttNotConfigured:"MQTT broker not configured. Set broker address in",mqttSettingsPath:"Settings → Network → MQTT Publishing",mqttNotConfiguredSuffix:"(you don't need to enable publishing, just fill in the broker details).",mqttMonitorOnlyDescription:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system.",powerMonitoring:"Power Monitoring",energyMonitoring:"Energy Monitoring",stateMonitoring:"State Monitoring",optional:"optional",topic:"Topic",jsonPath:"JSON Path",multiplier:"Multiplier",onValue:"ON Value",mqttPowerHint:`JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.
  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",jobAdded:"Job Added",jobAddedDescription:"Job added to queue",jobAssigned:"Job Assigned",jobAssignedDescription:"Model-based job assigned to printer",jobStarted:"Job Started",jobStartedDescription:"Queue job started printing",jobWaiting:"Job Waiting",jobWaitingDescription:"Job waiting for filament or printer",jobSkipped:"Job Skipped",jobSkippedDescription:"Job skipped (previous failed)",jobFailed:"Job Failed",jobFailedDescription:"Job failed to start",queueComplete:"Queue Complete",queueCompleteDescription:"All queue jobs finished",quietHours:"Quiet Hours",noNotificationsDuring:"No notifications during these hours",editProviderToChangeQuietHours:"Edit provider to change quiet hours",dailyDigest:"Daily Digest",batchNotifications:"Batch notifications into a single daily summary",sendAt:"Send at {{time}}",editProviderToChangeDigestTime:"Edit provider to change digest time",edit:"Edit",deleteProvider:"Delete Notification Provider",deleteConfirm:'Are you sure you want to delete "{{name}}"? This cannot be undone.',delete:"Delete",addTitle:"Add Notification Provider",editTitle:"Edit Notification Provider",nameLabel:"Name *",namePlaceholder:"My Notifications",providerTypeLabel:"Provider Type *",configuration:"Configuration",testConfiguration:"Test Configuration",printerFilter:"Printer Filter",onlyFromPrinter:"Only send notifications for events from this printer",quietHoursDnd:"Quiet Hours (Do Not Disturb)",quietStart:"Start",quietEnd:"End",dailyDigestLabel:"Daily Digest",sendDigestAt:"Send digest at",digestCollected:"Events will be collected and sent as a single summary at this time",notificationEvents:"Notification Events",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(after print completes)",cancel:"Cancel",save:"Save",add:"Add",nameRequired:"Name is required",fieldRequired:"{{field}} is required",phoneNumber:"Phone Number",apiKey:"API Key",serverUrl:"Server URL",topic:"Topic",authToken:"Auth Token",userKey:"User Key",appToken:"App Token",priority:"Priority",botToken:"Bot Token",chatId:"Chat ID",smtpServer:"SMTP Server",smtpPort:"SMTP Port",security:"Security",authentication:"Authentication",username:"Username",password:"Password",fromEmail:"From Email",toEmail:"To Email",webhookUrl:"Webhook URL",payloadFormat:"Payload Format",authorization:"Authorization",titleFieldName:"Title Field Name",messageFieldName:"Message Field Name",editTemplate:"Edit Template: {{name}}",titleLabel:"Title",bodyLabel:"Body",titlePlaceholder:"Notification title...",bodyPlaceholder:"Notification body...",availableVariables:"Available Variables",clickToInsert:"Click to insert at cursor position in body",livePreview:"Live Preview",hide:"Hide",show:"Show",loadingPreview:"Loading preview...",enterTemplateContent:"Enter template content to see preview",titlePreview:"Title:",bodyPreview:"Body:",resetToDefault:"Reset to Default",titleRequired:"Title is required",bodyRequired:"Body is required",notificationLog:"Notification Log",showFailedOnly:"Failed only",last24Hours:"Last 24 hours",last7Days:"Last 7 days",last30Days:"Last 30 days",last90Days:"Last 90 days",justNow:"Just now",noFailedNotifications:"No failed notifications",noNotificationsLogged:"No notifications logged",unknownProvider:"Unknown Provider",logTitle:"Title",logMessage:"Message",logError:"Error",logProvider:"Provider: {{type}}",logTime:"Time: {{time}}",refresh:"Refresh",clearOld:"Clear Old",statsSummary:"Last {{days}} days:",statsNotifications:"notifications",statsSent:"{{count}} sent",statsFailed:"{{count}} failed",eventTypes:{print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},userEmail:{title:"Notifications",emailNotifications:"Email Notifications",emailNotificationsDesc:"Receive email notifications for your own print jobs. Emails are sent using the system SMTP settings configured in Advanced Authentication.",sendingTo:"Notifications will be sent to",noEmailWarning:"Your account does not have an email address. Contact an administrator to add one.",printJobNotifications:"Print Job Notifications",printJobNotificationsDesc:"Choose which events trigger email notifications for print jobs you submit.",printJobStarts:"Print Job Starts",printJobStartsDesc:"Get notified when your print job begins.",printJobFinishes:"Print Job Finishes",printJobFinishesDesc:"Get notified when your print job completes successfully.",printErrors:"Print Errors",printErrorsDesc:"Get notified when your print job fails or encounters an error.",printJobStops:"Print Job Stops",printJobStopsDesc:"Get notified when your print job is cancelled or stopped.",saveSuccess:"Notification preferences saved.",saveError:"Failed to save notification preferences."}},richTextEditor:{bold:"Bold",italic:"Italic",underline:"Underline",bulletList:"Bullet List",numberedList:"Numbered List",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",addLink:"Add Link",removeLink:"Remove Link"},externalLinks:{noLinksConfigured:"No external links configured",deleteLink:"Delete Link",removeCustomIcon:"Remove custom icon",openInNewTab:"Open in new tab",placeholders:{linkName:"My Link"}},keyboardShortcuts:{title:"Keyboard Shortcuts",navigation:"Navigation",archivesSection:"Archives",kProfilesSection:"K-Profiles",generalSection:"General",shortcuts:{goToPrinters:"Go to Printers",goToArchives:"Go to Archives",goToQueue:"Go to Queue",goToStats:"Go to Statistics",goToProfiles:"Go to Cloud Profiles",goToSettings:"Go to Settings",focusSearch:"Focus search",openUploadModal:"Open upload modal",clearSelection:"Clear selection / blur input",contextMenu:"Context menu on cards",refreshProfiles:"Refresh profiles",newProfile:"New profile",exitSelectionMode:"Exit selection mode",showHelp:"Show this help"},footer:"Press Esc or click outside to close"},notificationLog:{title:"Notification Log",events:{printStarted:"Print Started",printComplete:"Print Complete",printFailed:"Print Failed",printStopped:"Print Stopped",progress:"Progress",printerOffline:"Printer Offline",printerError:"Printer Error",lowFilament:"Low Filament",maintenanceDue:"Maintenance Due",test:"Test"},timeAgo:{justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago"}},restoreBackup:{title:"Restore Backup",restoring:"Restoring...",restoreComplete:"Restore Complete",restoreFailed:"Restore Failed",importSettings:"Import settings from a backup file",pleaseWait:"Please wait while your data is being restored",clickToSelect:"Click to select backup file (.json or .zip)",howDuplicateHandling:"How duplicate handling works:",categories:{printers:"Printers",smartPlugs:"Smart Plugs",notificationProviders:"Notification Providers",filaments:"Filaments",archives:"Archives",pendingUploads:"Pending Uploads",settingsTemplates:"Settings & Templates"},matchingInfo:{printers:"matched by serial number",smartPlugs:"matched by IP address",notificationProviders:"matched by name",filaments:"matched by name + type + brand",archives:"matched by content hash",pendingUploads:"matched by filename",settingsTemplates:"always overwritten"},replaceExisting:"Replace existing data",keepExisting:"Keep existing data",replaceDescription:"Overwrite items that already exist with backup data",keepDescription:"Only restore items that don't already exist",caution:"Caution:",cautionText:"Overwriting will replace your current configurations with backup data. Printer access codes are never overwritten for security.",itemsRestored:"Items Restored",itemsSkipped:"Items Skipped",restored:"Restored",skipped:"Skipped (already exist)",filesLabel:"Files (3MF, thumbnails, etc.)",newApiKeysGenerated:"New API Keys Generated",newApiKeysWarning:"These keys are only shown once. Copy them now!",processingBackup:"Processing backup file...",noDataFound:"No data was found to restore in the backup file.",failedToRestore:"Failed to restore backup. Please check the file format."},backupExport:{title:"Export Backup",selectData:"Select data to include",selectAll:"Select All",selectNone:"Select None",categoryDescriptions:{settings:"Language, theme, update preferences",notifications:"ntfy, Pushover, Discord, etc.",templates:"Custom message templates",smartPlugs:"Tasmota plug configurations",externalLinks:"Sidebar links to external services",printers:"Printer info (access codes excluded)",plateDetection:"Empty plate reference images",filaments:"Filament types and costs",maintenance:"Custom maintenance schedules",archives:"All print data + files (3MF, thumbnails, photos)",projects:"Projects, BOM items, and attachments",pendingUploads:"Virtual printer uploads awaiting review",apiKeys:"Webhook API keys (new keys generated on import)"},requiresPrinters:"Requires Printers to be selected",zipFileWarning:"ZIP file will be created.",zipFileDescription:"Includes all 3MF files, thumbnails, timelapses, and photos. This may take a while and result in a large file.",includeAccessCodes:"Include Access Codes",includeAccessCodesDescription:"For transferring to another machine",includeAccessCodesWarning:"Access codes will be included in plain text. Keep this backup file secure!",categoriesSelected:"{{selectedCount}} categories selected"},pendingUploads:{placeholders:{notes:"Add notes about this print..."},discardUpload:"Discard Upload",archiveAllUploads:"Archive All Uploads",discardAllUploads:"Discard All Uploads",archive:"Archive",timeAgo:{justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago",daysAgo:"{{days}}d ago"}},apiBrowser:{placeholders:{requestBody:"JSON request body...",searchEndpoints:"Search endpoints..."}},configureAmsSlot:{title:"Configure AMS Slot",slotConfigured:"Slot Configured!",configuringSlot:"Configuring slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Search presets...",colorPlaceholder:"Color name or hex (e.g., brown, FF8800)",clearCustomColor:"Clear custom color",noCloudPresets:"No cloud presets. Login to Bambu Cloud to sync.",noPresetsAvailable:"No presets available. Login to Bambu Cloud or import local profiles.",noMatchingPresets:"No matching presets found.",custom:"Custom",builtin:"Built-in",settingsSentToPrinter:"Settings sent to printer",filamentProfile:"Filament Profile",kProfileLabel:"K Profile (Pressure Advance)",filteringFor:"Filtering for: {{material}}",noKProfile:"No K profile (use default 0.020)",noMatchingKProfiles:"No matching K profiles found. Default K=0.020 will be used.",selectFilamentFirst:"Select a filament profile first",kFromCalibration:"K={{value}} from printer calibration",customColorLabel:"Custom Color (optional)",presetColors:"{{name}} colors:",showLessColors:"Show less colors",showMoreColors:"Show more colors",clear:"Clear",hexLabel:"Hex: #{{hex}}",resetting:"Resetting...",resetSlot:"Reset Slot",cancel:"Cancel",configuring:"Configuring...",configureSlot:"Configure Slot"},githubBackup:{title:"GitHub Backup",history:"History",downloadBackup:"Download Backup",restoreBackup:"Restore Backup",noBackupsYet:"No backups yet"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Search tags...",renameTag:"Rename tag",deleteTag:"Delete tag"},notificationTemplates:{placeholders:{title:"Notification title...",body:"Notification body..."}},batchTag:{placeholders:{newTag:"Enter new tag..."}},photoGallery:{deletePhoto:"Delete Photo"},filamentHoverCard:{copySpoolUuid:"Copy spool UUID"},kProfilesView:{hasNote:"Has note",copyProfile:"Copy profile"},layout:{openMenu:"Open menu",noPermissionSystemInfo:"You do not have permission to view system information"},dashboard:{dragToReorder:"Drag to reorder",hideWidget:"Hide widget"},notificationProviderCard:{deleteNotificationProvider:"Delete Notification Provider"},fileManagerModal:{closeFileManager:"Close file manager",sortFiles:"Sort files",goToParentFolder:"Go to parent folder",threeView:"3D View"},embeddedCameraViewer:{refreshStream:"Refresh stream",close:"Close",zoomOut:"Zoom out",resetZoom:"Reset zoom",zoomIn:"Zoom in",dragToResize:"Drag to resize"},timelapseViewer:{skipBack5s:"Skip back 5s",skipForward5s:"Skip forward 5s"},notificationProviders:{descriptions:{email:"SMTP email notifications",telegram:"Notifications via Telegram bot",discord:"Send to Discord channel via webhook",ntfy:"Free, self-hostable push notifications",pushover:"Simple, reliable push notifications",callmebot:"Free WhatsApp notifications via CallMeBot",webhook:"Generic HTTP POST to any URL"}},logViewer:{searchPlaceholder:"Search message or logger name...",noLogEntries:"No log entries found"},switchbarPopover:{noSwitchesInSwitchbar:"No switches in switchbar"},projectPageModal:{placeholders:{title:"Title",designer:"Designer",license:"License",description:"Enter description...",profileTitle:"Profile Title",profileDescription:"Profile description..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"Waiting",justNow:"Just now",now:"Now",minsAgo:"{{count}}m ago",inMins:"in {{count}}m",hoursAgo:"{{count}}h ago",inHours:"in {{count}}h",daysAgo:"{{count}}d ago",inDays:"in {{count}}d"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventory",writeTag:"Write",settings:"Settings"},status:{nfcReady:"NFC Ready",nfcOff:"NFC Off",offline:"Offline",online:"Online",noPrinters:"No printers",deviceOffline:"Device Offline",waitingConnection:"Waiting for device connection...",systemReady:"System Ready",status:"Status"},dashboard:{readyToScan:"Ready to scan",idleMessage:"Place a spool on the scale to identify it",nfcHint:"NFC tag will be read automatically",device:"Device",syncWeight:"Sync Weight",weightSynced:"Synced!",unknownTag:"Unknown Tag",newTag:"New Tag Detected",onScale:"on scale",linkSpool:"Link to Spool",linkTagTitle:"Link Tag to Spool",linkTag:"Link Tag",selectSpool:"Select a spool to link this tag to:",noUntagged:"No spools without tags found",tagDetected:"Tag detected",noTag:"No tag",tagId:"Tag",grossWeight:"Gross weight",spoolSize:"Spool size",close:"Close",currentSpool:"Current Spool"},modal:{spoolDetected:"Spool Detected",assignToAms:"Assign to AMS",syncWeight:"Sync Weight",weightSynced:"Synced!",syncing:"Syncing...",newTagDetected:"New Tag Detected",addToInventory:"Add to Inventory",assignToAmsTitle:"Assign to AMS",selectSlot:"Select a slot",assign:"Assign",assigning:"Assigning...",assignSuccess:"Assigned!",assignError:"Failed to assign spool. Please try again.",noPrinterSelected:"Select a printer...",noAmsDetected:"No AMS detected on this printer",slot:"Slot"},weight:{noReading:"No reading",stable:"Stable",measuring:"Measuring...",tare:"Tare",calibrate:"Calibrate"},spool:{remaining:"Remaining",material:"Material",brand:"Brand",color:"Color",coreWeight:"Core",labelWeight:"Label",scaleWeight:"Scale",netWeight:"Net",lastUsed:"Last used"},ams:{noData:"No AMS detected",connectAms:"Connect an AMS to see filament slots",noPrinter:"No printer selected",selectPrinter:"Select a printer from the top bar",printerDisconnected:"Printer disconnected",humidity:"Humidity",level:"Level",active:"Active",slot:"Slot",empty:"Empty"},inventory:{search:"Search spools...",empty:"No spools in inventory",noResults:"No matching spools",spools:"spools",addSpool:"Add Spool"},settings:{tabDevice:"Device",tabDisplay:"Display",tabScale:"Scale",tabUpdates:"Updates",nfcReader:"NFC Reader",type:"Type",connection:"Connection",notConnected:"N/A",deviceInfo:"Device Info",hostname:"Host",uptime:"Uptime",systemConfig:"Backend & Auth",backendUrl:"Bambuddy Backend URL",apiToken:"API Token",apiTokenPlaceholder:"Enter API token",saveConfig:"Save Config",systemQueued:"Config queued.",nfcDiagnostic:"NFC Diagnostic",scaleDiagnostic:"Scale Diagnostic",readTagDiagnostic:"Read Tag Diagnostic",testNfc:"Test reader",testScale:"Test accuracy",testReadTag:"Read tag",systemFieldsRequired:"Backend URL is required.",brightness:"Brightness",saved:"Saved",noBacklight:"No DSI backlight detected. Brightness control requires a DSI display.",screenBlank:"Screen Blank Timeout",screenBlankDesc:"Screen turns off after inactivity. Touch to wake.",displayNote:"Brightness is applied as a software filter.",scaleCalibration:"Scale Calibration",currentWeight:"Current weight",tareOffset:"Tare",calFactor:"Factor",knownWeight:"Known weight",calStep1:"Remove all items from the scale and press Set Zero.",calStep2:"Place known weight on scale.",setZero:"Set Zero",calibrateNow:"Calibrate",calibrated:"Calibrated",tareSet:"Tare command sent. Waiting for device...",tareFailed:"Failed to send tare command",zeroSet:"Zero point set. Place known weight on scale.",calibrationDone:"Calibration complete!",calibrationFailed:"Calibration failed",lastCalibrated:"Last calibrated",stable:"Stable",settling:"Settling...",firmware:"Firmware",scale:"Scale",noDevice:"No SpoolBuddy device found",daemonVersion:"Daemon Version",currentVersion:"Current",versionPending:"Waiting for daemon...",checking:"Checking...",checkUpdates:"Check for Updates",updateAvailable:"Update available",updateInstructions:"Update via SSH: run the SpoolBuddy install script to upgrade.",upToDate:"Up to date",includeBeta:"Include beta versions"},writeTag:{tabExisting:"Existing Spool",tabNew:"New Spool",tabReplace:"Replace Tag",searchPlaceholder:"Search by material, color, brand...",noUntaggedSpools:"No spools without tags",noTaggedSpools:"No spools with tags",selectSpool:"Select a spool, then place a blank NTAG on the reader",placeTag:"Place an NTAG on the reader",tagReady:"Tag detected — ready to write",writeTag:"Write Tag",replaceTag:"Replace Tag",writing:"Writing tag...",waiting:"Waiting for SpoolBuddy...",writeSuccess:"Tag written successfully!",writeFailed:"Write failed",queueFailed:"Failed to queue write command",tryAgain:"Try Again",cancel:"Cancel",replaceWarning:"Old tag will be unlinked. New tag will replace it.",deviceOffline:"SpoolBuddy is offline",material:"Material",colorName:"Color Name",color:"Color",brand:"Brand",weight:"Weight (g)",createSpool:"Create Spool",creating:"Creating...",spoolCreated:"Spool created! Ready to write.",createFailed:"Failed to create spool"},quickMenu:{printerPower:"Printer Power",systemControls:"System",restartDaemon:"Restart Daemon",restartBrowser:"Restart Browser",reboot:"Reboot",shutdown:"Shutdown",swipeToClose:"Swipe down to close",confirmTitle:"Confirm",confirmShutdown:"Are you sure you want to shut down the SpoolBuddy? You will need physical access to turn it back on.",confirmReboot:"Are you sure you want to reboot the SpoolBuddy?",confirmRestartDaemon:"Restart the SpoolBuddy daemon? NFC and scale will be temporarily unavailable.",confirmRestartBrowser:"Restart the kiosk browser? The display will briefly go blank.",confirm:"Confirm",confirmPlugOn:"Turn on {{name}}?",confirmPlugOff:"Turn off {{name}}?",turnOn:"Turn On",turnOff:"Turn Off"}},bugReport:{title:"Report a Bug",description:"Description",descriptionPlaceholder:"What went wrong? Please describe the issue...",email:"Email (optional)",emailPlaceholder:"your@email.com",emailPrivacy:"If provided, your email will be included in a collapsed section of the GitHub issue so the maintainer can follow up.",screenshot:"Screenshot",uploadOrPaste:"Upload, paste, or drag an image",dataCollectedSummary:"What data is included in the report?",dataIncluded:"Included:",dataIncludedList:"App version, OS, architecture, Python version, database stats (counts only), printer models, nozzle counts, firmware versions, connectivity status, integration status (Spoolman, MQTT, HA), non-sensitive settings, network interface count, Docker details, dependency versions.",dataNeverIncluded:"Never included:",dataNeverIncludedList:"Printer names, serial numbers, access codes, passwords, IP addresses, email addresses, API keys, tokens, webhook URLs, hostnames, or usernames.",submit:"Submit",startLogging:"Start Debug Logging",stepEnableLogging:"Debug logging enabled",stepReproduce:"Reproduce the issue now",stepStopLogging:"Stop & submit report",stopAndSubmit:"Stop & Submit",maxDuration:"Auto-stops after {{minutes}} min",stoppingLogs:"Collecting logs & submitting...",submitting:"Submitting bug report...",submitSuccess:"Bug report submitted successfully!",submitFailed:"Failed to submit bug report",thankYou:"Thank you!",submitted:"Your bug report has been submitted.",viewIssue:"View Issue",unexpectedError:"An unexpected error occurred"}},_ue={nav:{printers:"Drucker",archives:"Archiv",queue:"Warteschlange",stats:"Statistiken",profiles:"Profile",maintenance:"Wartung",projects:"Projekte",inventory:"Filament",files:"Dateimanager",notifications:"Benachrichtigungen",settings:"Einstellungen",system:"System",collapseSidebar:"Seitenleiste einklappen",expandSidebar:"Seitenleiste ausklappen",update:"Update",updateAvailable:"Update verfügbar: v{{version}}",updateAvailableBanner:"Version {{version}} ist verfügbar!",viewUpdate:"Update anzeigen",viewOnGithub:"Auf GitHub ansehen",keyboardShortcuts:"Tastaturkürzel (?)",switchToLight:"Zum hellen Modus wechseln",switchToDark:"Zum dunklen Modus wechseln",smartSwitches:"Smart Switches",logout:"Abmelden"},common:{save:"Speichern",saving:"Speichern...",cancel:"Abbrechen",delete:"Löschen",edit:"Bearbeiten",add:"Hinzufügen",close:"Schließen",confirm:"Bestätigen",loading:"Lädt...",error:"Fehler",success:"Erfolg",warning:"Warnung",enabled:"Aktiviert",disabled:"Deaktiviert",yes:"Ja",no:"Nein",on:"An",off:"Aus",all:"Alle",none:"Keine",search:"Suchen",filter:"Filtern",sort:"Sortieren",refresh:"Aktualisieren",download:"Herunterladen",upload:"Hochladen",uploading:"Hochladen...",uploadFailed:"Hochladen fehlgeschlagen",actions:"Aktionen",status:"Status",name:"Name",description:"Beschreibung",date:"Datum",time:"Zeit",hours:"Stunden",minutes:"Minuten",seconds:"Sekunden",days:"Tage",enable:"Aktivieren",disable:"Deaktivieren",permissions:"Berechtigungen",noPrinters:"Keine Drucker konfiguriert",noData:"Keine Daten verfügbar",linkNotFound:"Link nicht gefunden",required:"Erforderlich",optional:"Optional",dismiss:"Schließen",apply:"Anwenden",reset:"Zurücksetzen",export:"Exportieren",import:"Importieren",clear:"Leeren",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",noChange:"— Keine Änderung —",unchanged:"Unverändert",unassigned:"Nicht zugewiesen",unknown:"Unbekannt",unknownError:"Unbekannter Fehler",today:"Heute",tomorrow:"Morgen",asap:"Sofort",overdue:"Überfällig",now:"Jetzt",collapse:"Einklappen",expand:"Ausklappen",viewArchive:"Archiv anzeigen",viewInFileManager:"Im Dateimanager anzeigen",addedBy:"Hinzugefügt von {{username}}",prints:"Drucke",more:"+{{count}} weitere",ascending:"Aufsteigend",descending:"Absteigend",printer:"Drucker",remove:"Entfernen",type:"Typ",print:"Drucken",rename:"Umbenennen",move:"Verschieben",create:"Erstellen",duplicate:"Duplizieren",left:"Links",right:"Rechts"},printers:{title:"Drucker",addPrinter:"Drucker hinzufügen",editPrinter:"Drucker bearbeiten",deletePrinter:"Drucker löschen",printerName:"Druckername",serialNumber:"Seriennummer",ipAddress:"IP-Adresse / Hostname",accessCode:"Zugangscode",model:"Modell",nozzleCount:"Düsenanzahl",autoArchive:"Automatische Archivierung",status:{available:"Verfügbar",idle:"Bereit",printing:"Druckt",paused:"Pausiert",offline:"Offline",problem:"Problem",error:"Fehler",finished:"Fertig",unknown:"Unbekannt"},temperatures:{nozzle:"Düse",bed:"Druckbett",chamber:"Kammer"},progress:"{{percent}}% abgeschlossen",timeRemaining:"Noch {{time}}",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',maintenanceOk:"Wartung OK",maintenanceWarning:"{{count}} Warnung",maintenanceWarning_plural:"{{count}} Warnungen",maintenanceDue:"{{count}} fällig",maintenanceDue_plural:"{{count}} fällig",sort:{name:"Name",status:"Status",model:"Modell",location:"Standort",ascending:"Aufsteigend sortieren",descending:"Absteigend sortieren"},cardSize:{small:"Kleine Karten",medium:"Mittlere Karten",large:"Große Karten",extraLarge:"Extra große Karten"},hideOffline:"Offline ausblenden",nextAvailable:"Nächster verfügbar",powerOn:"Einschalten",offlinePrintersWithPlugs:"Offline-Drucker mit Smart-Plugs",noPrintersConfigured:"Noch keine Drucker konfiguriert",search:"Drucker suchen...",noSearchResults:"Keine Drucker entsprechen deiner Suche oder deinen Filtern",filter:{allStatuses:"Alle Status",allLocations:"Alle Standorte"},readyToPrint:"Druckbereit",external:"Extern",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Druckarchive löschen",noLabel:"Keine Bezeichnung",printPreview:"Druckvorschau",width:"Breite",height:"Höhe",noObjectsFound:"Keine Objekte gefunden",objectsLoadedOnPrintStart:"Objekte werden beim Druckstart geladen",willBeSkipped:"Wird übersprungen",name:"Name",serialCannotBeChanged:"Seriennummer kann nicht geändert werden",locationHelp:"Dient zur Gruppierung von Druckern und zum Filtern von Warteschlangenaufträgen",wifiSignal:{veryWeak:"Sehr schwach",weak:"Schwach",fair:"Ausreichend",good:"Gut",excellent:"Ausgezeichnet"},maintenanceUpToDate:"Alle Wartungen aktuell - Klicken zum Anzeigen",chamberLightOn:"Kammerbeleuchtung einschalten",chamberLightOff:"Kammerbeleuchtung ausschalten",files:"Dateien",browseFiles:"Druckerdateien durchsuchen",autoOffAfterPrint:"Automatisches Ausschalten nach Druck",autoOffExecuted:"Auto-off wurde ausgeführt - Drucker einschalten zum Zurücksetzen",hmsErrors:"HMS-Fehler",viewHmsErrors:"{{count}} HMS-Fehler anzeigen",resume:"Fortsetzen",pause:"Pausieren",stop:"Stoppen",camera:"Kamera",skipObject:"Objekt überspringen",reconnect:"Neu verbinden",mqttDebug:"MQTT-Debug",printerInformation:"Druckerinformationen",copyToClipboard:"Kopieren",copied:"Kopiert!",state:"Zustand",wifiSignalLabel:"WLAN-Signal",developerMode:"Entwicklermodus",enabled:"Aktiviert",disabled:"Deaktiviert",addedOn:"Hinzugefügt",sdCard:"SD-Karte",inserted:"Eingelegt",notInserted:"Nicht eingelegt",totalPrintHours:"Druckstunden",activeNozzle:"Aktiv: {{nozzle}} Düse",nozzleRack:"Düsenhalter",nozzleDocked:"Angedockt",nozzleMounted:"Montiert",nozzleActive:"Aktiv",nozzleIdle:"Inaktiv",nozzleDiameter:"Durchmesser",nozzleType:"Typ",nozzleStatus:"Status",nozzleFilament:"Filament",nozzleWear:"Verschleiß",nozzleMaxTemp:"Max Temp",nozzleSerial:"Seriennr.",nozzleHardenedSteel:"Gehärteter Stahl",nozzleStainlessSteel:"Edelstahl",nozzleTungstenCarbide:"Wolframkarbid",nozzleFlow:"Durchfluss",nozzleHighFlow:"High Flow",nozzleStandardFlow:"Standard",firmwareUpdate:"Firmware-Update",firmwareInstructions:"Gehen Sie auf dem Touchscreen des Druckers zu",firmwareNav:"Navigieren Sie zu",settings:"Einstellungen",firmware:"Firmware",discoverPrinters:"Drucker entdecken",searching:"Suche...",manualEntry:"Manuelle Eingabe",addFromCloud:"Aus Cloud hinzufügen",toast:{printerDeleted:"Drucker gelöscht",missingSpoolAssignment:"Druck gestartet auf {{printer}}. Fehlende Spulenzuordnung für: {{slots}}",printerAdded:"Drucker hinzugefügt",printerUpdated:"Drucker aktualisiert",failedToDelete:"Drucker konnte nicht gelöscht werden",failedToAdd:"Drucker konnte nicht hinzugefügt werden",failedToUpdate:"Drucker konnte nicht aktualisiert werden",commandSent:"Befehl gesendet",failedToSendCommand:"Befehl konnte nicht gesendet werden",turnedOn:"{{name}} eingeschaltet",failedToPowerOn:"{{name}} konnte nicht eingeschaltet werden",scriptTriggered:"Skript ausgelöst",printStopped:"Druck gestoppt",printPaused:"Druck pausiert",printResumed:"Druck fortgesetzt",referenceDeleted:"Referenz gelöscht",detectionAreaSaved:"Erkennungsbereich gespeichert",failedToRunScript:"Skript konnte nicht ausgeführt werden",failedToStopPrint:"Druck konnte nicht gestoppt werden",failedToPausePrint:"Druck konnte nicht pausiert werden",failedToResumePrint:"Druck konnte nicht fortgesetzt werden",failedToControlChamberLight:"Kammerbeleuchtung konnte nicht gesteuert werden",failedToSetSpeed:"Druckgeschwindigkeit konnte nicht eingestellt werden",failedToUpdateSetting:"Einstellung konnte nicht aktualisiert werden",failedToSkipObjects:"Objekte konnten nicht übersprungen werden",failedToRereadRfid:"RFID konnte nicht erneut gelesen werden",failedToCheckPlate:"Platte konnte nicht überprüft werden",failedToUpdateLabel:"Bezeichnung konnte nicht aktualisiert werden",failedToDeleteReference:"Referenz konnte nicht gelöscht werden",failedToSaveDetectionArea:"Erkennungsbereich konnte nicht gespeichert werden",plateCheckEnabled:"Plattenprüfung aktiviert",plateCheckDisabled:"Plattenprüfung deaktiviert",calibrationSaved:"Kalibrierung gespeichert!",calibrationFailed:"Kalibrierung fehlgeschlagen",rfidRereadInitiated:"RFID-Neueinlesen gestartet"},connection:{connected:"Verbunden",offline:"Offline"},queue:{inQueue:"{{count}} Druck in Warteschlange",inQueue_plural:"{{count}} Drucke in Warteschlange"},controls:"Steuerung",rfid:{reread:"RFID neu lesen"},permission:{noAdd:"Sie haben keine Berechtigung, Drucker hinzuzufügen",noEdit:"Sie haben keine Berechtigung, Drucker zu bearbeiten",noDelete:"Sie haben keine Berechtigung, Drucker zu löschen",noControl:"Sie haben keine Berechtigung, Drucker zu steuern",noFiles:"Sie haben keine Berechtigung, auf Druckerdateien zuzugreifen",noAmsRfid:"Sie haben keine Berechtigung, AMS-RFID erneut zu lesen",noSmartPlugControl:"Sie haben keine Berechtigung, Smart Plugs zu steuern",noCamera:"Sie haben keine Berechtigung, Kameras anzuzeigen"},modal:{addTitle:"Drucker hinzufügen",editTitle:"Drucker bearbeiten",myPrinter:"Mein Drucker",selectModel:"Modell auswählen...",locationGroup:"Standort / Gruppe (optional)",locationPlaceholder:"z.B. Werkstatt, Büro, Keller",autoArchiveLabel:"Abgeschlossene Drucke automatisch archivieren",fromPrinterSettings:"Aus Druckereinstellungen",modelOptional:"Modell (optional)",saveChanges:"Änderungen speichern"},skipObjects:{tooltip:"Objekte überspringen",onlyWhilePrinting:"Objekte überspringen (nur während des Drucks)",requiresMultiple:"Objekte überspringen (erfordert 2+ Objekte)",title:"Objekte überspringen",matchIdsInfo:"IDs mit Drucker-Display abgleichen",printerShowsIds:"Der Druckerbildschirm zeigt Objekt-IDs auf der Bauplatte",skipSelected:"Ausgewählte überspringen",skipping:"Überspringe...",noObjectsSelected:"Keine Objekte ausgewählt",selectObjectsToSkip:"Wählen Sie Objekte aus, die Sie vom aktuellen Druck überspringen möchten",skipped:"übersprungen",objectsSkipped:"Objekte übersprungen",activeCount:"{{count}} aktiv",waitForLayer:"Warten Sie auf Schicht 2+ zum Überspringen von Objekten (aktuell Schicht {{layer}})",skip:"Überspringen",confirmTitle:"Objekt überspringen?",confirmMessage:'Möchten Sie "{{name}}" wirklich überspringen? Dies kann nicht rückgängig gemacht werden.'},confirm:{deleteTitle:"Drucker löschen",deleteMessage:'Möchten Sie "{{name}}" wirklich löschen? Alle Verbindungseinstellungen werden entfernt.',deleteArchivesNote:"Der gesamte Druckverlauf für diesen Drucker wird dauerhaft gelöscht.",keepArchivesNote:"Der Druckverlauf wird beibehalten, aber nicht mehr mit diesem Drucker verknüpft.",stopTitle:"Druck stoppen",stopMessage:'Möchten Sie den aktuellen Druck auf "{{name}}" wirklich stoppen? Der Druckauftrag wird abgebrochen.',stopButton:"Druck stoppen",pauseTitle:"Druck pausieren",pauseMessage:'Möchten Sie den aktuellen Druck auf "{{name}}" wirklich pausieren?',pauseButton:"Druck pausieren",resumeTitle:"Druck fortsetzen",resumeMessage:'Möchten Sie den Druck auf "{{name}}" fortsetzen?',resumeButton:"Druck fortsetzen",powerOnTitle:"Drucker einschalten",powerOnMessage:'Möchten Sie die Stromversorgung für "{{name}}" wirklich EINSCHALTEN?',powerOnButton:"Einschalten",powerOffTitle:"Drucker ausschalten",powerOffMessage:'Möchten Sie die Stromversorgung für "{{name}}" wirklich AUSSCHALTEN?',powerOffWarning:'WARNUNG: "{{name}}" druckt gerade! Möchten Sie die Stromversorgung wirklich AUSSCHALTEN? Dies unterbricht den Druck und kann den Drucker beschädigen.',powerOffButton:"Ausschalten"},bulk:{select:"Auswählen",selectAll:"Alle auswählen",selectByLocation:"Nach Standort auswählen",selected:"{{count}} ausgewählt",actions:{stop:"Stoppen",pause:"Pausieren",resume:"Fortsetzen",clearPlate:"Druckbett leeren",clearHMS:"Benachrichtigungen löschen"},confirm:{stopTitle:"{{count}} Drucke stoppen",stopMessage:"Dies wird aktive Drucke auf {{count}} Drucker(n) abbrechen. Diese Aktion kann nicht rückgängig gemacht werden.",stopButton:"Alle stoppen",pauseTitle:"{{count}} Drucke pausieren",pauseMessage:"Dies wird aktive Drucke auf {{count}} Drucker(n) pausieren.",pauseButton:"Alle pausieren",clearPlateTitle:"{{count}} Druckbetten leeren",clearPlateMessage:"Dies wird das Druckbett auf {{count}} Drucker(n) leeren und kann wartende Aufträge starten.",clearPlateButton:"Alle leeren"},success:"{{action}} auf {{count}} Drucker(n) abgeschlossen",partial:"{{succeeded}} erfolgreich, {{failed}} fehlgeschlagen",noneApplicable:"Keine ausgewählten Drucker sind im richtigen Zustand für diese Aktion",selectByState:"Nach Status auswählen"},discovery:{title:"Drucker entdecken",searching:"Suche...",scanning:"Scanne...",scanProgress:"Scanne... {{scanned}}/{{total}}",foundPrinters:"{{count}} Drucker gefunden",noPrintersFound:"Keine Drucker gefunden",noPrintersFoundSubnet:"Keine Drucker im angegebenen Subnetz gefunden.",noPrintersFoundNetwork:"Keine Drucker im Netzwerk gefunden.",allConfigured:"Alle erkannten Drucker sind bereits konfiguriert.",alreadyAdded:"Bereits hinzugefügt",select:"Auswählen",manualEntry:"Manuelle Eingabe",addFromCloud:"Aus Cloud hinzufügen",subnetToScan:"Zu scannendes Subnetz",dockerNote:"Docker erkannt. Geben Sie das Subnetz Ihres Druckers in CIDR-Notation ein. Erfordert network_mode: host in docker-compose.yml.",scanSubnet:"Subnetz nach Druckern scannen",discoverNetwork:"Drucker im Netzwerk suchen",scanningSubnet:"Subnetz wird nach Bambu-Druckern gescannt...",scanningNetwork:"Netzwerk wird gescannt...",serialRequired:"Seriennummer erforderlich",unknown:"Unbekannt",failedToStart:"Erkennung konnte nicht gestartet werden"},drying:{start:"Trocknung starten",stop:"Trocknung stoppen",temperature:"Temperatur",duration:"Dauer",hours:"Stunden",timeRemaining:"{{time}} verbleibend",active:"Trocknung",notSupported:"Trocknung nicht unterstützt",powerRequired:"AMS-Netzteil anschließen, um Trocknung zu aktivieren",startingDrying:"Trocknung wird gestartet...",stoppingDrying:"Trocknung wird gestoppt...",rotateTray:"Spule während der Trocknung drehen"},filaments:"Filamente",openCameraOverlay:"Kamera-Overlay öffnen",openCameraWindow:"Kamera in neuem Fenster öffnen",firmwareUpdateAvailable:"Firmware-Update verfügbar: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Aktuell",firmwareUpdateButton:"Update",plateDetection:{noPermission:"Sie haben keine Berechtigung, Drucker zu aktualisieren",enabledClick:"Plattenprüfung aktiviert - Klicken zum Deaktivieren",disabledClick:"Plattenprüfung deaktiviert - Klicken zum Aktivieren",manageCalibration:"Platten-Erkennungskalibrierung verwalten",calibrationRequired:"Kalibrierung erforderlich",calibrationInstructions:"Bitte stellen Sie sicher, dass die Druckplatte <strong>vollständig leer</strong> ist, und klicken Sie dann auf Kalibrieren.",calibrationDescription:"Die Kalibrierung erfasst ein Referenzbild der leeren Platte. Zukünftige Prüfungen vergleichen mit dieser Referenz, um Objekte zu erkennen.",calibrationTip:"<strong>Tipp:</strong> Sie können bis zu 5 Kalibrierungen für verschiedene Platten speichern. Das System verwendet automatisch die beste Übereinstimmung bei der Prüfung.",plateEmpty:"Platte erscheint leer",objectsDetected:"Objekte auf Platte erkannt",confidence:"Konfidenz",difference:"Differenz",analysisPreview:"Analysevorschau:",analysisLegend:"Grüner Rahmen = Erkennungsbereich, Rote Überlagerung = Unterschiede zur Kalibrierung",savedReferences:"Gespeicherte Referenzen ({{count}}/{{max}})",deleteReference:"Referenz löschen",labelPlaceholder:"Bezeichnung...",clickToEdit:"{{label}} - Zum Bearbeiten klicken",clickToAddLabel:"Zum Hinzufügen einer Bezeichnung klicken"},speed:{title:"Druckgeschwindigkeit",silent:"Leise (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},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."},accessCodePlaceholder:"Leer lassen, um den aktuellen zu behalten",roi:{title:"Erkennungsbereich (ROI)",xStart:"X-Start",yStart:"Y-Start",width:"Breite",height:"Höhe",instruction:"Passen Sie den Erkennungsbereich an, um sich auf die Druckplatte zu konzentrieren. Der grüne Rahmen in der Vorschau zeigt den aktuellen Bereich."},developerModeWarning:"Der Entwickler-LAN-Modus ist nicht aktiviert auf: {{names}}. Einige Funktionen funktionieren möglicherweise nicht.",howToEnable:"Aktivieren",incompatibleFile:"Diese Datei wurde für {{slicedFor}} geslicet, aber dieser Drucker ist ein {{printerModel}}",dropNotPrintable:"Nur .gcode- und .gcode.3mf-Dateien können gedruckt werden",dropToPrint:"Zum Drucken ablegen",cannotPrint:"Drucker beschäftigt"},archives:{title:"Druckarchiv",searchPlaceholder:"Archiv durchsuchen...",filterByPrinter:"Nach Drucker filtern",filterByStatus:"Nach Status filtern",sortBy:"Sortieren nach",sortNewest:"Neueste zuerst",sortOldest:"Älteste zuerst",sortName:"Name",sortDuration:"Dauer",sortLargest:"Größte zuerst",sortSmallest:"Kleinste zuerst",sortSize:"Größe",noArchives:"Keine Archive gefunden",noArchivesSearch:"Keine Archive entsprechen Ihrer Suche",originalPrintNotVisible:"Ursprünglicher Druck nicht sichtbar - versuchen Sie, die Filter zu löschen",noArchivesYet:"Noch keine Archive",prints:"Drucke",pagination:{showing:"Zeige",to:"bis",of:"von",show:"Zeige",page:"Seite",all:"Alle"},loadingArchives:"Lade Archive...",releaseToUpload:"Loslassen zum Hochladen",showAll:"Alle anzeigen",showFavoritesOnly:"Nur Favoriten anzeigen",gridView:"Rasteransicht",listView:"Listenansicht",calendarView:"Kalenderansicht",logView:"Druckprotokoll",manageTags:"Tags verwalten",showFailedPrints:"Fehlgeschlagene Drucke anzeigen",hideFailedPrints:"Fehlgeschlagene Drucke ausblenden",hideDuplicates:"Duplikate ausblenden",viewOriginalPrint:"Klicken, um den ursprünglichen Druck anzuzeigen (#{{id}})",printTime:"Druckzeit",filamentUsed:"Verbrauchtes Filament",cost:"Kosten",reprint:"Drucken",preview:"Vorschau",deleteArchive:"Archiv löschen",deleteConfirm:"Möchten Sie dieses Archiv wirklich löschen?",favorite:"Favorit",unfavorite:"Aus Favoriten entfernen",viewDetails:"Details anzeigen",status:{completed:"Abgeschlossen",failed:"Fehlgeschlagen",stopped:"Gestoppt"},toast:{source3mfAttached:"Quell-3MF angehängt: {{filename}}",failedUploadSource3mf:"Fehler beim Hochladen der Quell-3MF",source3mfRemoved:"Quell-3MF entfernt",failedRemoveSource3mf:"Fehler beim Entfernen der Quell-3MF",f3dAttached:"F3D angehängt: {{filename}}",failedUploadF3d:"Fehler beim Hochladen der F3D",f3dRemoved:"F3D entfernt",failedRemoveF3d:"Fehler beim Entfernen der F3D",timelapseAttached:"Zeitraffer angehängt: {{filename}}",timelapseAlreadyAttached:"Zeitraffer bereits angehängt",noMatchingTimelapse:"Kein passender Zeitraffer gefunden",failedScanTimelapse:"Fehler beim Suchen nach Zeitraffer",failedAttachTimelapse:"Fehler beim Anhängen des Zeitraffers",timelapseRemoved:"Zeitraffer entfernt",failedRemoveTimelapse:"Fehler beim Entfernen des Zeitraffers",timelapseUploaded:"Zeitraffer hochgeladen: {{filename}}",failedUploadTimelapse:"Fehler beim Hochladen des Zeitraffers",archiveDeleted:"Archiv gelöscht",failedDeleteArchive:"Fehler beim Löschen des Archivs",addedToFavorites:"Zu Favoriten hinzugefügt",removedFromFavorites:"Aus Favoriten entfernt",projectUpdated:"Projekt aktualisiert",failedUpdateProject:"Fehler beim Aktualisieren des Projekts",linkCopied:"Link in die Zwischenablage kopiert",failedCopyLink:"Fehler beim Kopieren des Links",photoDeleted:"Foto gelöscht",failedDeletePhoto:"Fehler beim Löschen des Fotos",failedDeleteArchives:"Fehler beim Löschen der Archive",failedUpdateFavorites:"Fehler beim Aktualisieren der Favoriten",exportDownloaded:"Export heruntergeladen",exportFailed:"Export fehlgeschlagen"},menu:{print:"Drucken",schedule:"Planen",openInBambuStudio:"Im Slicer öffnen",slice:"Slicen",externalLink:"Externer Link",viewOnMakerWorld:"Auf MakerWorld ansehen",preview3d:"3D-Vorschau",viewTimelapse:"Zeitraffer ansehen",scanForTimelapse:"Nach Zeitraffer suchen",uploadTimelapse:"Zeitraffer hochladen",removeTimelapse:"Zeitraffer entfernen",downloadSource3mf:"Quell-3MF herunterladen",uploadSource3mf:"Quell-3MF hochladen",replaceSource3mf:"Quell-3MF ersetzen",removeSource3mf:"Quell-3MF entfernen",uploadF3d:"F3D hochladen",replaceF3d:"F3D ersetzen",downloadF3d:"F3D herunterladen",removeF3d:"F3D entfernen",download:"Herunterladen",copyDownloadLink:"Download-Link kopieren",qrCode:"QR-Code",viewPhotos:"Fotos ansehen",viewPhotosCount:"Fotos ansehen ({{count}})",projectPage:"Projektseite",addToFavorites:"Zu Favoriten hinzufügen",removeFromFavorites:"Aus Favoriten entfernen",edit:"Bearbeiten",goToProject:"Zum Projekt: {{name}}",addToProject:"Zu Projekt hinzufügen",removeFromProject:"Aus Projekt entfernen",loading:"Laden...",noProjectsAvailable:"Keine Projekte verfügbar",select:"Auswählen",deselect:"Abwählen",delete:"Löschen"},permission:{noReprint:"Sie haben keine Berechtigung, dieses Archiv erneut zu drucken",noAddToQueue:"Sie haben keine Berechtigung, zur Warteschlange hinzuzufügen",noUpdateArchives:"Sie haben keine Berechtigung, Archive zu aktualisieren",noUploadFiles:"Sie haben keine Berechtigung, Dateien hochzuladen",noDownload:"Sie haben keine Berechtigung, Archive herunterzuladen",noCopyLink:"Sie haben keine Berechtigung, Download-Links zu kopieren",noDelete:"Sie haben keine Berechtigung, dieses Archiv zu löschen",noCreate:"Sie haben keine Berechtigung, Archive zu erstellen"},card:{previousPlate:"Vorherige Platte",nextPlate:"Nächste Platte",plateNumber:"Platte {{index}}",moreOptions:"Rechtsklick für mehr Optionen",addToFavorites:"Zu Favoriten hinzufügen",removeFromFavorites:"Aus Favoriten entfernen",cancelled:"abgebrochen",failed:"fehlgeschlagen",duplicate:"Duplikat",duplicateTitle:"Dieses Modell wurde bereits zuvor gedruckt",openSource3mf:"Quell-3MF in Bambu Studio öffnen (Rechtsklick für mehr Optionen)",downloadF3d:"Fusion 360 Designdatei herunterladen",viewTimelapse:"Zeitraffer ansehen",viewPhoto:"1 Foto ansehen",viewPhotos:"{{count}} Fotos ansehen",openFolder:"Ordner öffnen: {{name}}",slicedFile:"Geslicte Datei - druckbereit",sourceFile:"Nur Quelldatei - keine AMS-Zuordnung verfügbar",gcode:"GCODE",source:"QUELLE",project:"Projekt: {{name}}",estimated:"Geschätzt: {{time}}",actual:"Tatsächlich: {{time}}",accuracy:"Genauigkeit: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} Schicht",layers:"{{count}} Schichten",object:"{{count}} Objekt",objects:"{{count}} Objekte",slicedFor:"Geslict für {{model}}",uploadedBy:"Hochgeladen von",noPermissionReprint:"Sie haben keine Berechtigung, erneut zu drucken",noFileForReprint:"Keine 3MF-Datei verfügbar — die Datei konnte beim Aufzeichnen des Drucks nicht vom Drucker heruntergeladen werden",noPermissionEdit:"Sie haben keine Berechtigung, Archive zu bearbeiten",noPermissionDelete:"Sie haben keine Berechtigung, Archive zu löschen",reprint:"Drucken",schedulePrint:"Druck planen",schedule:"Planen",openInBambuStudio:"Im Slicer öffnen",openInBambuStudioToSlice:"Im Slicer öffnen zum Slicen",slice:"Slicen",externalLink:"Externer Link",makerWorld:"MakerWorld: {{designer}}",viewProject:"Projekt ansehen",noExternalLink:"Kein externer Link",preview3d:"3D-Vorschau",download:"Herunterladen",edit:"Bearbeiten",delete:"Löschen"},modal:{deleteArchive:"Archiv löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.',deleteButton:"Löschen",removeSource3mf:"Quell-3MF entfernen",removeSource3mfConfirm:'Möchten Sie die Quell-3MF-Datei wirklich von "{{name}}" entfernen? Die ursprüngliche Slicer-Projektdatei wird gelöscht.',removeButton:"Entfernen",removeF3d:"F3D entfernen",removeF3dConfirm:'Möchten Sie die Fusion 360 Designdatei wirklich von "{{name}}" entfernen?',removeTimelapse:"Zeitraffer entfernen",removeTimelapseConfirm:'Möchten Sie das Zeitraffervideo wirklich von "{{name}}" entfernen?',timelapse:"{{name}} - Zeitraffer",selectTimelapse:"Zeitraffer auswählen",selectTimelapseDesc:"Keine automatische Übereinstimmung gefunden. Wählen Sie den Zeitraffer für diesen Druck:",deleteArchives:"Archive löschen",deleteArchivesConfirm:"Möchten Sie wirklich {{count}} Archiv(e) löschen? Diese Aktion kann nicht rückgängig gemacht werden.",deleteCount:"{{count}} löschen"},page:{title:"Archive",printsCount:"{{filtered}} von {{total}} Drucken",dropFilesHere:".3mf-Dateien hier ablegen",releaseToUpload:"Loslassen zum Hochladen",only3mfSupported:"Nur .3mf-Dateien werden unterstützt",close:"Schließen",selected:"{{count}} ausgewählt",selectAll:"Alle auswählen",tags:"Tags",project:"Projekt",favorite:"Favorit",delete:"Löschen",toggledFavorites:"Favoriten für {{count}} Archiv(e) umgeschaltet",failedUpdateFavorites:"Fehler beim Aktualisieren der Favoriten",archivesDeleted:"{{count}} Archiv(e) gelöscht",failedDeleteArchives:"Fehler beim Löschen der Archive",photoDeleted:"Foto gelöscht",failedDeletePhoto:"Fehler beim Löschen des Fotos"},list:{name:"Name",printer:"Drucker",date:"Datum",size:"Größe",actions:"Aktionen",hasTimelapse:"Hat Zeitraffer"},log:{date:"Datum",printName:"Druckname",printer:"Drucker",user:"Benutzer",status:"Status",duration:"Dauer",filament:"Filament",allPrinters:"Alle Drucker",allUsers:"Alle Benutzer",allStatuses:"Alle Status",cancelled:"Abgebrochen",skipped:"Übersprungen",dateFrom:"Von",dateTo:"Bis",noEntries:"Keine Druckprotokolleinträge gefunden",showing:"{{count}} von {{total}} Einträgen",rowsPerPage:"Zeilen",page:"Seite",prev:"Zurück",next:"Weiter",clearLog:"Protokoll löschen",clearLogTitle:"Druckprotokoll löschen",clearLogConfirm:"Alle Druckprotokolleinträge werden dauerhaft gelöscht. Archive und Warteschlangeneinträge sind nicht betroffen. Diese Aktion kann nicht rückgängig gemacht werden. Sind Sie sicher?",clearLogButton:"Alle löschen",cleared:"{{count}} Protokolleinträge gelöscht",clearFailed:"Druckprotokoll konnte nicht gelöscht werden"}},queue:{title:"Druckwarteschlange",subtitle:"Planen und verwalten Sie Ihre Druckaufträge",addToQueue:"Zur Warteschlange hinzufügen",print:"Drucken",reprint:"Erneut drucken",schedulePrint:"Druck planen",editQueueItem:"Warteschlangeneintrag bearbeiten",printToPrinters:"Auf {{count}} Druckern drucken",queueToPrinters:"Zu {{count}} Druckern hinzufügen",queueSelectedPlates:"{{count}} Platten in die Warteschlange",selectAllPlates:"Alle {{count}} Platten auswählen",deselectAll:"Alle abwählen",printQueued:"Druck in Warteschlange",itemsQueued:"{{count}} Einträge in Warteschlange",sending:"Wird gesendet...",sendingProgress:"Sende {{current}}/{{total}}...",adding:"Wird hinzugefügt...",addingProgress:"Füge hinzu {{current}}/{{total}}...",savingProgress:"Speichere {{current}}/{{total}}...",clearQueue:"Warteschlange leeren",clearHistory:"Verlauf löschen",emptyQueue:"Warteschlange ist leer",position:"Position",scheduledTime:"Geplante Zeit",moveUp:"Nach oben",moveDown:"Nach unten",startNow:"Jetzt starten",printingInProgress:"Druck läuft...",viewArchive:"Archiv anzeigen",viewInFileManager:"Im Dateimanager anzeigen",itemCount:"{{count}} Element",itemCount_plural:"{{count}} Elemente",dragToReorder:"Ziehen zum Neuordnen (nur Sofort)",reorderHint:"Position betrifft nur Sofort-Elemente. Geplante Elemente werden zur festgelegten Zeit ausgeführt.",sjf:{label:"SJF",tooltip:"Kürzester Auftrag zuerst — Scheduler bevorzugt kürzere Drucke"},addedBy:"Hinzugefügt von {{name}}",nextInQueue:"Nächster in der Warteschlange",clearPlate:"Druckplatte freigeben & Nächsten starten",clearPlateSuccess:"Druckplatte freigegeben — bereit für nächsten Druck",plateReady:"Druckplatte freigegeben — bereit für nächsten Druck",plateNumber:"Platte {{index}}",quantity:"Menge",quantityHint:"Erstellt {{count}} Warteschlangeneinträge",activeBatches:"Aktive Stapel",batchProgress:"{{completed}} von {{total}} abgeschlossen",cancelBatch:"Verbleibende abbrechen",batchCancelled:"Verbleibende Stapeleinträge abgebrochen",cancelBatchConfirmTitle:"Stapel abbrechen",cancelBatchConfirmMessage:"Alle verbleibenden ausstehenden Einträge in diesem Stapel abbrechen?",batch:"Stapel",sections:{currentlyPrinting:"Aktuell druckend",queued:"In Warteschlange",history:"Verlauf"},status:{pending:"Ausstehend",waiting:"Wartend",printing:"Druckt",paused:"Pausiert",completed:"Abgeschlossen",failed:"Fehlgeschlagen",skipped:"Übersprungen",cancelled:"Abgebrochen"},summary:{printing:"Druckt",queued:"In Warteschlange",totalTime:"Gesamte Wartezeit",totalWeight:"Gesamtgewicht der Warteschlange",history:"Verlauf"},filter:{allPrinters:"Alle Drucker",unassigned:"Nicht zugewiesen",allStatus:"Alle Status",allLocations:"Alle Standorte",any:"Beliebig"},sort:{byPosition:"Nach Position sortieren",byName:"Nach Name sortieren",byPrinter:"Nach Drucker sortieren",bySchedule:"Nach Zeitplan sortieren",byDate:"Nach Datum sortieren",ascendingOldest:"Aufsteigend (älteste zuerst)",descendingNewest:"Absteigend (neueste zuerst)"},badges:{staged:"Bereitgestellt",requiresPrevious:"Erfordert vorherigen Erfolg",autoPowerOff:"Automatisch ausschalten",gcodeInjection:"G-code"},empty:{title:"Keine Drucke geplant",description:'Planen Sie einen Druck von der Archivseite über die Option "Planen" im Kontextmenü oder ziehen Sie Dateien hierher.'},time:{asap:"Sofort",overdue:"Überfällig",now:"Jetzt",lessThanMinute:"In weniger als einer Minute",inMinutes:"In {{count}} Min",inHours:"In {{count}} Stunden"},actions:{stopPrint:"Druck stoppen",startPrint:"Druck starten",requeue:"Erneut einreihen"},bulkEdit:{title:"{{count}} Element bearbeiten",title_plural:"{{count}} Elemente bearbeiten",description:"Nur geänderte Einstellungen werden auf ausgewählte Elemente angewendet.",printer:"Drucker",noChange:"— Keine Änderung —",queueOptions:"Warteschlangenoptionen",staged:"Bereitgestellt (manueller Start)",autoPowerOff:"Nach Druck automatisch ausschalten",requirePrevious:"Vorherigen Erfolg erfordern",printOptions:"Druckoptionen",bedLevelling:"Bett-Nivellierung",flowCalibration:"Fluss-Kalibrierung",vibrationCalibration:"Vibrations-Kalibrierung",layerInspection:"Erste-Schicht-Prüfung",timelapse:"Zeitraffer",useAms:"AMS verwenden",applyChanges:"Änderungen übernehmen",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",selected:"{{count}} ausgewählt",editSelected:"Ausgewählte bearbeiten",cancelSelected:"Ausgewählte abbrechen"},confirm:{cancelTitle:"Geplanten Druck abbrechen",cancelMessage:'Möchten Sie "{{name}}" wirklich abbrechen?',stopTitle:"Druck stoppen",stopMessage:'Möchten Sie den aktuellen Druck "{{name}}" wirklich stoppen? Der Druckauftrag wird am Drucker abgebrochen.',removeTitle:"Aus Verlauf entfernen",removeMessage:'Möchten Sie "{{name}}" wirklich aus dem Warteschlangenverlauf entfernen?',clearHistoryTitle:"Verlauf löschen",clearHistoryMessage:"Möchten Sie alle {{count}} Element(e) aus dem Verlauf entfernen?",cancelButton:"Druck abbrechen",stopButton:"Druck stoppen",thisPrint:"diesen Druck",thisItem:"dieses Element"},toast:{cancelled:"Warteschlangenelement abgebrochen",cancelFailed:"Element konnte nicht abgebrochen werden",removed:"Warteschlangenelement entfernt",removeFailed:"Element konnte nicht entfernt werden",stopped:"Druck gestoppt",stopFailed:"Druck konnte nicht gestoppt werden",released:"Druck in Warteschlange freigegeben",startFailed:"Druck konnte nicht gestartet werden",reorderFailed:"Warteschlange konnte nicht neu geordnet werden",historyCleared:"{{count}} Verlaufselement(e) gelöscht",clearHistoryFailed:"Verlauf konnte nicht gelöscht werden",updateFailed:"Elemente konnten nicht aktualisiert werden",bulkCancelled:"{{count}} Element(e) abgebrochen",bulkCancelFailed:"Elemente konnten nicht abgebrochen werden"},timeline:{listView:"Liste",timelineView:"Zeitstrahl",unassigned:"Nicht zugewiesen",noData:"Keine geplanten Drucke für diesen Tag",allDoneBy:"Alle Drucke voraussichtlich fertig um {{time}}",staged:"Bereitgestellt",filterAll:"Alle anzeigen",filterPrinting:"Druckend",filterQueued:"Warteschlange",time:{anyMoment:"jeden Moment",minutesLeft:"{{minutes}}m übrig",hoursLeft:"{{hours}}h übrig",hoursMinutesLeft:"{{hours}}h {{minutes}}m übrig"},day:{previous:"Vorheriger Tag",next:"Nächster Tag",today:"Heute"}},permissions:{noStopPrint:"Sie haben keine Berechtigung, Drucke zu stoppen",noStartPrint:"Sie haben keine Berechtigung, Drucke zu starten",noEdit:"Sie haben keine Berechtigung, dieses Warteschlangenelement zu bearbeiten",noCancel:"Sie haben keine Berechtigung, dieses Warteschlangenelement abzubrechen",noRequeue:"Sie haben keine Berechtigung, Elemente erneut einzureihen",noRemove:"Sie haben keine Berechtigung, dieses Warteschlangenelement zu entfernen",noClearHistory:"Sie haben keine Berechtigung, den gesamten Verlauf zu löschen",noEditItems:"Sie haben keine Berechtigung, Warteschlangenelemente zu bearbeiten",noCancelItems:"Sie haben keine Berechtigung, Warteschlangenelemente abzubrechen"}},backgroundDispatch:{unknownFile:"Unbekannte Datei",unknownPrinter:"Unbekannter Drucker",startingPrints:"Starte Drucke",progressSummary:"{{complete}}/{{total}} abgeschlossen • Geplant: {{dispatched}} • In Bearbeitung: {{processing}}",expandDetails:"Dispatch-Details ausklappen",collapseDetails:"Dispatch-Details einklappen",dismissToast:"Dispatch-Hinweis schließen",cancelDispatchJob:"Dispatch-Job abbrechen",cancel:"Abbrechen",cancelling:"Wird abgebrochen…",status:{dispatched:"Geplant",processing:"In Bearbeitung",completed:"Abgeschlossen",failed:"Fehlgeschlagen",cancelled:"Abgebrochen"},toast:{cancellingUpload:"Upload wird abgebrochen...",cancelled:"Dispatch abgebrochen",cancelFailed:"Dispatch konnte nicht abgebrochen werden",completeWithFailures:"Background Dispatch abgeschlossen: {{completed}} erfolgreich, {{failed}} fehlgeschlagen",completeSuccess:"Background Dispatch abgeschlossen: {{completed}} erfolgreich",printStartedRemaining:"{{completed}} Druck(e) gestartet, {{remaining}} weitere werden gesendet..."}},stats:{title:"Dashboard",subtitle:"Widgets zum Neuanordnen ziehen. Auf das Augensymbol klicken zum Ausblenden.",overview:"Übersicht",totalPrints:"Gesamtdrucke",successRate:"Erfolgsrate",totalPrintTime:"Gesamtdruckzeit",printTime:"Druckzeit",totalFilament:"Gesamtverbrauch Filament",filamentUsed:"Filamentverbrauch",filamentCost:"Filamentkosten",totalCost:"Gesamtkosten",energyUsed:"Energieverbrauch",energyCost:"Energiekosten",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",users:"Authentifizierung",backup:"Sicherung",emailAuth:"E-Mail-Authentifizierung",ldap:"LDAP"},ldap:{title:"LDAP-Authentifizierung",enabledDesc:"LDAP-Authentifizierung ist aktiviert",disabledDesc:"LDAP-Authentifizierung ist deaktiviert",disabledHint:"LDAP-Einstellungen unten konfigurieren und speichern, dann aktivieren.",enabled:"LDAP-Authentifizierung aktiviert",disabled:"LDAP-Authentifizierung deaktiviert",feature1:"Benutzer können sich mit LDAP-Anmeldedaten anmelden",feature2:"Lokales Admin-Konto bleibt als Fallback erhalten",feature3:"LDAP-Gruppen werden bei der Anmeldung BamBuddy-Gruppen zugeordnet",serverConfig:"LDAP-Server-Konfiguration",serverUrl:"Server-URL",serverUrlHint:"Verwenden Sie ldap:// für Standard oder ldaps:// für SSL-Verbindungen",security:"Sicherheit",securityHint:"StartTLS aktualisiert eine einfache Verbindung auf TLS. LDAPS verwendet TLS von Anfang an.",bindDn:"Bind-DN (Dienstkonto)",bindPassword:"Bind-Passwort",searchBase:"Such-Basis-DN",userFilter:"Benutzer-Suchfilter",userFilterHint:"{username} wird durch den Anmeldenamen ersetzt. Verwenden Sie (uid={username}) für OpenLDAP.",autoProvision:"Benutzer automatisch anlegen",autoProvisionHint:"Automatisch ein BamBuddy-Konto bei der ersten LDAP-Anmeldung erstellen",defaultGroup:"Standardgruppe",defaultGroupNone:"— Keine (kein Fallback) —",defaultGroupHint:"Fallback-Gruppe, die zugewiesen wird, wenn sich ein LDAP-Benutzer authentifiziert, aber in keiner zugeordneten LDAP-Gruppe enthalten ist. Leer lassen, um nicht zugeordnete Benutzer ohne Berechtigungen zu belassen.",groupMapping:"Gruppenzuordnung (JSON)",groupMappingHint:"LDAP-Gruppen-DNs BamBuddy-Gruppen zuordnen. Verfügbare Gruppen: ",testConnection:"Verbindung testen",settingsSaved:"LDAP-Einstellungen gespeichert",errors:{serverRequired:"LDAP-Server-URL ist erforderlich",searchBaseRequired:"Such-Basis-DN ist erforderlich",enableAuthFirst:"Authentifizierung zuerst aktivieren",configureLdapFirst:"LDAP-Einstellungen zuerst speichern"}},email:{smtpSettings:"SMTP-Konfiguration",smtpHost:"SMTP-Server",smtpPort:"SMTP-Port",security:"Sicherheit",authentication:"Authentifizierung",username:"Benutzername",password:"Passwort",fromEmail:"Absender-E-Mail",fromName:"Absendername",testConnection:"SMTP-Verbindung testen",testRecipient:"Test-Empfänger-E-Mail",sendTest:"Test-E-Mail senden",sending:"Wird gesendet...",save:"Einstellungen speichern",saving:"Wird gespeichert...",advancedAuth:"Erweiterte Authentifizierung",advancedAuthEnabled:"Erweiterte Authentifizierung ist aktiviert",advancedAuthEnabledDesc:"E-Mail-basierte Benutzerverwaltungsfunktionen sind aktiv. Neue Benutzer erhalten automatisch generierte Passwörter per E-Mail und können ihr Passwort über die Passwort vergessen Funktion zurücksetzen.",advancedAuthDisabled:"Erweiterte Authentifizierung ist deaktiviert",advancedAuthDisabledDesc:"Aktivieren Sie die erweiterte Authentifizierung, um E-Mail-basierte Funktionen für die Benutzerverwaltung zu aktivieren.",enable:"Aktivieren",disable:"Deaktivieren",feature1:"Passwörter werden automatisch generiert und an neue Benutzer gesendet",feature2:"Benutzer können sich mit Benutzername oder E-Mail anmelden",feature3:"Passwort vergessen Funktion ist verfügbar",feature4:"Administratoren können Benutzerpasswörter per E-Mail zurücksetzen",errors:{requiredFields:"Bitte füllen Sie alle Pflichtfelder aus",usernameRequired:"Benutzername ist erforderlich, wenn Authentifizierung aktiviert ist",enterTestEmail:"Bitte geben Sie eine Test-E-Mail-Adresse ein",smtpServerAndEmail:"Bitte füllen Sie SMTP-Server und Absender-E-Mail aus, bevor Sie testen",usernamePasswordRequired:"Benutzername und Passwort sind erforderlich, wenn Authentifizierung aktiviert ist",configureSmtpFirst:"Bitte konfigurieren und testen Sie zuerst die SMTP-Einstellungen",enableAuthFirst:"Bitte aktivieren Sie zuerst die Authentifizierung, um E-Mail-basierte Funktionen nutzen zu können."},success:{settingsSaved:"SMTP-Einstellungen erfolgreich gespeichert"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"Keine (Port 25)"},authOptions:{enabled:"Aktiviert",disabled:"Deaktiviert"}},appearance:"Erscheinungsbild",notifications:"Benachrichtigungen",smartPlugs:"Smart Plugs",spoolman:"Spoolman",updates:"Updates",language:"Sprache",languageDescription:"Wählen Sie Ihre bevorzugte Sprache",theme:"Design",themeLight:"Hell",themeDark:"Dunkel",themeSystem:"System",defaultView:"Standardansicht",defaultViewDescription:"Seite, die beim Öffnen der App angezeigt wird",checkForUpdates:"Nach Updates suchen",autoUpdate:"Automatische Updates",currentVersion:"Aktuelle Version",latestVersion:"Neueste Version",upToDate:"Sie sind auf dem neuesten Stand",updateAvailable:"Update verfügbar",notificationLanguage:"Benachrichtigungssprache",notificationLanguageDescription:"Sprache für Push-Benachrichtigungen",bedCooledThreshold:"Bett-Abkühlung Schwellenwert",bedCooledThresholdDescription:"Temperatur, unter der das Bett nach einem Druck als abgekühlt gilt",userNotificationsEnabled:"Benutzerbenachrichtigungen",userNotificationsEnabledDescription:"Aktiviert das Benutzerbenachrichtigungsmenü und E-Mail-Benachrichtigungen für Druckereignisse. Erfordert Erweiterte Authentifizierung.",userNotificationsDisabledHint:"Erweiterte Authentifizierung aktivieren, um Benutzerbenachrichtigungen zu verwenden.",notificationProviders:"Benachrichtigungsanbieter",addProvider:"Anbieter hinzufügen",editProvider:"Anbieter bearbeiten",providerType:"Anbietertyp",testNotification:"Testbenachrichtigung",testSuccess:"Testbenachrichtigung erfolgreich gesendet",testFailed:"Testbenachrichtigung konnte nicht gesendet werden",quietHours:"Ruhezeiten",quietHoursDescription:"Keine Störungen während dieser Zeiten",quietHoursStart:"Beginn",quietHoursEnd:"Ende",events:{title:"Benachrichtigungsereignisse",printStart:"Druck gestartet",printComplete:"Druck abgeschlossen",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",printProgress:"Fortschrittsmeldungen",printProgressDescription:"Bei 25%, 50%, 75% benachrichtigen",printerOffline:"Drucker offline",printerError:"Druckerfehler",filamentLow:"Filament niedrig",maintenanceDue:"Wartung fällig",maintenanceDueDescription:"Benachrichtigen, wenn Wartung erforderlich"},smartPlug:{title:"Smart Plugs",add:"Smart Plug hinzufügen",edit:"Smart Plug bearbeiten",name:"Name",ipAddress:"IP-Adresse",linkedPrinter:"Verknüpfter Drucker",autoOn:"Automatisch einschalten",autoOnDescription:"Einschalten beim Druckstart",autoOff:"Automatisch ausschalten",autoOffDescription:"Ausschalten nach Druckende",offDelay:"Ausschaltverzögerung",offDelayMinutes:"Minuten nach Druck",offDelayTemp:"Wenn Düse unter Temperatur",currentState:"Aktueller Status",turnOn:"Einschalten",turnOff:"Ausschalten"},filamentTracking:"Filament-Verfolgung",filamentTrackingDesc:"Wählen Sie, wie Sie Ihre Filamentspulen verfolgen möchten. Sie können das integrierte Inventar oder einen externen Spoolman-Server verwenden.",filamentChecks:"Filament-Prüfungen",disableFilamentWarnings:"Filament-Warnungen deaktivieren",disableFilamentWarningsDesc:"Keine Warnungen über unzureichendes Filament beim Drucken oder Einreihen anzeigen",preferLowestFilament:"Niedrigsten Filamentrest bevorzugen",preferLowestFilamentDesc:"Bei mehreren passenden Spulen die mit dem geringsten Restfilament verwenden",trackingModeBuiltIn:"Integriertes Inventar",trackingModeBuiltInDesc:"RFID-Erkennung und Verbrauchserfassung inklusive",trackingModeSpoolmanDesc:"Externer Filament-Management-Server",builtInFeatureRfid:"Erkennt automatisch Bambu Lab RFID-Spulen im AMS",builtInFeatureUsage:"Erfasst den Filamentverbrauch pro Druck",builtInFeatureCatalog:"Spulen, Farben und K-Faktor-Profile verwalten",builtInFeatureThirdParty:"Drittanbieter-Spulen können Inventarspulen zugewiesen werden",amsSyncButton:"Gewichte vom AMS synchronisieren",amsSyncTitle:"Spulengewichte vom AMS synchronisieren",amsSyncMessage:"Alle Inventar-Spulengewichte werden mit den aktuellen AMS-Restwerten der verbundenen Drucker überschrieben. Verwenden Sie dies zur Wiederherstellung beschädigter Gewichtsdaten. Drucker müssen online sein.",amsSyncing:"Synchronisiere...",amsSyncSuccess:"{{synced}} Spule(n) synchronisiert, {{skipped}} übersprungen",amsSyncError:"Synchronisierung der Gewichte vom AMS fehlgeschlagen",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL Ihres Spoolman-Servers (z.B. http://localhost:7912)",spoolmanConnected:"Verbunden",spoolmanDisconnected:"Nicht verbunden",status:"Status",connect:"Verbinden",disconnect:"Trennen",howSyncWorks:"So funktioniert die Synchronisierung",syncInfoRfidOnly:"Nur offizielle Bambu Lab Spulen mit RFID werden synchronisiert",syncInfoAutoCreate:"Neue Spulen werden bei der ersten Synchronisierung automatisch in Spoolman erstellt",syncInfoThirdPartySkipped:"Nicht-Bambu-Lab-Spulen (Drittanbieter, nachgefüllt) werden übersprungen",linkingExistingSpools:"Vorhandene Spulen verknüpfen",linkingExistingSpoolsDesc:'Um vorhandene Spoolman-Spulen mit Ihrem AMS zu verknüpfen, fahren Sie über einen AMS-Slot und klicken Sie auf "Mit Spoolman verknüpfen".',syncMode:"Synchronisierungsmodus",syncModeAuto:"Automatisch",syncModeManual:"Nur manuell",syncModeAutoDesc:"AMS-Daten werden automatisch synchronisiert, wenn Änderungen erkannt werden",syncModeManualDesc:"Nur bei manueller Auslösung synchronisieren",syncAmsData:"AMS-Daten synchronisieren",syncAmsDataDesc:"AMS-Daten des Druckers manuell mit Spoolman synchronisieren",allPrinters:"Alle Drucker",noDefaultPrinter:"Kein Standard (jedes Mal fragen)",sidebarOrder:"Seitenleisten-Reihenfolge",saveThumbnails:"Vorschaubilder speichern",captureFinishPhoto:"Abschlussfoto aufnehmen",noPrintersConfigured:"Keine Drucker konfiguriert",archiveMode:{always:"Immer Archiveintrag erstellen",never:"Nie Archiveintrag erstellen",ask:"Jedes Mal fragen"},checkForUpdatesLabel:"Nach Updates suchen",checkPrinterFirmware:"Drucker-Firmware prüfen",includeBetaUpdates:"Beta-Versionen einschließen",includeBetaUpdatesDesc:"Über Beta- und Vorabversionen bei der Updateprüfung benachrichtigen",enableRetry:"Wiederholung aktivieren",homeAssistantDescription:"Smart Plugs über Home Assistant steuern",environmentManagedLabel:"(Umgebungsvariable)",autoEnabledViaEnv:"Automatisch über Umgebungsvariablen aktiviert",urlFromEnvReadOnly:"Wert wird über HA_URL Umgebungsvariable gesetzt (schreibgeschützt)",tokenFromEnvReadOnly:"Wert wird über HA_TOKEN Umgebungsvariable gesetzt (schreibgeschützt)",mqttConnectedTo:"Verbunden mit",prometheusDescription:"Druckerdaten im Prometheus-Format bereitstellen",noSmartPlugsTitle:"Keine Smart Plugs konfiguriert",noSmartPlugsDescription:"Fügen Sie einen Tasmota-basierten Smart Plug hinzu, um den Energieverbrauch zu verfolgen und die Stromsteuerung zu automatisieren.",noProvidersTitle:"Keine Anbieter konfiguriert",noProvidersDescription:"Fügen Sie einen Anbieter hinzu, um Benachrichtigungen zu erhalten.",noTemplatesAvailable:"Keine Vorlagen verfügbar. Starten Sie das Backend neu, um Standardvorlagen zu laden.",apiPermissionView:"Druckerstatus und Warteschlange anzeigen",apiPermissionEdit:"Elemente zur Druckwarteschlange hinzufügen und entfernen",apiKeysEmptyTitle:"Keine API-Schlüssel",apiKeysEmptyDescription:"Erstellen Sie einen API-Schlüssel zur Integration mit externen Diensten.",noUsersFound:"Keine Benutzer gefunden",noGroupsFound:"Keine Gruppen gefunden",noGroupsAvailable:"Keine Gruppen verfügbar",passwordsDoNotMatch:"Passwörter stimmen nicht überein",systemGroupWarning:"System-Gruppennamen können nicht geändert werden",authDisabledTitle:"Authentifizierung ist deaktiviert",authDisabledFeature1:"Anmeldung zum Zugriff auf das System erforderlich",authDisabledFeature2:"Mehrere Benutzer mit gruppenbasierten Berechtigungen erstellen",authDisabledFeature3:"Zugriff mit über 50 granularen Berechtigungen steuern",userHasCreated:"Dieser Benutzer hat erstellt:",userItemsQuestion:"Was möchten Sie mit diesen Elementen tun?",deleteUserConfirm:"Möchten Sie diesen Benutzer wirklich löschen?",actionCannotBeUndone:"Diese Aktion kann nicht rückgängig gemacht werden.",addFirstSmartPlug:"Ersten Smart Plug hinzufügen",providers:"Anbieter",log:"Protokoll",testAll:"Alle testen",testResults:"Testergebnisse",testPassedCount:"{{count}} bestanden",testFailedCount:"{{count}} fehlgeschlagen",messageTemplates:"Nachrichtenvorlagen",messageTemplatesDescription:"Passen Sie Benachrichtigungen für jedes Ereignis an.",apiKeys:"API-Schlüssel",apiKeysDescription:"Erstellen Sie API-Schlüssel für externe Integrationen und Webhooks.",createKey:"Schlüssel erstellen",apiKeyCreated:"API-Schlüssel erfolgreich erstellt",apiKeyCopyWarning:"Kopieren Sie diesen Schlüssel jetzt - er wird nicht mehr angezeigt!",useInApiBrowser:"Im API-Browser verwenden",createNewApiKey:"Neuen API-Schlüssel erstellen",keyName:"Schlüsselname",keyNamePlaceholder:"z.B. Home Assistant, OctoPrint",readStatus:"Status lesen",readStatusDescription:"Druckerstatus und Warteschlange anzeigen",manageQueue:"Warteschlange verwalten",manageQueueDescription:"Elemente zur Druckwarteschlange hinzufügen und entfernen",controlPrinter:"Drucker steuern",controlPrinterDescription:"Drucke pausieren, fortsetzen und stoppen",unnamedKey:"Unbenannter Schlüssel",lastUsed:"Zuletzt verwendet",read:"Lesen",control:"Steuern",createFirstKey:"Ersten Schlüssel erstellen",webhookEndpoints:"Webhook-Endpunkte",webhookApiKeyHint:"Verwenden Sie Ihren API-Schlüssel im X-API-Key-Header.",webhook:{getAllStatus:"Alle Druckerstatus abrufen",getSpecificStatus:"Spezifischen Druckerstatus abrufen",addToQueue:"Zur Druckwarteschlange hinzufügen",pausePrint:"Druck pausieren",resumePrint:"Druck fortsetzen",stopPrint:"Druck stoppen"},apiBrowser:"API-Browser",apiBrowserDescription:"Erkunden und testen Sie alle verfügbaren API-Endpunkte.",apiKeyForTesting:"API-Schlüssel zum Testen",apiKeyPlaceholder:"Fügen Sie hier Ihren API-Schlüssel ein, um authentifizierte Endpunkte zu testen...",apiKeyHint:"Dieser Schlüssel wird als X-API-Key-Header mit Anfragen gesendet.",deleteApiKeyTitle:"API-Schlüssel löschen",deleteApiKeyMessage:"Möchten Sie diesen API-Schlüssel wirklich löschen? Alle Integrationen, die diesen Schlüssel verwenden, funktionieren nicht mehr.",deleteKey:"Schlüssel löschen",amsDisplayThresholds:"AMS-Anzeigeschwellenwerte",amsThresholdsDescription:"Konfigurieren Sie Farbschwellenwerte für AMS-Feuchtigkeits- und Temperaturanzeigen.",humidity:"Luftfeuchtigkeit",goodGreen:"Gut (grün)",fairOrange:"Mittel (orange)",aboveFairBad:"Über dem mittleren Schwellenwert wird rot angezeigt (schlecht)",fairAlsoDryingThreshold:"Dieser Schwellenwert wird auch für die automatische Trocknung verwendet",temperature:"Temperatur",goodBlue:"Gut (blau)",aboveFairHot:"Über dem mittleren Schwellenwert wird rot angezeigt (heiß)",historyRetention:"Verlaufsaufbewahrung",keepSensorHistory:"Sensorverlauf behalten für",historyRetentionDescription:"Ältere Feuchtigkeits- und Temperaturdaten werden automatisch gelöscht",defaultPrintOptions:"Standard-Druckoptionen",defaultPrintOptionsDescription:"Standardwerte für Druckoptionen bei neuen Drucken festlegen. Diese können im Druckdialog pro Druck überschrieben werden.",defaultBedLevelling:"Bett-Nivellierung",defaultBedLevellingDesc:"Bett vor dem Druck automatisch nivellieren",defaultFlowCali:"Fluss-Kalibrierung",defaultFlowCaliDesc:"Extrusionsfluss kalibrieren",defaultVibrationCali:"Vibrationskalibrierung",defaultVibrationCaliDesc:"Ringing-Artefakte reduzieren",defaultLayerInspect:"Erste-Schicht-Inspektion",defaultLayerInspectDesc:"KI-Inspektion der ersten Schicht",defaultTimelapse:"Zeitraffer",defaultTimelapseDesc:"Zeitraffervideo aufnehmen",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Druckplatte-Bestätigung",requirePlateClear:"Druckplatte-Bestätigung erforderlich",requirePlateClearDescription:"Wenn aktiviert, wartet der Scheduler auf eine Druckplatte-Bestätigung pro Drucker, bevor geplante Drucke auf Druckern mit abgeschlossenen Aufträgen gestartet werden. Deaktivieren Sie dies für Farm-Workflows, bei denen die Platten physisch überprüft werden.",gcodeInjection:"G-code Injection",gcodeInjectionDescription:'Konfigurieren Sie benutzerdefinierten G-code, der am Anfang und/oder Ende von Drucken für Auto-Print-Systeme wie Farmloop, SwapMod, AutoClear und Printflow 3D eingefügt wird. Snippets werden pro Druckermodell konfiguriert und angewendet, wenn "G-code einfügen" bei einem Warteschlangen-Element aktiviert ist.',gcodeInjectionNoPrinters:"Keine Drucker gefunden. Fügen Sie Drucker hinzu, um G-code-Snippets zu konfigurieren.",gcodeStartLabel:"Start G-code",gcodeEndLabel:"End G-code",gcodeStartPlaceholder:"G-code, der vor dem Druckstart eingefügt wird...",gcodeEndPlaceholder:"G-code, der nach dem Druckende angefügt wird...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Automatische Trocknung",queueDryingDescription:"AMS-Filament automatisch trocknen, wenn der Drucker zwischen Warteschlangen-Drucken im Leerlauf ist. Verwendet den Feuchtigkeitsschwellenwert oben.",queueDryingEnabled:"Automatische Trocknung aktivieren",queueDryingEnabledDescription:"AMS-Trocknung automatisch starten, wenn der Drucker im Leerlauf ist und die Feuchtigkeit über dem Schwellenwert liegt",queueDryingBlock:"Auf Trocknung warten",queueDryingBlockDescription:"Druckwarteschlange blockieren, bis die Trocknung abgeschlossen ist. Wenn aus, haben Drucke Vorrang.",ambientDryingEnabled:"Umgebungstrocknung",ambientDryingEnabledDescription:"Filament auf inaktiven Druckern automatisch trocknen, wenn die Luftfeuchtigkeit den Schwellenwert überschreitet — auch ohne Warteschlange.",dryingPresets:"Trocknungsvoreinstellungen",dryingPresetsDescription:"Temperatur und Dauer pro Filamenttyp. AMS 2 Pro verwendet niedrigere Temperaturen, AMS-HT unterstützt höhere.",dryingFilament:"Filament",printModal:"Druckdialog",expandCustomMapping:"Benutzerdefinierte Zuordnung standardmäßig erweitern",expandCustomMappingDescription:"Bei Druck auf mehrere Drucker die AMS-Zuordnung pro Drucker erweitert anzeigen",authentication:"Authentifizierung",authEnabledDescription:"Ihre Instanz ist mit Benutzerauthentifizierung gesichert",authDisabledDescription:"Aktivieren Sie die Anmeldepflicht und verwalten Sie den Benutzerzugriff",authDisabledMessage:"Aktivieren Sie die Authentifizierung, um Benutzerkonten zu erstellen, Berechtigungen zu verwalten und Ihre Bambuddy-Instanz zu sichern.",enableAuthentication:"Authentifizierung aktivieren",currentUser:"Aktueller Benutzer",changePassword:"Passwort ändern",admin:"Admin",users:"Benutzer",addUser:"Benutzer hinzufügen",groups:"Gruppen",addGroup:"Gruppe hinzufügen",system:"System",noDescription:"Keine Beschreibung",userCount:"{{count}} Benutzer",permissionCount:"{{count}} Berechtigungen",createUser:"Benutzer erstellen",username:"Benutzername",enterUsername:"Benutzername eingeben",password:"Passwort",enterPassword:"Passwort eingeben (min. 6 Zeichen)",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Passwort bestätigen",viewReleaseOnGitHub:"Release auf GitHub anzeigen",turnAllPlugsOn:"Alle Stecker einschalten",turnAllPlugsOff:"Alle Stecker ausschalten",clearNotificationLogs:"Benachrichtigungsprotokolle löschen",clearLogsMessage:"Dadurch werden alle Benachrichtigungsprotokolle, die älter als 30 Tage sind, dauerhaft gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.",clearLogs:"Protokolle löschen",resetUiPreferences:"UI-Einstellungen zurücksetzen",resetUiPreferencesMessage:"Dadurch werden alle UI-Einstellungen auf Standardwerte zurückgesetzt: Seitenleisten-Reihenfolge, Theme, Dashboard-Layout, Ansichtsmodi und Sortiereinstellungen. Ihre Drucker, Archive und Servereinstellungen werden NICHT beeinträchtigt. Die Seite wird nach dem Löschen neu geladen.",resetPreferences:"Einstellungen zurücksetzen",deleteGroupTitle:"Gruppe löschen",deleteGroupMessage:"Möchten Sie diese Gruppe wirklich löschen? Benutzer in dieser Gruppe verlieren diese Berechtigungen.",deleteGroup:"Gruppe löschen",disableAuthenticationTitle:"Authentifizierung deaktivieren",disableAuthenticationMessage:"Möchten Sie die Authentifizierung wirklich deaktivieren? Dadurch wird Ihre Bambuddy-Instanz ohne Anmeldung zugänglich. Alle Benutzer bleiben in der Datenbank, aber die Authentifizierung wird deaktiviert.",disableAuthentication:"Authentifizierung deaktivieren",configureBambuddy:"Bambuddy konfigurieren",systemDefault:"Systemstandard",archiveSettings:"Archiv-Einstellungen",newWindow:"Neues Fenster",embeddedOverlay:"Eingebettetes Overlay",preferredSlicer:"Bevorzugter Slicer",preferredSlicerDescription:"Wähle die Slicer-Anwendung zum Öffnen von Dateien",externalCameras:"Externe Kameras",costTracking:"Kostenverfolgung",printsOnly:"Nur Drucke",totalConsumption:"Gesamtverbrauch",dataManagement:"Datenverwaltung",storageUsage:"Speichernutzung",storageUsageDescription:"Aufschlüsselung der Datennutzung nach Kategorie",storageUsageTotal:"Gesamt",storageUsageErrors:"Fehler",storageUsageOtherBreakdown:"Sonstiges (enthält statische Assets, Skripte und Konfigurationsdateien)",storageUsageSystem:"System",storageUsageData:"Daten",storageUsageUnavailable:"Speichernutzungsinformationen nicht verfügbar",clearNotificationLogsDescription:"Benachrichtigungsprotokolle älter als 30 Tage löschen",resetUiPreferencesDescription:"Seitenleisten-Reihenfolge, Theme, Ansichtsmodi und Layout-Einstellungen zurücksetzen. Drucker, Archive und Einstellungen werden nicht beeinflusst.",enableHomeAssistant:"Home Assistant aktivieren",enableMqtt:"MQTT aktivieren",useTls:"TLS verwenden",enableMetricsEndpoint:"Metrik-Endpunkt aktivieren",availableMetrics:"Verfügbare Metriken",editUser:"Benutzer bearbeiten",deleteUserTitle:"Benutzer löschen",groupName:"Gruppenname",leaveEmptyForAnonymous:"Leer lassen für anonym",leaveEmptyForNoAuth:"Leer lassen für keine Authentifizierung",enterNewPassword:"Neues Passwort eingeben",confirmNewPassword:"Neues Passwort bestätigen",enterGroupName:"Gruppenname eingeben",enterDescriptionOptional:"Beschreibung eingeben (optional)",enterCurrentPassword:"Aktuelles Passwort eingeben",enterNewPasswordMin6:"Neues Passwort eingeben (min. 6 Zeichen)",toast:{keyCopied:"Schlüssel in Zwischenablage kopiert",copyFailed:"Schlüssel konnte nicht kopiert werden",keyAddedToBrowser:"Schlüssel zum API-Browser hinzugefügt",clearLogsFailed:"Protokolle konnten nicht gelöscht werden",uiPreferencesReset:"UI-Einstellungen zurückgesetzt. Wird neu geladen...",authDisabled:"Authentifizierung erfolgreich deaktiviert",authDisableFailed:"Authentifizierung konnte nicht deaktiviert werden",apiKeyCreated:"API-Schlüssel erstellt",apiKeyDeleted:"API-Schlüssel gelöscht",userCreated:"Benutzer erfolgreich erstellt",userUpdated:"Benutzer erfolgreich aktualisiert",userDeleted:"Benutzer erfolgreich gelöscht",groupCreated:"Gruppe erfolgreich erstellt",groupUpdated:"Gruppe erfolgreich aktualisiert",groupDeleted:"Gruppe erfolgreich gelöscht",fillRequiredFields:"Bitte füllen Sie alle erforderlichen Felder aus",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein",enterGroupName:"Bitte geben Sie einen Gruppennamen ein",settingsSaved:"Einstellungen gespeichert",cameraSettingsSaved:"Kamera-Einstellungen gespeichert",enterCameraUrl:"Bitte geben Sie eine Kamera-URL ein",passwordChanged:"Passwort erfolgreich geändert",connectionFailed:"Verbindung fehlgeschlagen",testFailed:"Test fehlgeschlagen",cameraConnected:"Kamera verbunden{{resolution}}"},testConnection:"Verbindung testen",catalog:{spoolCatalog:"Spulenkatalog",spoolCatalogDescription:"Leerspulengewichte nach Marke/Typ. Wird für die automatische Gewichtssuche beim Hinzufügen von Spulen verwendet.",searchCatalog:"Katalog durchsuchen...",addNewEntry:"Neuen Eintrag hinzufügen",namePlaceholder:"Name (z.B. Bambu Lab - Plastik)",weight:"Gewicht",type:"Typ",default:"Standard",custom:"Benutzerdefiniert",noMatch:"Keine Einträge entsprechen Ihrer Suche",empty:"Keine Einträge im Katalog",deleteEntry:"Eintrag löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',resetCatalog:"Katalog zurücksetzen",resetConfirm:"Katalog auf Standardwerte zurücksetzen? Alle benutzerdefinierten Einträge werden entfernt.",loadFailed:"Spulenkatalog konnte nicht geladen werden",nameWeightRequired:"Name und Gewicht sind erforderlich",entryAdded:"Eintrag hinzugefügt",addFailed:"Eintrag konnte nicht hinzugefügt werden",entryUpdated:"Eintrag aktualisiert",updateFailed:"Eintrag konnte nicht aktualisiert werden",entryDeleted:"Eintrag gelöscht",deleteFailed:"Eintrag konnte nicht gelöscht werden",resetSuccess:"Katalog auf Standardwerte zurückgesetzt",resetFailed:"Katalog konnte nicht zurückgesetzt werden",exported:"{{count}} Einträge exportiert",imported:"{{added}} Einträge importiert ({{skipped}} übersprungen)",importFailed:"Import fehlgeschlagen: ungültiges JSON-Format",exportTooltip:"Katalog als JSON exportieren",importTooltip:"Katalog aus JSON importieren",resetTooltip:"Auf Standardwerte zurücksetzen",selectedCount:"{{count}} ausgewählt",deleteSelected:"Ausgewählte löschen",bulkDeleteConfirm:"Möchten Sie {{count}} Einträge wirklich löschen?",bulkDeleted:"{{count}} Einträge gelöscht",bulkDeleteFailed:"Fehler beim Löschen der Einträge"},colorCatalog:{title:"Farbkatalog",description:"Filamentfarben nach Hersteller/Material. Wird für die automatische Farbsuche beim Hinzufügen von Spulen verwendet.",searchColors:"Farben durchsuchen...",allManufacturers:"Alle Hersteller",addNewColor:"Neue Farbe hinzufügen",manufacturer:"Hersteller",colorName:"Farbname",hex:"Hex",materialOptional:"Material (optional)",showing:"{{filtered}} von {{total}} Farben angezeigt",noMatch:"Keine Farben entsprechen Ihrer Suche",empty:"Keine Farben im Katalog",deleteColor:"Farbe löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',resetCatalog:"Farbkatalog zurücksetzen",resetConfirm:"Katalog auf Standardwerte zurücksetzen? Alle benutzerdefinierten Farben werden entfernt.",sync:"Sync",starting:"Starten...",syncTooltip:"Von FilamentColors.xyz synchronisieren (2000+ Farben)",loadFailed:"Farbkatalog konnte nicht geladen werden",fieldsRequired:"Hersteller, Farbname und Hex-Farbe sind erforderlich",colorAdded:"Farbe hinzugefügt",addFailed:"Farbe konnte nicht hinzugefügt werden",colorUpdated:"Farbe aktualisiert",updateFailed:"Farbe konnte nicht aktualisiert werden",colorDeleted:"Farbe gelöscht",deleteFailed:"Farbe konnte nicht gelöscht werden",resetSuccess:"Farbkatalog auf Standardwerte zurückgesetzt",resetFailed:"Katalog konnte nicht zurückgesetzt werden",syncUpToDate:"Bereits aktuell ({{count}} Farben geprüft)",syncComplete:"{{added}} neue Farben hinzugefügt ({{skipped}} bereits vorhanden)",syncError:"Sync-Fehler",syncFailed:"Synchronisierung von FilamentColors.xyz fehlgeschlagen",exported:"{{count}} Farben exportiert",imported:"{{added}} Farben importiert ({{skipped}} übersprungen)",importFailed:"Import fehlgeschlagen: ungültiges JSON-Format",selectedCount:"{{count}} ausgewählt",deleteSelected:"Ausgewählte löschen",bulkDeleteConfirm:"Möchten Sie {{count}} Farben wirklich löschen?",bulkDeleted:"{{count}} Farben gelöscht",bulkDeleteFailed:"Fehler beim Löschen der Farben"},dateFormat:"Datumsformat",dateFormatUs:"US (MM/TT/JJJJ)",dateFormatEu:"EU (TT/MM/JJJJ)",dateFormatIso:"ISO (JJJJ-MM-TT)",timeFormat:"Zeitformat",timeFormat12:"12-Stunden (3:30 PM)",timeFormat24:"24-Stunden (15:30)",defaultPrinter:"Standarddrucker",defaultPrinterDescription:"Diesen Drucker für Uploads, Nachdrucke und andere Vorgänge vorauswählen.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Elemente in der Seitenleiste per Drag & Drop neu anordnen. Hier auf Standardreihenfolge zurücksetzen.",setDefault:"Standard setzen",sidebarOrderSetDefaultHint:"Standard setzen übernimmt die aktuelle Menüreihenfolge für Benutzer, die ihre noch nicht angepasst haben.",sidebarDefaultSet:"Standard-Menüreihenfolge wurde festgelegt.",sidebarDefaultCleared:"Standard-Menüreihenfolge gelöscht.",sidebarDefaultFailed:"Festlegen der Standard-Menüreihenfolge fehlgeschlagen.",reset:"Zurücksetzen",darkMode:"Dunkelmodus",lightMode:"Hellmodus",active:"(aktiv)",background:"Hintergrund",accent:"Akzent",style:"Stil",bgNeutral:"Neutral",bgWarm:"Warm",bgCool:"Kühl",bgOled:"OLED Schwarz",bgSlate:"Schieferblau",bgForest:"Waldgrün",accentGreen:"Grün",accentTeal:"Türkis",accentBlue:"Blau",accentOrange:"Orange",accentPurple:"Lila",accentRed:"Rot",styleClassic:"Klassisch",styleGlow:"Leuchtend",styleVibrant:"Lebendig",themeToggleHint:"Zwischen Hell- und Dunkelmodus mit dem Sonnen-/Mondsymbol in der Seitenleiste wechseln.",autoArchivePrints:"Drucke automatisch archivieren",autoArchiveDescription:"3MF-Dateien automatisch speichern, wenn Drucke abgeschlossen sind",saveThumbnailsDescription:"Vorschaubilder aus 3MF-Dateien extrahieren und speichern",captureFinishPhotoDescription:"Foto von der Druckerkamera aufnehmen, wenn der Druck abgeschlossen ist",ffmpegNotInstalled:"ffmpeg nicht installiert",ffmpegRequired:"Kameraaufnahme benötigt ffmpeg. Installieren über <brew>brew install ffmpeg</brew> (macOS) oder <apt>apt install ffmpeg</apt> (Linux).",camera:"Kamera",cameraViewMode:"Kamera-Ansichtsmodus",cameraOverlayDescription:"Kamera öffnet sich als größenveränderbares Overlay auf dem Hauptbildschirm",cameraWindowDescription:"Kamera öffnet sich in einem separaten Browserfenster",externalCamerasDescription:"Externe Kameras konfigurieren, um die eingebaute Druckerkamera zu ersetzen. Unterstützt MJPEG-Streams, RTSP, HTTP-Snapshots und USB-Kameras (V4L2). Wenn aktiviert, wird die externe Kamera für Live-Ansicht und Abschlussfotos verwendet.",cameraPlaceholderUsb:"Gerätepfad (/dev/video0)",cameraPlaceholderUrl:"Kamera-URL (rtsp://... oder http://...)",cameraTypeMjpeg:"MJPEG-Stream",cameraTypeRtsp:"RTSP-Stream",cameraTypeSnapshot:"HTTP-Snapshot",cameraTypeUsb:"USB-Kamera (V4L2)",cameraRotation:"Drehung",test:"Testen",connected:"Verbunden",disconnected:"Getrennt",currency:"Währung",defaultFilamentCost:"Standard-Filamentkosten (pro kg)",electricityCost:"Stromkosten pro kWh",energyDisplayMode:"Energieanzeige-Modus",energyModePrintDescription:"Dashboard zeigt Summe der während Drucken verbrauchten Energie",energyModeTotalDescription:"Dashboard zeigt Gesamtenergie der Smart Plugs",fileManager:"Dateimanager",createArchiveEntry:"Archiveintrag beim Drucken erstellen",createArchiveEntryDescription:"Beim Drucken aus dem Dateimanager optional einen Archiveintrag erstellen",lowDiskSpaceWarning:"Warnung bei wenig Speicherplatz",lowDiskSpaceDescription:"Warnung anzeigen, wenn freier Speicherplatz unter diesen Schwellenwert fällt",printerFirmware:"Drucker-Firmware",checkFirmwareDescription:"Nach Firmware-Updates von Bambu Lab suchen",bambuddySoftware:"Bambuddy Software",autoCheckDescription:"Automatisch beim Start nach neuen Versionen suchen",checkNow:"Jetzt prüfen",updateAvailableVersion:"Update verfügbar: v{{version}}",releaseNotes:"Versionshinweise",updateViaDocker:"Update über Docker Compose:",installUpdate:"Update installieren",latestVersionRunning:"Sie verwenden die neueste Version",failedToCheckUpdates:"Update-Prüfung fehlgeschlagen: {{error}}",backupRestore:"Sicherung & Wiederherstellung",backupRestoreDescription:"Einstellungen exportieren/importieren und GitHub-Backup konfigurieren",goToBackup:"Zur Sicherung",externalUrl:"Externe URL",externalUrlDescription:"Die externe URL, unter der Bambuddy erreichbar ist. Wird für Benachrichtigungsbilder und externe Integrationen verwendet.",bambuddyUrl:"Bambuddy-URL",externalUrlHint:"Protokoll und Port angeben (z.B. http://192.168.1.100:8000)",ftpRetry:"FTP-Wiederholung",ftpRetryDescription:"FTP-Operationen bei unzuverlässigem Drucker-WLAN wiederholen. Gilt für 3MF-Downloads, Druck-Uploads, Zeitraffer-Downloads und Firmware-Updates.",autoRetryDescription:"Fehlgeschlagene FTP-Operationen automatisch wiederholen",retryAttempts:"Wiederholungsversuche",retryDelay:"Wiederholungsverzögerung",connectionTimeout:"Verbindungs-Timeout",time_one:"{{count}} Mal",time_other:"{{count}} Mal",second_one:"{{count}} Sekunde",second_other:"{{count}} Sekunden",nSeconds:"{{count}} Sekunden",increaseForWeakWifi:"Erhöhen für Drucker mit schwachem WLAN",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Mit Home Assistant verbinden, um Smart Plugs über die HA REST-API zu steuern. Unterstützt Switch-, Light-, Input_Boolean- und Script-Entitäten.",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"Langlebiges Zugriffstoken",haTokenHint:"Token in HA erstellen: Profil → Langlebige Zugriffstoken → Token erstellen",connectionSuccessful:"Verbindung erfolgreich",connectionFailed:"Verbindung fehlgeschlagen",haConnectionSuccess:"Erfolgreich mit Home Assistant verbunden.",haConnectionFailed:"Verbindung zu Home Assistant fehlgeschlagen.",mqttPublishing:"MQTT-Veröffentlichung",mqttDescription:"BamBuddy-Ereignisse an einen externen MQTT-Broker zur Integration mit Node-RED, Home Assistant und anderen Automatisierungssystemen veröffentlichen.",mqttEnableDescription:"Ereignisse an externen MQTT-Broker veröffentlichen",brokerHostname:"Broker-Hostname",port:"Port",usernameOptional:"Benutzername (optional)",passwordOptional:"Passwort (optional)",topicPrefix:"Topic-Präfix",topicPrefixHint:"Topics werden sein: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Prometheus-Metriken",prometheusEndpointDescription:"Druckermetriken unter <code>/api/v1/metrics</code> für Prometheus/Grafana-Überwachung bereitstellen.",bearerTokenOptional:"Bearer-Token (optional)",bearerTokenHint:"Wenn gesetzt, müssen Anfragen <code>Authorization: Bearer <token></code> enthalten",metricsConnectionStatus:"Verbindungsstatus",metricsPrinterState:"Druckerstatus (idle/printing/etc)",metricsPrintProgress:"Druckfortschritt 0-100%",metricsBedTemp:"Betttemperatur",metricsNozzleTemp:"Düsentemperatur",metricsPrintsTotal:"Gesamtdrucke nach Ergebnis",metricsMore:"...und mehr (Schichten, Lüfter, Warteschlange, Filamentverbrauch)",smartPlugsDescription:"Smart Plugs (Tasmota oder Home Assistant) verbinden, um Stromsteuerung zu automatisieren und Energieverbrauch für Ihre Drucker zu verfolgen.",allOn:"Alle Ein",allOff:"Alle Aus",addSmartPlug:"Smart Plug hinzufügen",energySummary:"Energieübersicht",currentPower:"Aktuelle Leistung",plugsOnline:"{{reachable}}/{{total}} Plugs online",today:"Heute",yesterday:"Gestern",total:"Gesamt",enablePlugsForSummary:"Plugs aktivieren, um Energieübersicht zu sehen",addNotificationProvider:"Hinzufügen",systemBadge:"(System)",creating:"Erstellen...",changing:"Ändern...",deleteUserAndItems:"Benutzer UND dessen Elemente löschen",deleteUserKeepItems:"Benutzer löschen, Elemente behalten (werden herrenlos)",ok:"OK"},notification:{printStarted:{title:"Druck gestartet",body:"{{printer}}: {{filename}} wird gedruckt"},printCompleted:{title:"Druck abgeschlossen",body:"{{printer}}: {{filename}} erfolgreich abgeschlossen"},printFailed:{title:"Druck fehlgeschlagen",body:"{{printer}}: {{filename}} ist fehlgeschlagen"},printStopped:{title:"Druck gestoppt",body:"{{printer}}: {{filename}} wurde gestoppt"},printProgress:{title:"Druckfortschritt",body:"{{printer}}: {{filename}} ist zu {{percent}}% abgeschlossen"},printerOffline:{title:"Drucker offline",body:"{{printer}} ist offline"},printerError:{title:"Druckerfehler",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filament niedrig",body:"{{printer}}: Filament geht zur Neige"},maintenanceDue:{title:"Wartung fällig",body:"{{printer}}: {{items}} benötigen Aufmerksamkeit"}},errors:{generic:"Etwas ist schiefgelaufen",networkError:"Netzwerkfehler. Bitte überprüfen Sie Ihre Verbindung.",notFound:"Nicht gefunden",unauthorized:"Nicht autorisiert",serverError:"Serverfehler",validationError:"Bitte überprüfen Sie Ihre Eingabe",printerConnectionFailed:"Verbindung zum Drucker fehlgeschlagen",saveFailed:"Speichern fehlgeschlagen",deleteFailed:"Löschen fehlgeschlagen",loadFailed:"Laden der Daten fehlgeschlagen"},hmsErrors:{title:"Fehler - {{name}}",noErrors:"Keine Fehler",viewOnWiki:"Im Bambu Lab Wiki ansehen",clearInstructions:"Löschen Sie die Fehler am Drucker, um sie hier zu entfernen.",clearErrors:"Fehler löschen",clearSuccess:"HMS-Fehler gelöscht",clearFailed:"HMS-Fehler konnten nicht gelöscht werden"},mqttDebug:{title:"MQTT-Debug-Protokoll",searchPlaceholder:"Topic oder Payload suchen...",noMessages:"Noch keine Nachrichten protokolliert",startLoggingHint:'Klicken Sie auf "Protokollierung starten", um MQTT-Nachrichten aufzuzeichnen',noMessagesMatch:"Keine Nachrichten entsprechen Ihrem Filter",adjustFilterHint:"Versuchen Sie, Ihre Such- oder Filterkriterien anzupassen",incoming:"Eingehend",outgoing:"Ausgehend",loggingStopped:"Protokollierung gestoppt",loggingActive:"Protokollierung aktiv - Nachrichten werden automatisch aktualisiert",startLogging:"Protokollierung starten",stopLogging:"Protokollierung stoppen",clearLog:"Protokoll löschen",topic:"Topic",timestamp:"Zeitstempel",direction:"Richtung",all:"Alle"},printerFiles:{title:"Dateimanager",storageUsed:"Belegt:",storageFree:"Frei:",filterPlaceholder:"Dateien filtern...",deleteButton:"Löschen",deleteFiles:"{{count}} Dateien löschen",deleteFileConfirm:'"{{name}}" löschen? Dies kann nicht rückgängig gemacht werden.',deleteFilesConfirm:"{{count}} ausgewählte Dateien löschen? Dies kann nicht rückgängig gemacht werden.",noFiles:"Keine Dateien auf dem Drucker",loadingFiles:"Dateien werden geladen...",failedToLoad:"Dateien konnten nicht geladen werden",toast:{filesDeleted:"{{count}} Datei(en) gelöscht",deleteFailed:"Löschen fehlgeschlagen: {{error}}"}},confirm:{delete:"Möchten Sie dies wirklich löschen?",unsavedChanges:"Sie haben ungespeicherte Änderungen. Möchten Sie wirklich verlassen?",clearQueue:"Möchten Sie die Warteschlange wirklich leeren?"},login:{title:"Bambuddy Anmeldung",subtitle:"Melden Sie sich bei Ihrem Konto an",username:"Benutzername",usernamePlaceholder:"Benutzername eingeben",usernameOrEmail:"Benutzername oder E-Mail",usernameOrEmailPlaceholder:"Benutzername oder @ E-Mail",password:"Passwort",passwordPlaceholder:"Passwort eingeben",signIn:"Anmelden",signingIn:"Anmeldung läuft...",forgotPassword:"Passwort vergessen?",loginSuccess:"Erfolgreich angemeldet",loginFailed:"Anmeldung fehlgeschlagen",enterCredentials:"Bitte Benutzername und Passwort eingeben",forgotPasswordTitle:"Passwort vergessen",forgotPasswordMessage:"Wenn Sie Ihr Passwort vergessen haben, wenden Sie sich bitte an Ihren Systemadministrator.",forgotPasswordEmailMessage:"Geben Sie Ihre E-Mail-Adresse ein und wir senden Ihnen ein neues Passwort.",emailAddress:"E-Mail-Adresse",emailPlaceholder:"ihre.email@beispiel.de",cancel:"Abbrechen",sending:"Wird gesendet...",sendResetEmail:"Zurücksetzungs-E-Mail senden",howToReset:"So setzen Sie Ihr Passwort zurück:",resetStep1:"Kontaktieren Sie Ihren Bambuddy-Administrator",resetStep2:"Bitten Sie ihn, Ihr Passwort in der Benutzerverwaltung zurückzusetzen",resetStep3:"Er kann ein neues temporäres Passwort für Sie festlegen",resetStep4:"Melden Sie sich mit dem neuen Passwort an und ändern Sie es in den Einstellungen",gotIt:"Verstanden"},setup:{title:"Bambuddy Einrichtung",subtitle:"Konfigurieren Sie die Authentifizierung für Ihre Bambuddy-Instanz",enableAuth:"Authentifizierung aktivieren",adminAccount:"Admin-Konto",adminAccountDesc:"Wenn bereits Admin-Benutzer existieren, wird die Authentifizierung mit den vorhandenen Admin-Konten aktiviert. Lassen Sie die Felder unten leer, um vorhandene Admins zu verwenden, oder geben Sie neue Anmeldedaten ein, um einen neuen Admin-Benutzer zu erstellen.",adminUsername:"Admin-Benutzername",adminPassword:"Admin-Passwort",optionalIfAdminExists:"(optional, wenn Admin-Benutzer existieren)",adminUsernamePlaceholder:"Admin-Benutzernamen eingeben (optional)",adminPasswordPlaceholder:"Admin-Passwort eingeben (optional)",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Admin-Passwort bestätigen",settingUp:"Einrichtung läuft...",completeSetup:"Einrichtung abschließen",toast:{authEnabledAdminCreated:"Authentifizierung aktiviert und Admin-Benutzer erstellt",authEnabledExistingAdmins:"Authentifizierung mit vorhandenen Admin-Benutzern aktiviert",setupCompleted:"Einrichtung abgeschlossen",enterBothCredentials:"Bitte geben Sie sowohl Admin-Benutzernamen als auch Passwort ein, oder lassen Sie beide leer, um vorhandene Admin-Benutzer zu verwenden",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein"}},changePassword:{title:"Passwort ändern",currentPassword:"Aktuelles Passwort",currentPasswordPlaceholder:"Aktuelles Passwort eingeben",newPassword:"Neues Passwort",newPasswordPlaceholder:"Neues Passwort eingeben (min. 6 Zeichen)",confirmPassword:"Neues Passwort bestätigen",confirmPasswordPlaceholder:"Neues Passwort bestätigen",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein",changing:"Wird geändert...",success:"Passwort erfolgreich geändert",failed:"Passwortänderung fehlgeschlagen"},plateAlert:{title:"Druck pausiert!",message:"Objekte auf dem Druckbett erkannt. Der Druck wurde automatisch pausiert. Bitte räumen Sie das Druckbett und setzen Sie den Druck fort.",understand:"Verstanden"},camera:{title:"Kameraansicht",invalidPrinterId:"Ungültige Drucker-ID",live:"Live",snapshot:"Schnappschuss",restartStream:"Stream neu starten",refreshSnapshot:"Schnappschuss aktualisieren",fullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",connectingToCamera:"Verbinde mit Kamera...",capturingSnapshot:"Schnappschuss wird aufgenommen...",connectionLost:"Verbindung verloren",connectionFailed:"Kameraverbindung fehlgeschlagen",reconnecting:"Neuverbindung in {{countdown}}s... (Versuch {{attempt}}/{{max}})",reconnectNow:"Jetzt verbinden",cameraUnavailable:"Kamera nicht verfügbar",cameraUnavailableDesc:"Stellen Sie sicher, dass der Drucker eingeschaltet und verbunden ist.",noCamera:"Keine Kamera verfügbar",retry:"Erneut versuchen",cameraStream:"Kamera-Stream",zoomOut:"Verkleinern",zoomIn:"Vergrößern",resetZoom:"Zoom zurücksetzen",recording:"Aufnahme",startRecording:"Aufnahme starten",stopRecording:"Aufnahme stoppen",chamberLight:"Kammerbeleuchtung umschalten"},groups:{title:"Gruppenverwaltung",subtitle:"Berechtigungsgruppen für Zugriffskontrolle verwalten",backToSettings:"Zurück zu Einstellungen",createGroup:"Gruppe erstellen",noPermission:"Sie haben keine Berechtigung, auf diese Seite zuzugreifen.",system:"System",noDescription:"Keine Beschreibung",usersCount:"{{count}} Benutzer",permissionsCount:"{{count}} Berechtigungen",edit:"Bearbeiten",delete:"Löschen",toast:{created:"Gruppe erfolgreich erstellt",updated:"Gruppe erfolgreich aktualisiert",deleted:"Gruppe erfolgreich gelöscht",enterGroupName:"Bitte geben Sie einen Gruppennamen ein"},modal:{editGroup:"Gruppe bearbeiten",createGroup:"Gruppe erstellen",cancel:"Abbrechen",saving:"Speichern...",creating:"Erstellen...",saveChanges:"Änderungen speichern"},form:{groupName:"Gruppenname",groupNamePlaceholder:"Gruppennamen eingeben",systemGroupWarning:"Systemgruppennamen können nicht geändert werden",description:"Beschreibung",descriptionPlaceholder:"Beschreibung eingeben (optional)",permissions:"Berechtigungen ({{count}} ausgewählt)"},deleteModal:{title:"Gruppe löschen",message:"Sind Sie sicher, dass Sie diese Gruppe löschen möchten? Benutzer in dieser Gruppe verlieren diese Berechtigungen.",confirm:"Gruppe löschen"},editor:{title:"Gruppe bearbeiten",createTitle:"Gruppe erstellen",search:"Berechtigungen suchen...",selectAll:"Alle auswählen",clearAll:"Alle abwählen",permissionsSelected:"{{count}} ausgewählt",noResults:"Keine Berechtigungen entsprechen Ihrer Suche"}},users:{title:"Benutzerverwaltung",subtitle:"Benutzer und deren Zugriff auf Ihre Bambuddy-Instanz verwalten",backToSettings:"Zurück zu Einstellungen",createUser:"Benutzer erstellen",noPermission:"Sie haben keine Berechtigung, auf diese Seite zuzugreifen.",admin:"Admin",noGroups:"Keine Gruppen",active:"Aktiv",inactive:"Inaktiv",edit:"Bearbeiten",delete:"Löschen",system:"System",noGroupsAvailable:"Keine Gruppen verfügbar",table:{username:"Benutzername",groups:"Gruppen",status:"Status",actions:"Aktionen"},toast:{created:"Benutzer erfolgreich erstellt",updated:"Benutzer erfolgreich aktualisiert",deleted:"Benutzer erfolgreich gelöscht",fillRequired:"Bitte füllen Sie alle Pflichtfelder aus",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein"},modal:{createUser:"Benutzer erstellen",editUser:"Benutzer bearbeiten",cancel:"Abbrechen",creating:"Erstellen...",saving:"Speichern...",saveChanges:"Änderungen speichern",advancedAuthSubtitle:"mit erweiterter Authentifizierung"},form:{username:"Benutzername",usernamePlaceholder:"Benutzernamen eingeben",email:"E-Mail",emailPlaceholder:"benutzer@beispiel.de",password:"Passwort",passwordPlaceholder:"Passwort eingeben",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Passwort bestätigen",newPasswordPlaceholder:"Neues Passwort eingeben",confirmNewPasswordPlaceholder:"Neues Passwort bestätigen",leaveBlankToKeep:"leer lassen, um das aktuelle zu behalten",groups:"Gruppen",optional:"optional",autoGeneratedPassword:"Ein sicheres Passwort wird automatisch generiert und per E-Mail an den Benutzer gesendet.",passwordManagedByAdvancedAuth:'Das Passwort wird durch erweiterte Authentifizierung verwaltet. Verwenden Sie "Passwort zurücksetzen", um ein neues Passwort per E-Mail an den Benutzer zu senden.',resetPassword:"Passwort zurücksetzen",resettingPassword:"Passwort wird zurückgesetzt..."},deleteModal:{title:"Benutzer löschen",message:"Sind Sie sicher, dass Sie diesen Benutzer löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",confirm:"Benutzer löschen"}},streamOverlay:{title:"Stream-Overlay",invalidPrinterId:"Ungültige Drucker-ID",cameraStream:"Kamera-Stream",progress:"Fortschritt",eta:"ETA",printerIdle:"Drucker ist inaktiv",printerOffline:"Drucker offline",status:{printing:"Druckt",paused:"Pausiert",finished:"Fertig",failed:"Fehlgeschlagen",idle:"Inaktiv",unknown:"Unbekannt"}},profiles:{title:"Profile",subtitle:"Verwalten Sie Ihre Slicer-Voreinstellungen und Druckvorschub-Kalibrierungen",tabs:{cloud:"Cloud-Profile",local:"Lokale Profile",kprofiles:"K-Profile"},localProfiles:{title:"Lokale Profile",subtitle:"Slicer-Voreinstellungen aus OrcaSlicer importieren und verwalten",import:"Profile importieren",importDesc:".bbscfg-, .bbsflmt-, .orca_filament-, .zip- oder .json-Dateien hier ablegen",importing:"Importiere...",search:"Lokale Voreinstellungen durchsuchen...",noPresets:"Noch keine lokalen Voreinstellungen",badge:"Lokal",edit:"Bearbeiten",delete:"Löschen",cancel:"Abbrechen",deleteConfirmTitle:"Voreinstellung löschen",deleteConfirm:"Möchten Sie diese Voreinstellung wirklich löschen? Dies kann nicht rückgängig gemacht werden.",source:"Quelle",inheritsFrom:"Erbt von",filamentType:"Typ",vendor:"Hersteller",compatiblePrinters:"Drucker",nozzleTemp:"Düsentemperatur",cost:"Kosten",density:"Dichte",pressureAdvance:"Druckvorschub",filament:"Filament",process:"Prozess",printer:"Drucker",toast:{importSuccess:"{{count}} Voreinstellung(en) importiert",importSkipped:"{{count}} Voreinstellung(en) übersprungen (Duplikate)",importError:"{{count}} Fehler beim Import",deleted:"Voreinstellung gelöscht",updated:"Voreinstellung aktualisiert"}},connectedAs:"Verbunden als",logout:"Abmelden",noLogoutPermission:"Sie haben keine Berechtigung zum Abmelden",failedToLoad:"Profile konnten nicht geladen werden",retry:"Erneut versuchen",time:{justNow:"Gerade eben",minsAgo:"vor {{count}}m",hoursAgo:"vor {{count}}h",daysAgo:"vor {{count}}d"},toast:{loggedOut:"Abgemeldet"},login:{title:"Mit Bambu Cloud verbinden",subtitle:"Synchronisieren Sie Ihre Slicer-Voreinstellungen geräteübergreifend",email:"E-Mail",password:"Passwort",region:"Region",regionGlobal:"Global",regionChina:"China",verificationCode:"Bestätigungscode",totpCode:"Authenticator-Code",checkEmail:"Prüfen Sie Ihre E-Mail ({{email}}) für einen 6-stelligen Code",enterTotpHint:"Geben Sie den 6-stelligen Code aus Ihrer Authenticator-App ein",accessToken:"Zugriffstoken",accessTokenHint:"Fügen Sie Ihr Bambu Lab Zugriffstoken ein (aus Bambu Studio)",back:"Zurück",loginButton:"Anmelden",verifyButton:"Bestätigen",setTokenButton:"Token setzen",useToken:"Stattdessen Zugriffstoken verwenden",useEmail:"Stattdessen mit E-Mail anmelden",toast:{loggedIn:"Erfolgreich angemeldet",codeSent:"Bestätigungscode an Ihre E-Mail gesendet",enterTotp:"Geben Sie den Code aus Ihrer Authenticator-App ein",tokenSet:"Token erfolgreich gesetzt"}},presets:{myPreset:"Mein Profil (bearbeitbar)",duplicate:"Duplizieren",editable:"Bearbeitbar",failedToLoadDetails:"Profil-Details konnten nicht geladen werden",deleteConfirm:"Dieses Profil löschen?",deleteWarning:'"{{name}}" wird dauerhaft aus Bambu Cloud gelöscht. Dies kann nicht rückgängig gemacht werden.',noDuplicatePermission:"Sie haben keine Berechtigung zum Duplizieren von Profilen",noEditPermission:"Sie haben keine Berechtigung zum Bearbeiten von Profilen",noDeletePermission:"Sie haben keine Berechtigung zum Löschen von Profilen",types:{filament:"Filament-Profil",printer:"Drucker-Profil",process:"Prozess-Profil"},toast:{deleted:"Profil gelöscht",created:"Profil erstellt",updated:"Profil aktualisiert",duplicated:"Profil dupliziert",fieldAdded:'Feld "{{key}}" hinzugefügt',exported:"Profil exportiert"},baseLabel:"Basis: {{name}}",currentLabel:"Aktuell: {{name}}",newPreset:"Neues Profil",editPreset:"Profil bearbeiten",duplicatePreset:"Profil duplizieren",createNewPreset:"Neues Profil erstellen",customizeSettings:"Passen Sie die Einstellungen für Ihr neues Profil an",compareWithBase:"Mit Basis-Profil vergleichen",compare:"Vergleichen",basePreset:"Basis-Profil",selectBasePreset:"Basis-Profil auswählen...",presetName:"Profilname",myCustomPreset:"Mein eigenes Profil",inheritsFrom:"Erbt von",dropJsonToImport:"JSON zum Importieren ablegen",tabs:{common:"Allgemein",allFields:"Alle Felder"},availableFields:"Verfügbare Felder",searchFieldsPlaceholder:"Felder suchen...",noMatchingFields:"Keine passenden Felder",allFieldsAdded:"Alle Felder hinzugefügt",addCustomField:"Eigenes Feld hinzufügen",yourOverrides:"Ihre Überschreibungen",noOverridesYet:"Noch keine Überschreibungen",clickFieldsToAdd:"Klicken Sie links auf Felder, um sie hinzuzufügen",saveAsTemplate:"Als Vorlage speichern",jsonTip:"Tipp: Ziehen Sie eine .json-Datei auf dieses Fenster, um Einstellungen zu importieren"},cloudView:{searchPlaceholder:"Profile suchen...",templates:"Vorlagen",refresh:"Aktualisieren",newPreset:"Neues Profil",clearFilters:"Filter zurücksetzen",compareMode:"Vergleichsmodus",selectAnotherPreset:"Wählen Sie ein weiteres {{type}}-Profil",clickTwoPresets:"Klicken Sie auf zwei Profile des gleichen Typs zum Vergleichen",selectFirst:"1. Erstes auswählen",selectSecond:"2. Zweites auswählen",compareNow:"Jetzt vergleichen",lastSynced:"Zuletzt synchronisiert:",showingCount:"{{showing}} von {{total}} Profilen",noPresetsFound:"Keine Profile gefunden",columns:{filament:"Filament",process:"Prozess",printer:"Drucker"},noFilamentPresets:"Keine Filament-Profile",noProcessPresets:"Keine Prozess-Profile",noPrinterPresets:"Keine Drucker-Profile",filters:{type:"Typ",owner:"Besitzer",printer:"Drucker",nozzle:"Düse",filament:"Filament",layer:"Schicht",all:"Alle",myPresets:"Meine Profile",builtIn:"Voreingestellt",process:"Prozess"},noTemplatesPermission:"Sie haben keine Berechtigung, Vorlagen zu verwalten",noRefreshPermission:"Sie haben keine Berechtigung, Profile zu aktualisieren",noCreatePermission:"Sie haben keine Berechtigung, Profile zu erstellen"},templates:{title:"Schnellvorlagen",noTemplates:"Noch keine Vorlagen",createFirst:"Erstellen Sie Vorlagen aus dem Preset-Editor",typeFilter:"Typ:",deleteTitle:"Vorlage löschen",deleteWarning:"Diese Aktion kann nicht rückgängig gemacht werden",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',namePlaceholder:"Vorlagenname",descriptionPlaceholder:"Beschreibung",settingsJson:"Einstellungen (JSON)",fieldsCount:"{{count}} Felder",shownInModals:"In Dialogen angezeigt",hiddenInModals:"In Dialogen ausgeblendet",apply:"Anwenden",toast:{deleted:"Vorlage gelöscht",updated:"Vorlage aktualisiert",created:"Vorlage erstellt",applied:"Vorlage angewendet"}}},support:{debugLoggingActive:"Debug-Protokollierung ist aktiv",manageLogs:"Verwalten",collectItem7:"Drucker-Verbindungsstatus und Firmware-Versionen",collectItem8:"Integrationsstatus (Spoolman, MQTT, HA)",collectItem9:"Netzwerkschnittstellen (nur Subnetze)",collectItem10:"Python-Paketversionen",collectItem11:"Datenbankzustandsprüfungen",collectItem12:"Docker-Umgebungsdetails"},fileManager:{title:"Dateimanager",subtitle:"Organisieren und verwalten Sie Ihre Druckdateien",uploadFiles:"Dateien hochladen",newFolder:"Neuer Ordner",folderName:"Ordnername",folderNamePlaceholder:"z.B. Funktionsteile",renameFile:"Datei umbenennen",renameFolder:"Ordner umbenennen",moveFiles:"{{count}} Datei(en) verschieben",rootNoFolder:"Stammverzeichnis (Kein Ordner)",current:"aktuell",linkFolder:"Ordner verknüpfen",linkFolderDescription:'"{{name}}" mit einem Projekt oder Archiv verknüpfen für schnellen Zugriff.',project:"Projekt",archive:"Archiv",noProjectsFound:"Keine Projekte gefunden",noArchivesFound:"Keine Archive gefunden",unlink:"Verknüpfung aufheben",link:"Verknüpfen",dragDropFiles:"Dateien hierher ziehen",dropFilesHere:"Dateien hier ablegen",orClickToBrowse:"oder klicken zum Durchsuchen",allFileTypesSupported:"Alle Dateitypen werden unterstützt. ZIP-Dateien werden extrahiert.",zipFilesDetected:"ZIP-Dateien erkannt",zipExtractOptions:"ZIP-Dateien werden extrahiert. Wählen Sie, wie die Ordnerstruktur behandelt werden soll:",preserveZipStructure:"Ordnerstruktur aus ZIP beibehalten",createFolderFromZip:"Ordner aus ZIP-Dateiname erstellen",stlThumbnailGeneration:"STL-Vorschaubildgenerierung",zipMayContainStl:"ZIP-Dateien können STL-Dateien enthalten. Vorschaubilder können während der Extraktion generiert werden.",thumbnailsCanBeGenerated:"Vorschaubilder können für STL-Dateien generiert werden. Große Modelle benötigen möglicherweise mehr Zeit.",generateThumbnailsForStl:"Vorschaubilder für STL-Dateien generieren",threemfDetected:"3MF-Dateien erkannt",threemfExtractionInfo:"Druckermodell, Material, Farbe und Druckeinstellungen werden automatisch aus 3MF-Dateien extrahiert.",willBeExtracted:"Wird extrahiert",filesExtracted:"{{count}} Dateien extrahiert",uploadComplete:"Upload abgeschlossen: {{succeeded}} erfolgreich",uploadFailed:"Hochladen fehlgeschlagen",zipFilesFailed:"{{count}} Dateien fehlgeschlagen",uploading:"Hochladen...",changeLink:"Verknüpfung ändern...",linkTo:"Verknüpfen mit...",linkToProjectOrArchive:"Mit Projekt oder Archiv verknüpfen",addToQueue:"Zur Warteschlange",schedulePrint:"Planen",generateThumbnail:"Vorschaubild generieren",generateThumbnails:"Vorschaubilder generieren",generateThumbnailsForMissing:"Vorschaubilder für STL-Dateien ohne Vorschau generieren",gridView:"Rasteransicht",listView:"Listenansicht",lowDiskSpaceWarning:"Warnung: Wenig Speicherplatz",lowDiskSpaceDetails:"Nur {{free}} frei von {{total}} gesamt. Schwellenwert ist auf {{threshold}} GB eingestellt.",files:"Dateien",folders:"Ordner",size:"Größe",free:"Frei",allFiles:"Alle Dateien",wrap:"Umbrechen",enableTextWrapping:"Textumbruch aktivieren",disableTextWrapping:"Textumbruch deaktivieren",dragToResizeTooltip:"Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen",searchFiles:"Dateien suchen...",allTypes:"Alle Typen",prints:"Drucke",ascending:"Aufsteigend",descending:"Absteigend",resultsCount:"{{showing}} von {{total}} Dateien",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",selected:"{{count}} ausgewählt",adding:"Hinzufügen...",loadingFiles:"Dateien werden geladen...",folderIsEmpty:"Ordner ist leer",noFilesYet:"Noch keine Dateien",folderEmptyDescription:"Laden Sie Dateien hoch oder verschieben Sie Dateien in diesen Ordner.",noFilesDescription:"Laden Sie Dateien hoch, um Ihre Druckdateien zu organisieren.",noMatchingFiles:"Keine passenden Dateien",noMatchingFilesDescription:"Keine Dateien entsprechen Ihren aktuellen Such- oder Filterkriterien.",clearFilters:"Filter zurücksetzen",printedCount:"{{count}}x gedruckt",uploadedBy:"Hochgeladen von",deleteFolder:"Ordner löschen",deleteFile:"Datei löschen",deleteFilesCount:"{{count}} Dateien löschen",deleteFolderConfirm:"Möchten Sie diesen Ordner wirklich löschen? Alle Dateien darin werden ebenfalls gelöscht.",deleteFileConfirm:"Möchten Sie diese Datei wirklich löschen?",deleteFilesConfirm:"Möchten Sie {{count}} ausgewählte Dateien wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.",deleting:"Wird gelöscht...",noPermissionRenameFolder:"Sie haben keine Berechtigung, Ordner umzubenennen",noPermissionLinkFolder:"Sie haben keine Berechtigung, Ordner zu verknüpfen",noPermissionDeleteFolder:"Sie haben keine Berechtigung, Ordner zu löschen",noPermissionPrint:"Sie haben keine Berechtigung zum Drucken",noPermissionAddToQueue:"Sie haben keine Berechtigung, zur Warteschlange hinzuzufügen",noPermissionDownload:"Sie haben keine Berechtigung, Dateien herunterzuladen",noPermissionRenameFile:"Sie haben keine Berechtigung, diese Datei umzubenennen",noPermissionGenerateThumbnail:"Sie haben keine Berechtigung, Vorschaubilder zu generieren",noPermissionDeleteFile:"Sie haben keine Berechtigung, diese Datei zu löschen",noPermissionCreateFolder:"Sie haben keine Berechtigung, Ordner zu erstellen",noPermissionUpload:"Sie haben keine Berechtigung, Dateien hochzuladen",noPermissionMoveFiles:"Sie haben keine Berechtigung, Dateien zu verschieben",noPermissionDeleteFiles:"Sie haben keine Berechtigung, Dateien zu löschen",linkExternal:"Extern verknüpfen",linkExternalFolder:"Externen Ordner verknüpfen",linkExternalFolderDescription:"Ein Host-Verzeichnis (NAS, USB, Netzlaufwerk) in den Dateimanager einbinden. Dateien werden nicht kopiert — sie werden direkt vom Originalpfad gelesen.",externalFolderNamePlaceholder:"z.B. NAS-Drucke",externalPath:"Host-Pfad",externalPathHelp:"Absoluter Pfad zum Verzeichnis auf dem Docker-Host. Muss als Bind-Mount in den Container eingebunden sein.",readOnly:"Nur Lesen",readOnlyHelp:"verhindert Uploads und Löschungen",showHiddenFiles:"Versteckte Dateien anzeigen (Punkt-Dateien)",externalFolder:"Externer Ordner",scanFolder:"Scannen",toast:{folderCreated:"Ordner erstellt",folderDeleted:"Ordner gelöscht",fileDeleted:"Datei gelöscht",filesDeleted:"{{count}} Dateien gelöscht",filesMoved:"Dateien verschoben",folderLinked:"Ordner verknüpft",folderUnlinked:"Ordnerverknüpfung aufgehoben",externalFolderLinked:"Externer Ordner verknüpft und gescannt",folderScanned:"Scan abgeschlossen: {{added}} hinzugefügt, {{removed}} entfernt",addedToQueue:"{{count}} Datei(en) zur Warteschlange hinzugefügt",addedToQueuePartial:"{{added}} Datei(en) hinzugefügt, {{failed}} fehlgeschlagen",failedToAddToQueue:"Fehler beim Hinzufügen: {{error}}",fileRenamed:"Datei umbenannt",folderRenamed:"Ordner umbenannt",thumbnailsGenerated:"{{count}} Vorschaubild(er) generiert",thumbnailsGeneratedPartial:"{{succeeded}} Vorschaubild(er) generiert, {{failed}} fehlgeschlagen",noStlMissingThumbnails:"Keine STL-Dateien ohne Vorschaubild",failedToGenerateThumbnails:"Fehler beim Generieren der Vorschaubilder: {{error}}",thumbnailGenerated:"Vorschaubild generiert",failedToGenerateThumbnail:"Fehler beim Generieren des Vorschaubildes: {{error}}"}},projects:{title:"Projekte",subtitle:"Organisieren und verfolgen Sie Ihre 3D-Druckprojekte",newProject:"Neues Projekt",editProject:"Projekt bearbeiten",deleteProject:"Projekt löschen",projectName:"Projektname",description:"Beschreibung",noProjects:"Noch keine Projekte",noProjectsFiltered:"Keine {{status}} Projekte",noProjectsFilteredHelp:"Sie haben keine {{status}} Projekte. Projekte werden hier angezeigt, wenn sich ihr Status ändert.",createFirst:"Erstellen Sie Ihr erstes Projekt, um verwandte Drucke zu organisieren, den Fortschritt zu verfolgen und Ihre Builds zu verwalten.",createFirstButton:"Erstes Projekt erstellen",create:"Erstellen",files:"Dateien",prints:"Drucke",plates:"Platten",parts:"Teile",lastModified:"Zuletzt geändert",deleteConfirm:"Möchten Sie dieses Projekt wirklich löschen? Archive und Warteschlangenelemente werden getrennt, aber nicht gelöscht.",addFiles:"Dateien hinzufügen",removeFile:"Datei entfernen",viewDetails:"Details anzeigen",namePlaceholder:"z.B. Voron 2.4 Build",descriptionPlaceholder:"Optionale Beschreibung...",color:"Farbe",targetPlates:"Ziel-Platten",targetPlatesPlaceholder:"z.B. 25",targetPlatesHelp:"Anzahl der Druckaufträge",targetParts:"Ziel-Teile",targetPartsPlaceholder:"z.B. 150",targetPartsHelp:"Benötigte Objekte insgesamt",tagsLabel:"Tags (kommagetrennt)",tagsPlaceholder:"z.B. voron, funktional, geschenk",dueDate:"Fälligkeitsdatum",priority:"Priorität",priorityLow:"Niedrig",priorityNormal:"Normal",priorityHigh:"Hoch",priorityUrgent:"Dringend",statusActive:"Aktiv",statusCompleted:"Abgeschlossen",statusArchived:"Archiviert",done:"Fertig",completed:"abgeschlossen",failed:"fehlgeschlagen",inQueue:"in Warteschlange",noPrintsYet:"Noch keine Drucke",printJobs:"Druckaufträge (Platten)",partsPrinted:"Gedruckte Teile",failedParts:"Fehlgeschlagene Teile",import:"Importieren",export:"Exportieren",importProject:"Projekt importieren",exportAll:"Alle Projekte exportieren",loading:"Projekte werden geladen...",noEditPermission:"Sie haben keine Berechtigung, Projekte zu bearbeiten",noDeletePermission:"Sie haben keine Berechtigung, Projekte zu löschen",noCreatePermission:"Sie haben keine Berechtigung, Projekte zu erstellen",noImportPermission:"Sie haben keine Berechtigung, Projekte zu importieren",noExportPermission:"Sie haben keine Berechtigung, Projekte zu exportieren",toast:{created:"Projekt erstellt",updated:"Projekt aktualisiert",deleted:"Projekt gelöscht",imported:"Projekt importiert",multipleImported:"{{count}} Projekte importiert",importFailed:"Import fehlgeschlagen",exported:"Projekte exportiert (nur Metadaten)"}},projectDetail:{notFound:"Projekt nicht gefunden",backToProjects:"Zurück zu Projekten",export:"Exportieren",exportProject:"Projekt exportieren",noExportPermission:"Sie haben keine Berechtigung, Projekte zu exportieren",noEditPermission:"Sie haben keine Berechtigung, Projekte zu bearbeiten",partOf:"Teil von:",priorityLabel:"Priorität:",noPrints:"Noch keine Drucke in diesem Projekt",status:{active:"Aktiv",completed:"Abgeschlossen",archived:"Archiviert"},priority:{low:"Niedrig",normal:"Normal",high:"Hoch",urgent:"Dringend"},dueDate:{overdue:"Überfällig",today:"Heute fällig",daysLeft:"{{count}} Tage übrig"},progress:{platesProgress:"Platten-Fortschritt",partsProgress:"Teile-Fortschritt",printJobs:"Druckaufträge",parts:"Teile",percentComplete:"{{percent}}% abgeschlossen",remaining:"{{count}} verbleibend"},stats:{printJobs:"Druckaufträge",total:"gesamt",failed:"{{count}} fehlgeschlagen",partsPrinted:"{{count}} Teile gedruckt",printTime:"Druckzeit",filamentUsed:"Filament verbraucht"},cost:{title:"Kostenverfolgung",filamentCost:"Filamentkosten",energy:"Energie",totalCost:"Gesamtkosten",total:"Gesamt",includesBom:"inkl. Stückliste",budget:"Budget",remaining:"Verbleibend"},subProjects:{title:"Unterprojekte ({{count}})"},notes:{title:"Notizen",noEditPermission:"Sie haben keine Berechtigung, Notizen zu bearbeiten",placeholder:"Notizen zu diesem Projekt hinzufügen...",empty:"Noch keine Notizen. Klicken Sie auf Bearbeiten, um Notizen hinzuzufügen."},files:{title:"Dateien",linkFolders:"Ordner aus dem Dateimanager verknüpfen",forQuickAccess:"für schnellen Zugriff auf dieses Projekt.",fileCount:"{{count}} Datei(en)",empty:"Keine Ordner verknüpft. Gehen Sie zum Dateimanager und verknüpfen Sie einen Ordner mit diesem Projekt."},bom:{title:"Stückliste",acquired:"{{completed}}/{{total}} beschafft",showAll:"Alle anzeigen",hideDone:"Erledigte ausblenden",addPart:"Teil hinzufügen",noAddPermission:"Sie haben keine Berechtigung, Teile hinzuzufügen",partNamePlaceholder:"Teilename (z.B. M3x8 Schrauben)",partName:"Teilename",qty:"Menge",price:"Preis ({{currency}})",sourcingUrlPlaceholder:"Bezugsquelle-URL (optional)",remarksPlaceholder:"Bemerkungen (optional)",deletePart:"Teil löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',noUpdatePermission:"Sie haben keine Berechtigung, Teile zu aktualisieren",noEditPermission:"Sie haben keine Berechtigung, Teile zu bearbeiten",noDeletePermission:"Sie haben keine Berechtigung, Teile zu löschen",totalCost:"Gesamtkosten:",empty:"Keine Teile in der Stückliste. Fügen Sie Hardware, Elektronik oder andere Komponenten hinzu, um zu verfolgen, was beschafft werden muss."},timeline:{title:"Aktivitätsverlauf",empty:"Noch keine Aktivität."},template:{saveAsTemplate:"Als Vorlage speichern",noCreatePermission:"Sie haben keine Berechtigung, Vorlagen zu erstellen"},queue:{title:"Warteschlange",viewAll:"Alle anzeigen",printing:"{{count}} druckend",queued:"{{count}} in Warteschlange"},prints:{title:"Drucke ({{count}})"},toast:{projectUpdated:"Projekt aktualisiert",partAdded:"Teil hinzugefügt",partRemoved:"Teil entfernt",exportFailed:"Export fehlgeschlagen",projectExported:"Projekt exportiert",templateCreated:"Vorlage erstellt"}},system:{title:"Systeminformationen",version:"Version",uptime:"Laufzeit",cpuUsage:"CPU-Auslastung",memoryUsage:"Speicherauslastung",diskUsage:"Festplattenauslastung",networkInfo:"Netzwerkinformationen",logs:"Protokolle",debugMode:"Debug-Modus",enableDebug:"Debug-Protokollierung aktivieren",disableDebug:"Debug-Protokollierung deaktivieren",downloadLogs:"Protokolle herunterladen",clearLogs:"Protokolle löschen",dockerInfo:"Docker-Info",containerName:"Container-Name",imageName:"Image-Name",platform:"Plattform",architecture:"Architektur"},library:{title:"Filament-Bibliothek",addFilament:"Filament hinzufügen",editFilament:"Filament bearbeiten",deleteFilament:"Filament löschen",vendor:"Hersteller",material:"Material",color:"Farbe",kFactor:"K-Faktor",temperature:"Temperatur",noFilaments:"Keine Filamente in der Bibliothek",deleteConfirm:"Möchten Sie dieses Filament wirklich löschen?",importFromPrinter:"Vom Drucker importieren",exportToFile:"In Datei exportieren"},spoolman:{title:"Spoolman-Integration",enabled:"Spoolman aktiviert",url:"Spoolman URL",connected:"Verbunden",disconnected:"Nicht verbunden",testConnection:"Verbindung testen",sync:"Synchronisieren",syncing:"Synchronisiert...",lastSync:"Letzte Synchronisierung",linkToSpoolman:"Mit Spoolman verknüpfen",openInSpoolman:"In Spoolman öffnen",unlinkSpool:"Spule trennen",unlinkConfirmTitle:"Spule entkoppeln?",unlinkConfirmMessage:"Dadurch wird die Spule von Spoolman getrennt. Die Spulendaten in Spoolman bleiben unverändert.",selectSpool:"Spule auswählen",noUnlinkedSpools:"Keine nicht verknüpften Spulen verfügbar",linkSuccess:"Spule erfolgreich mit Spoolman verknüpft",linkFailed:"Verknüpfung mit Spoolman fehlgeschlagen",unlinkSuccess:"Spule erfolgreich von Spoolman getrennt",unlinkFailed:"Trennen der Spule von Spoolman fehlgeschlagen",spoolId:"Spulen-ID",fillSourceLabel:"(Spoolman)",weight:"Gewicht",remaining:"Verbleibend",disableWeightSync:"AMS-Gewichtsschätzung deaktivieren",disableWeightSyncDesc:"Verbleibende Kapazität nicht aus AMS-Schätzungen aktualisieren. Verwenden Sie dies, wenn Sie die Verbrauchserfassung von Spoolman gegenüber den prozentualen AMS-Schätzungen bevorzugen. Neue Spulen verwenden weiterhin die AMS-Schätzung als Anfangsgewicht.",reportPartialUsage:"Teilverbrauch bei fehlgeschlagenen Drucken melden",reportPartialUsageDesc:"Wenn ein Druck fehlschlägt oder abgebrochen wird, den geschätzten Filamentverbrauch bis zu diesem Zeitpunkt basierend auf dem Schichtfortschritt melden."},inventory:{title:"Spulen-Inventar",addSpool:"Spule hinzufügen",editSpool:"Spule bearbeiten",material:"Material",selectMaterial:"Material auswählen...",subtype:"Untertyp",brand:"Marke",searchBrand:"Marke suchen...",useCustomBrand:'"{{brand}}" verwenden',useCustomMaterial:"Benutzerdefiniertes Material verwenden: {{material}}",colorName:"Farbname",colorNamePlaceholder:"Jade White, Fire Red...",color:"Farbe",hexColor:"Hex-Farbe",pickColor:"Benutzerdefinierte Farbe wählen",labelWeight:"Nenngewicht",coreWeight:"Leergewicht der Spule",searchSpoolWeight:"Spulengewicht suchen...",weightUsed:"Verbraucht",currentWeight:"Restgewicht",measuredWeight:"Gemessenes Gewicht",spoolName:"Spule",costPerKg:"Kosten pro kg",measuredWeightError:"Das gemessene Gewicht muss zwischen {{min}}g und {{max}}g liegen.",slicerFilament:"Slicer-Filament",slicerFilamentName:"Slicer-Preset-Name",slicerPreset:"Slicer-Preset",searchPresets:"Filament-Presets suchen...",selectedPreset:"Ausgewählt",noPresetsFound:"Keine Presets gefunden",tempOverrides:"Temperatur-Überschreibungen",note:"Notiz",notePlaceholder:"Zusätzliche Notizen zu dieser Spule...",archive:"Archivieren",restore:"Wiederherstellen",noSpools:"Noch keine Spulen. Fügen Sie Ihre erste Spule hinzu.",noManualSpools:"Keine manuell hinzugefügten Spulen verfügbar. Fügen Sie zuerst eine Spule zum Inventar hinzu.",kProfiles:"K-Profile",addKProfile:"K-Profil hinzufügen",assignSpool:"Spule zuweisen",unassignSpool:"Zuweisung aufheben",assignSuccess:"Spule zugewiesen und AMS-Slot konfiguriert",assignFailed:"Spulenzuweisung fehlgeschlagen",selectSpool:"Wählen Sie eine Spule für diesen Slot",assigned:"Zugewiesen",assigning:"Wird zugewiesen...",searchSpools:"Spulen suchen...",showAllSpools:"Alle Spulen anzeigen",allMaterials:"Alle Materialien",filterByBrand:"Nach Marke filtern...",showArchived:"Archivierte anzeigen",quickAdd:"Schnellerfassung (Lager)",quantity:"Menge",stock:"Lager",configured:"Konfiguriert",spoolsCreated:"{{count}} Spulen erstellt",spoolCreated:"Spule erstellt",spoolUpdated:"Spule aktualisiert",spoolDeleted:"Spule gelöscht",spoolArchived:"Spule archiviert",spoolRestored:"Spule wiederhergestellt",deleteConfirm:"Möchten Sie diese Spule wirklich löschen? Dies kann nicht rückgängig gemacht werden.",archiveConfirm:"Möchten Sie diese Spule wirklich archivieren?",advancedSettings:"Erweiterte Einstellungen",filamentInfoTab:"Filament-Info",paProfileTab:"PA-Profil",filamentInfo:"Filament",additional:"Zusätzlich",loadingPresets:"Cloud-Presets werden geladen...",cloudConnected:"Cloud verbunden",cloudNotConnected:"Cloud nicht verbunden (Standardwerte)",recentColors:"Zuletzt",searchColors:"Farben suchen...",searchResults:"Suchergebnisse",allColors:"Alle Farben",commonColors:"Häufige Farben",showLess:"Weniger",showAll:"Alle",noColorsFound:"Keine Farben gefunden",noResults:"Keine Ergebnisse",selectMaterialFirst:"Bitte zuerst ein Material im Filament-Info Tab auswählen.",noPrintersConfigured:"Keine Drucker konfiguriert. Fügen Sie Drucker hinzu.",matchingFilter:"Filter",anyBrand:"Jede Marke",anyVariant:"Jede Variante",autoSelect:"Auto-Auswahl",matches:"Treffer",match:"Treffer",noMatches:"Keine Treffer",connected:"Verbunden",offline:"Offline",printerOffline:"Drucker ist offline. Verbinden Sie ihn, um Kalibrierungsprofile anzuzeigen.",noKProfilesMatch:"Keine K-Profile stimmen mit dem gewählten Filament überein.",leftNozzle:"Linke Düse",rightNozzle:"Rechte Düse",profilesSelected:"Kalibrierungsprofil(e) ausgewählt",totalInventory:"Gesamtbestand",totalConsumed:"Gesamtverbrauch",byMaterial:"Nach Material",inPrinter:"Im Drucker",lowStock:"Niedriger Bestand",sinceTracking:"Seit Beginn der Erfassung",loadedInAms:"Im AMS/Ext geladen",remaining:"Verbleibend",weightCheck:"Gewichtskontrolle",lastWeighed:"Zuletzt gewogen",neverWeighed:"Nie gewogen",search:"Spulen suchen...",showing:"Zeige",to:"bis",of:"von",show:"Zeige",spools:"Spulen",spool:"Spule",page:"Seite",noSpoolsMatch:"Keine Ergebnisse",noSpoolsMatchDesc:"Versuchen Sie, Ihre Suche oder Filter anzupassen.",active:"Aktiv",archived:"Archiviert",all:"Alle",used:"Verwendet",new:"Neu",clearFilters:"Filter löschen",table:"Tabelle",cards:"Karten",net:"Netto",groupSimilar:"Gruppieren",groupedSpools:"{{count}} identische Spulen",groupedRows:"Zeilen",columns:"Spalten",configureColumns:"Spalten konfigurieren",configureColumnsDesc:"Ziehen zum Neuordnen oder Pfeile verwenden. Sichtbarkeit mit dem Augensymbol umschalten.",visible:"sichtbar",reset:"Zurücksetzen",cancel:"Abbrechen",applyChanges:"Änderungen anwenden",moveUp:"Nach oben",moveDown:"Nach unten",hideColumn:"Spalte ausblenden",showColumn:"Spalte einblenden",linkToSpool:"Mit Spule verknüpfen",tagLinked:"Tag mit Spule verknüpft",tagLinkFailed:"Tag-Verknüpfung fehlgeschlagen",tagAlreadyLinked:"Tag bereits mit anderer Spule verknüpft",unknownTag:"Unbekannter RFID-Tag erkannt",usageHistory:"Verbrauchshistorie",noUsageHistory:"Noch kein Verbrauch erfasst",printName:"Druckname",weightConsumed:"Verbrauchtes Gewicht",clearHistory:"Löschen",historyCleared:"Verbrauchshistorie gelöscht",fillSourceLabel:"(Inv)",lowStockThresholdError:"Der Schwellenwert muss zwischen 0.1 und 99.9 liegen",assignMismatchTitle:"Material stimmt nicht überein",assignMismatchMessage:'Das ausgewählte Spulenmaterial "{{spoolMaterial}}" stimmt nicht mit dem Tray-Material "{{trayMaterial}}" für {{location}} überein. Trotzdem zuweisen?',assignMismatchConfirm:"Trotzdem zuweisen",assignPartialMismatchMessage:'Das Spulenmaterial "{{spoolMaterial}}" ist ähnlich, stimmt aber nicht genau mit "{{trayMaterial}}" in {{location}} überein. Möchten Sie fortfahren?',assignProfileMismatchMessage:'Das Spulenprofil "{{spoolProfile}}" stimmt nicht mit dem Fachprofil "{{trayProfile}}" in {{location}} überein. Möchten Sie fortfahren?'},timelapse:{title:"Zeitraffer",create:"Zeitraffer erstellen",download:"Herunterladen",delete:"Löschen",preview:"Vorschau",frameRate:"Bildrate",quality:"Qualität",processing:"Wird verarbeitet...",noTimelapses:"Keine Zeitraffer verfügbar"},ams:{title:"AMS",slot:"Slot",empty:"Leer",emptySlot:"Leerer Slot",unknown:"Unbekannt",humidity:"Luftfeuchtigkeit",temperature:"Temperatur",filamentType:"Filamenttyp",filamentColor:"Farbe",remaining:"Verbleibend",history:"AMS-Verlauf",noHistory:"Kein Verlauf verfügbar",configureSlot:"Slot konfigurieren",externalSpool:"Externe Spule",profile:"Profil",kFactor:"K-Faktor",fill:"Füllstand",configure:"Konfigurieren",used:"verwendet",remainingUnit:"verbleibend"},printModal:{title:"Druck starten",selectPrinter:"Drucker auswählen",selectPlate:"Platte auswählen",filamentMapping:"Filamentzuordnung",totalCost:"Gesamtkosten:",slotRemainingShort:" - {{grams}}g übrig",printSettings:"Druckeinstellungen",bedLeveling:"Bett-Nivellierung",flowCalibration:"Fluss-Kalibrierung",vibrationCalibration:"Vibrations-Kalibrierung",layerInspection:"Erste-Schicht-Prüfung",timelapse:"Zeitraffer",startPrint:"Druck starten",addToQueue:"Zur Warteschlange hinzufügen",cancel:"Abbrechen",noPrintersAvailable:"Keine Drucker verfügbar",printerBusy:"Drucker ist beschäftigt",printerOffline:"Drucker ist offline",sameTypeDifferentColor:"Gleicher Typ, andere Farbe",filamentTypeNotLoaded:"Filamenttyp nicht geladen",openCalendar:"Kalender öffnen",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Linke Düse",rightNozzleTooltip:"Rechte Düse",filamentOverride:"Filament-Überschreibung",filamentOverrideHint:"Filamente für modellbasierte Zuweisung optional überschreiben. Der Planer wird gegen die ausgewählten Filamente statt der ursprünglichen 3MF-Werte abgleichen.",originalFilament:"Original",overrideWith:"Ersetzen mit",resetToOriginal:"Auf Original zurücksetzen",insufficientFilamentTitle:"Nicht genug Filament",insufficientFilamentMessage:"Einige zugewiesene Spulen haben weniger Filament als dieser Druck benötigt:",insufficientFilamentLine:"{{printer}} - {{slot}}: benötigt {{required}}g, verbleibend {{remaining}}g",printAnyway:"Trotzdem drucken",forceColorMatch:"Farbe erzwingen",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Gestaffelt an {{count}} Drucker senden",gcodeInjection:"Auto-Print G-code einfügen"},backup:{title:"Sichern & Wiederherstellen",createBackup:"Sicherung erstellen",restoreBackup:"Sicherung wiederherstellen",restoreDescription:"Alle Daten aus einer Sicherungsdatei ersetzen",downloadBackup:"Sicherung herunterladen",uploadBackup:"Sicherung hochladen",lastBackup:"Letzte Sicherung",autoBackup:"Automatische Sicherung",backupNow:"Jetzt sichern",restoreWarning:"Warnung: Das Wiederherstellen einer Sicherung überschreibt alle aktuellen Daten.",includeArchives:"Archive einschließen",includeSettings:"Einstellungen einschließen",includeProfiles:"Profile einschließen",backupSuccess:"Sicherung erfolgreich erstellt",restoreSuccess:"Sicherung erfolgreich wiederhergestellt",backupFailed:"Sicherung fehlgeschlagen",restoreFailed:"Wiederherstellung fehlgeschlagen",restoreNote:"Virtueller Drucker wird während der Wiederherstellung gestoppt",githubBackup:"GitHub Backup",enabled:"Aktiviert",cloudLoginRequired:"Bambu Cloud Login erforderlich. Melden Sie sich unter Profile → Cloud-Profile an, um GitHub-Backup zu aktivieren.",cloudLoginRequiredShort:"Cloud-Login erforderlich",githubDescription:"Synchronisieren Sie Ihre Profile automatisch mit einem privaten GitHub-Repository für Backup und Versionsverlauf.",repositoryUrl:"Repository-URL",personalAccessToken:"Persönlicher Zugriffstoken",tokenSaved:"(gespeichert)",enterNewToken:"Neuen Token eingeben zum Aktualisieren",tokenHint:"Feingranularer Token mit Lese-/Schreibberechtigung für Inhalte",branch:"Branch",manualOnly:"Nur manuell",hourly:"Stündlich",daily:"Täglich",weekly:"Wöchentlich",includeInBackup:"In Sicherung einschließen",kProfiles:"K-Profile",kProfilesDescription:"Druckvorschub-Kalibrierung von verbundenen Druckern",noPrintersConnected:"Keine Drucker verbunden",printersConnected:"{{connected}}/{{total}} verbunden",cloudProfiles:"Cloud-Profile",cloudProfilesDescription:"Filament-, Drucker- und Prozessprofile aus der Bambu Cloud",appSettings:"App-Einstellungen",appSettingsDescription:"Bambuddy-Konfiguration (komplette Datenbank)",spoolInventory:"Spulenbestand",spoolInventoryDescription:"Filamentspulen, Nutzungsverlauf und Kostenverfolgung",printArchives:"Druckarchive",printArchivesDescription:"Druckverlauf-Metadaten (keine GCode/3MF-Dateien)",lastBackupAt:"Letzte Sicherung:",noBackupsYet:"Noch keine Sicherungen",next:"Nächste:",startingBackup:"Sicherung wird gestartet...",test:"Test",enableBackup:"Sicherung aktivieren",testConnection:"Verbindung testen",enterRepoUrl:"Repository-URL eingeben",enterRepoAndToken:"Repository-URL und Zugriffstoken eingeben",repoRequired:"Repository-URL ist erforderlich",tokenRequired:"Zugriffstoken ist erforderlich",githubBackupEnabled:"GitHub-Backup aktiviert",tokenUpdated:"Token aktualisiert",settingsSaved:"Einstellungen gespeichert",failedToSave:"Speichern fehlgeschlagen: {{message}}",backupCompleteFiles:"Sicherung abgeschlossen - {{count}} Dateien aktualisiert",backupSkippedNoChanges:"Sicherung übersprungen - keine Änderungen",backupFailed2:"Sicherung fehlgeschlagen: {{message}}",clearedLogs:"{{count}} Protokolle gelöscht",failedToClearLogs:"Protokolle löschen fehlgeschlagen: {{message}}",history:"Verlauf",clear:"Löschen",date:"Datum",status:"Status",commit:"Commit",localBackup:"Lokale Sicherung",localBackupDescription:"Erstellen Sie eine vollständige Sicherung Ihrer Bambuddy-Daten einschließlich Datenbank, Archive, Uploads und aller Dateien.",downloadBackupLabel:"Sicherung herunterladen",completeBackupZip:"Vollständige Sicherung: Datenbank + alle Dateien (ZIP)",download:"Herunterladen",preparingBackup:"Sicherung wird vorbereitet...",creatingArchive:"Sicherungsarchiv wird erstellt... Dies kann bei großen Archiven eine Weile dauern.",downloadingFile:"Sicherungsdatei wird heruntergeladen...",backupDownloaded:"Sicherung erfolgreich heruntergeladen",failedToCreateBackup:"Sicherung erstellen fehlgeschlagen: {{message}}",restore:"Wiederherstellen",restoreReplacesAll:"Wiederherstellung ersetzt alle Daten.",restoreReplacesAllDetail:"Ihre aktuelle Datenbank und Dateien werden vollständig ersetzt. Nach der Wiederherstellung ist ein Neustart erforderlich.",restoreConfirmTitle:"Sicherung wiederherstellen",restoreConfirmMessage:'Sind Sie sicher, dass Sie von "{{filename}}" wiederherstellen möchten? Dies ersetzt Ihre aktuelle Datenbank und alle Dateien vollständig. Die Anwendung muss nach der Wiederherstellung neu gestartet werden.',restoreConfirmButton:"Sicherung wiederherstellen",uploadingFile:"Sicherungsdatei wird hochgeladen...",backupRestoredRestart:"Sicherung wiederhergestellt. Bitte starten Sie Bambuddy neu.",failedToRestore:"Sicherung wiederherstellen fehlgeschlagen. Bitte überprüfen Sie das Dateiformat.",reloadNow:"Jetzt neu laden",creatingBackup:"Sicherung erstellen",restoringBackup:"Sicherung wiederherstellen",preparing:"Vorbereiten...",processing:"Verarbeiten...",doNotClosePage:"Bitte schließen Sie diese Seite nicht und navigieren Sie nicht weg. Dieser Vorgang kann bei großen Sicherungen mehrere Minuten dauern.",restoring:"Wiederherstellen...",restoreComplete:"Wiederherstellung abgeschlossen",restoreFailed2:"Wiederherstellung fehlgeschlagen",importSettings:"Einstellungen aus einer Sicherungsdatei importieren",pleaseWaitRestoring:"Bitte warten Sie, während Ihre Daten wiederhergestellt werden",selectBackupFile:"Klicken Sie, um eine Sicherungsdatei auszuwählen (.json oder .zip)",duplicateHandling:"So funktioniert die Duplikatbehandlung:",matchPrinters:"Drucker",matchPrintersBy:"abgeglichen nach Seriennummer",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"abgeglichen nach IP-Adresse",matchNotificationProviders:"Benachrichtigungsanbieter",matchNotificationProvidersBy:"abgeglichen nach Name",matchFilaments:"Filamente",matchFilamentsBy:"abgeglichen nach Name + Typ + Marke",matchArchives:"Archive",matchArchivesBy:"abgeglichen nach Inhaltshash (immer übersprungen)",matchPendingUploads:"Ausstehende Uploads",matchPendingUploadsBy:"abgeglichen nach Dateiname",matchSettingsTemplates:"Einstellungen & Vorlagen",matchSettingsTemplatesBy:"immer überschrieben",replaceExisting:"Vorhandene Daten ersetzen",keepExisting:"Vorhandene Daten behalten",overwriteDescription:"Bereits vorhandene Elemente mit Sicherungsdaten überschreiben",keepDescription:"Nur Elemente wiederherstellen, die noch nicht vorhanden sind",overwriteCaution:"Achtung:",overwriteWarning:"Das Überschreiben ersetzt Ihre aktuellen Konfigurationen durch Daten aus der Sicherung. Drucker-Zugangscodes werden aus Sicherheitsgründen nie überschrieben.",cancel:"Abbrechen",processingBackup:"Sicherungsdatei wird verarbeitet...",itemsRestored:"Wiederhergestellt",itemsSkipped:"Übersprungen",restored:"Wiederhergestellt",skippedAlreadyExist:"Übersprungen (bereits vorhanden)",filesCategory:"Dateien (3MF, Thumbnails, etc.)",andMore:"...und {{count}} weitere",newApiKeysGenerated:"Neue API-Schlüssel generiert",keysShownOnce:"Diese Schlüssel werden nur einmal angezeigt. Kopieren Sie sie jetzt!",copy:"Kopieren",noDataFound:"In der Sicherungsdatei wurden keine Daten zur Wiederherstellung gefunden.",close:"Schließen",categories:{settings:"Einstellungen",notification_providers:"Benachrichtigungsanbieter",notification_templates:"Benachrichtigungsvorlagen",smart_plugs:"Smart Plugs",printers:"Drucker",filaments:"Filamente",maintenance_types:"Wartungstypen",archives:"Archive",projects:"Projekte",pending_uploads:"Ausstehende Uploads",external_links:"Externe Links",api_keys:"API-Schlüssel"}},tags:{title:"Tags",addTag:"Tag hinzufügen",editTag:"Tag bearbeiten",deleteTag:"Tag löschen",tagName:"Tag-Name",tagColor:"Tag-Farbe",noTags:"Keine Tags",deleteConfirm:"Möchten Sie diesen Tag wirklich löschen?",manageTags:"Tags verwalten"},uploadModal:{title:"3MF-Dateien hochladen",dragDrop:"3MF-Dateien hierher ziehen",or:"oder",browseFiles:"Dateien durchsuchen",extractionInfo:"Das Druckermodell wird automatisch aus den 3MF-Datei-Metadaten extrahiert.",uploaded:"hochgeladen",failed:"fehlgeschlagen",uploading:"Wird hochgeladen...",upload:"Hochladen",uploadFailed:"Hochladen fehlgeschlagen"},editArchive:{title:"Archiv bearbeiten",name:"Name",namePlaceholder:"Druckname",printer:"Drucker",noPrinter:"Kein Drucker",project:"Projekt",noProject:"Kein Projekt",itemsPrinted:"Gedruckte Teile",itemsPrintedHelp:"Anzahl der in diesem Druckauftrag produzierten Teile",notes:"Notizen",notesPlaceholder:"Notizen zu diesem Druck hinzufügen...",externalLink:"Externer Link",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link zu Printables, Thingiverse oder anderer Quelle",tags:"Tags",tagsPlaceholder:"Tags hinzufügen...",addMoreTags:"Weitere Tags hinzufügen...",matchingTags:'Übereinstimmend mit "{{query}}"',existingTags:"Vorhandene Tags",clickToAdd:"(zum Hinzufügen klicken)",status:"Status",failureReason:"Fehlergrund",selectReason:"Grund auswählen...",photos:"Fotos des Druckergebnisses",photosHelp:"Klicken Sie auf + um Fotos Ihres Druckergebnisses hinzuzufügen",printResult:"Druckergebnis",saving:"Wird gespeichert...",failureReasons:{adhesionFailure:"Haftungsfehler",spaghettiDetached:"Spaghetti / Abgelöst",layerShift:"Schichtversatz",cloggedNozzle:"Verstopfte Düse",filamentRunout:"Filament aufgebraucht",warping:"Verformung",stringing:"Fadenziehen",underExtrusion:"Unterextrusion",powerFailure:"Stromausfall",userCancelled:"Vom Benutzer abgebrochen",other:"Sonstiges"},statuses:{completed:"Abgeschlossen",failed:"Fehlgeschlagen",aborted:"Abgebrochen",printing:"Druckt"}},kProfiles:{title:"K-Profile",noPrintersConfigured:"Keine Drucker konfiguriert",addPrinterInSettings:"Fügen Sie einen Drucker in den Einstellungen hinzu, um K-Profile zu verwalten",noActivePrinters:"Keine aktiven Drucker",enablePrinterConnection:"Aktivieren Sie eine Druckerverbindung, um K-Profile anzuzeigen",loadingProfiles:"Lade K-Profile...",printerOffline:"Drucker offline",printerOfflineDesc:"Der ausgewählte Drucker ist nicht verbunden. Schalten Sie ihn ein, um K-Profile anzuzeigen.",noMatchingProfiles:"Keine passenden Profile",noMatchingProfilesDesc:"Keine Profile entsprechen Ihren Suchkriterien",noKProfiles:"Keine K-Profile",noKProfilesDesc:"Keine Druckvorschub-Profile für {{diameter}}mm Düse gefunden",createFirstProfile:"Erstes Profil erstellen",printer:"Drucker",nozzle:"Düse",refresh:"Aktualisieren",addProfile:"Profil hinzufügen",export:"Exportieren",import:"Importieren",select:"Auswählen",selectAll:"Alle auswählen",delete:"Löschen",searchPlaceholder:"Nach Name oder Filament suchen...",allExtruders:"Alle Extruder",leftOnly:"Nur links",rightOnly:"Nur rechts",allFlow:"Alle Flusstypen",hfOnly:"Nur HF",sOnly:"Nur S",sortName:"Sortieren: Name",sortKValue:"Sortieren: K-Wert",sortFilament:"Sortieren: Filament",leftExtruder:"Linker Extruder",rightExtruder:"Rechter Extruder",modal:{addTitle:"K-Profil hinzufügen",editTitle:"K-Profil bearbeiten",profileName:"Profilname",profileNamePlaceholder:"Mein PLA-Profil",kValue:"K-Wert",kValuePlaceholder:"0,020",kValueHelp:"Typischer Bereich: 0,01 - 0,06 für PLA, 0,02 - 0,10 für PETG",filament:"Filament",selectFilament:"Filament auswählen...",noFilamentsHelp:"Keine Filamente gefunden. Erstellen Sie zuerst ein K-Profil in Bambu Studio.",flowType:"Flusstyp",highFlow:"High Flow",standard:"Standard",nozzleSize:"Düsengröße",extruder:"Extruder",extruders:"Extruder",left:"Links",right:"Rechts",notes:"Notizen (lokal gespeichert)",notesPlaceholder:"Notizen zu diesem Profil hinzufügen...",notesHelp:"Notizen werden in Bambuddy gespeichert, nicht auf dem Drucker",syncing:"Synchronisiert mit Drucker...",savingExtruder:"Speichern auf Extruder {{current}}/{{total}}...",pleaseWait:"Bitte warten"},deleteConfirm:{title:"Profil löschen",cannotUndo:"Dies kann nicht rückgängig gemacht werden",message:'Möchten Sie "{{name}}" wirklich vom Drucker löschen?'},bulkDelete:{title:"Profile löschen",cannotUndo:"Dies kann nicht rückgängig gemacht werden",message:"Möchten Sie wirklich {{count}} ausgewählte Profile vom Drucker löschen?"},toast:{profileSaved:"K-Profil gespeichert",profilesSaved:"K-Profil auf {{count}} Extrudern gespeichert",selectAtLeastOneExtruder:"Bitte wählen Sie mindestens einen Extruder aus",profileDeleted:"K-Profil gelöscht",profilesDeleted:"{{count}} Profile gelöscht",exportedProfiles:"{{count}} Profile exportiert",importedProfiles:"{{count}} von {{total}} Profilen importiert",noProfilesToExport:"Keine Profile zum Exportieren",invalidFileFormat:"Ungültiges Dateiformat",failedToParseImport:"Import-Datei konnte nicht gelesen werden",failedToSaveBatch:"K-Profile konnten nicht gespeichert werden",noteSaved:"Notiz gespeichert",failedToSaveNote:"Notiz konnte nicht gespeichert werden"},permission:{noRead:"Sie haben keine Berechtigung, Profile zu aktualisieren",noCreate:"Sie haben keine Berechtigung, Profile hinzuzufügen",noUpdate:"Sie haben keine Berechtigung, K-Profile zu aktualisieren",noDelete:"Sie haben keine Berechtigung, K-Profile zu löschen",noExport:"Sie haben keine Berechtigung, Profile zu exportieren",noImport:"Sie haben keine Berechtigung, Profile zu importieren"}},virtualPrinter:{title:"Virtueller Drucker",running:"Läuft",stopped:"Gestoppt",description:{default:"Aktiviere einen virtuellen Drucker, der in Bambu Studio und OrcaSlicer erscheint. Dateien, die an diesen Drucker gesendet werden, werden direkt archiviert ohne zu drucken.",proxy:"Aktiviere einen Proxy, der Slicer-Datenverkehr an einen echten Drucker weiterleitet, um Ferndruck über jedes Netzwerk zu ermöglichen."},enable:{title:"Virtuellen Drucker aktivieren",visibleInSlicer:'Sichtbar als "Bambuddy" in der Slicer-Erkennung',proxyingTo:"Proxy zu {{name}}",notActive:"Nicht aktiv"},model:{title:"Druckermodell",description:"Wähle welches Druckermodell emuliert werden soll.",restartWarning:"Das Ändern des Modells startet den virtuellen Drucker neu"},accessCode:{title:"Zugangscode",isSet:"Zugangscode ist gesetzt",notSet:"Kein Zugangscode gesetzt - erforderlich zum Aktivieren",placeholder:"8-Zeichen-Code eingeben",placeholderChange:"Neuen Code eingeben zum Ändern",hint:"Muss genau 8 Zeichen lang sein. Wird von Slicern zur Authentifizierung verwendet.",charCount:"({{count}}/8)"},targetPrinter:{title:"Zieldrucker",configured:"Proxy-Ziel konfiguriert",notConfigured:"Kein Zieldrucker ausgewählt - erforderlich für Proxy-Modus",placeholder:"Drucker auswählen...",hint:"Wähle den Drucker aus, an den der Slicer-Datenverkehr weitergeleitet werden soll. Der Drucker muss im LAN-Modus sein.",noPrinters:"Keine Drucker konfiguriert. Füge zuerst einen Drucker hinzu, um den Proxy-Modus zu verwenden."},remoteInterface:{title:"Netzwerkschnittstelle überschreiben",configured:"Schnittstellenüberschreibung aktiv",optional:"Optional - verwenden wenn die automatisch erkannte IP falsch ist (z.B. mehrere NICs, Docker, VPN)",placeholder:"Automatisch erkennen (Standard)...",hint:"Überschreibt die per SSDP beworbene und im TLS-Zertifikat verwendete IP-Adresse. Nützlich wenn Bambuddy mehrere Netzwerkschnittstellen hat."},mode:{title:"Modus",archive:"Archivieren",archiveDesc:"Dateien sofort archivieren",review:"Überprüfen",reviewDesc:"Vor dem Archivieren überprüfen",queue:"Warteschlange",queueDesc:"Archivieren und zur Warteschlange hinzufügen",proxy:"Proxy",proxyDesc:"An echten Drucker weiterleiten"},autoDispatch:{title:"Automatisch starten",description:"Drucke automatisch starten, wenn sie zur Warteschlange hinzugefügt werden. Wenn deaktiviert, warten Drucke auf manuellen Start."},setupRequired:{title:"Einrichtung erforderlich",description:"Die virtuelle Druckerfunktion erfordert zusätzliche Systemkonfiguration, bevor sie funktioniert. Dies beinhaltet Portweiterleitung, Firewall-Regeln und plattformspezifische Einstellungen.",readGuide:"Lese die Einrichtungsanleitung vor dem Aktivieren"},howItWorks:{title:"So funktioniert es",step1:"Im selben LAN erscheinen virtuelle Drucker automatisch in deinem Slicer (Bambu Studio / OrcaSlicer). Aus anderen Netzwerken füge sie manuell per IP-Adresse und Zugangscode hinzu.",step2:'Im Archiv-, Überprüfungs- und Warteschlangen-Modus verwende die "Senden"-Funktion im Slicer, um 3MF-Dateien an Bambuddy zu senden. Der Slicer zeigt "Druck erfolgreich" — die Datei wird gespeichert, nicht gedruckt.',step3:"Im Proxy-Modus leitet der virtuelle Drucker den gesamten Datenverkehr an einen echten Drucker weiter — Drucke starten sofort wie bei einer direkten Verbindung."},status:{title:"Status-Details",printerName:"Druckername",model:"Modell",serialNumber:"Seriennummer",mode:"Modus",pendingFiles:"Ausstehende Dateien",targetPrinter:"Zieldrucker",ftpPort:"FTP-Port",mqttPort:"MQTT-Port",ftpConnections:"FTP-Verbindungen",mqttConnections:"MQTT-Verbindungen"},toast:{updated:"Virtuelle Druckereinstellungen aktualisiert",failedToUpdate:"Einstellungen konnten nicht aktualisiert werden",accessCodeRequired:"Bitte zuerst einen Zugangscode setzen",targetPrinterRequired:"Bitte zuerst einen Zieldrucker auswählen",bindIpRequired:"Bitte zuerst eine Bind-IP setzen",accessCodeEmpty:"Zugangscode darf nicht leer sein",accessCodeLength:"Zugangscode muss genau 8 Zeichen lang sein",created:"Virtueller Drucker erstellt",failedToCreate:"Virtueller Drucker konnte nicht erstellt werden",deleted:"Virtueller Drucker gelöscht",failedToDelete:"Virtueller Drucker konnte nicht gelöscht werden"},list:{title:"Virtuelle Drucker",add:"Hinzufügen",addFirst:"Virtuellen Drucker hinzufügen",empty:"Keine virtuellen Drucker konfiguriert. Fügen Sie einen hinzu, um zu beginnen."},bindIp:{title:"Bind-Interface",placeholder:"Interface auswählen...",hint:"Netzwerkinterface, an das dieser virtuelle Drucker gebunden wird. Muss pro Drucker eindeutig sein."},proxy:{accessCodeHint:"Im Proxy-Modus den Zugangscode des Zieldruckers im Slicer verwenden. Die Verbindung wird transparent zum echten Drucker weitergeleitet."},addDialog:{title:"Virtuellen Drucker hinzufügen",name:"Name",hint:"Sie können Zugangscode, Zieldrucker und andere Einstellungen nach dem Erstellen konfigurieren.",create:"Erstellen"},deleteConfirm:{title:"Virtuellen Drucker löschen",message:'Möchten Sie "{{name}}" wirklich löschen? Dies stoppt alle Dienste für diesen Drucker.'}},modelViewer:{openInSlicer:"Im Slicer öffnen",tabs:{model:"3D-Modell",gcode:"G-Code Vorschau"},notAvailable:"nicht verfügbar",notSliced:"nicht geslicet",plates:"Platten",allPlates:"Alle Platten",plateNumber:"Platte {{number}}",plateCount:"{{count}} Platte",plateCount_other:"{{count}} Platten",objectCount:"{{count}} Objekt",objectCount_other:"{{count}} Objekte",filamentCount:"{{count}} Filament",filamentCount_other:"{{count}} Filamente",eta:"ETA {{minutes}} Min",noPreview:"Keine Vorschau für diese Datei verfügbar",pagination:{pageOf:"Seite {{current}} von {{total}}",prev:"Zurück",next:"Weiter"},errors:{failedToLoad:"Datei konnte nicht geladen werden",noMeshes:"Keine Meshes in 3MF-Datei gefunden",unsupportedFormat:"Nicht unterstütztes Dateiformat"}},maintenanceDescriptions:{lubricateCarbonRods:"Schmiermittel auf Karbonstäbe für sanfte Bewegung auftragen",lubricateRails:"Schmiermittel auf Linearschienen für sanfte Bewegung auftragen",cleanNozzle:"Hotend und Düse reinigen, um Verstopfungen zu verhindern",checkBelts:"Riemenspannung für präzise Drucke überprüfen",cleanBuildPlate:"Druckplatte für bessere Haftung reinigen",checkExtruder:"Extruderzahnräder auf Verschleiß prüfen",checkCooling:"Sicherstellen, dass Lüfter ordnungsgemäß funktionieren",generalInspection:"Allgemeine Druckerinspektion",cleanCarbonRods:"Karbonstäbe reinigen, um Reibung zu reduzieren",lubricateSteelRods:"Schmiermittel auf Stahlstangen für sanfte Bewegung auftragen",cleanSteelRods:"Stahlstangen reinigen, um Reibung zu reduzieren",cleanLinearRails:"Linearschienen abwischen, um Staub und Schmutz zu entfernen",checkPtfeTube:"PTFE-Schlauch auf Verschleiß oder Beschädigung prüfen",replaceHepaFilter:"HEPA-Filter für Luftqualität ersetzen",replaceCarbonFilter:"Aktivkohlefilter ersetzen",lubricateLeftNozzleRail:"Linke Düsenschiene schmieren (H2-Serie)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Plug-Admin-Seite öffnen",deleteSmartPlug:"Smart Plug löschen",turnOnSmartPlug:"Smart Plug einschalten",turnOffSmartPlug:"Smart Plug ausschalten",turnOn:"Einschalten",turnOff:"Ausschalten",addSmartPlug:{scanningNetwork:"Netzwerk wird durchsucht...",chooseEntity:"Entität auswählen...",connectionFailed:"Verbindung fehlgeschlagen",searchEntities:"Entitäten suchen...",searchPowerSensors:"Leistungssensoren suchen...",searchEnergySensors:"Energiesensoren suchen...",placeholders:{plugName:"Wohnzimmer Steckdose",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Gleich wie Leistungs-Topic oder anders"}},linkedTo:"Verbunden mit:",monitorOnly:"Nur Überwachung",alerts:"Alarme",scheduleOn:"Ein {{time}}",scheduleOff:"Aus {{time}}",on:"Ein",off:"Aus",power:"Leistung",kwhToday:"kWh Heute",settings:"Einstellungen",automationSettings:"Automatisierungseinstellungen",showInSwitchbar:"In Schaltleiste anzeigen",quickAccessSidebar:"Schnellzugriff über Seitenleiste",enabled:"Aktiviert",enableAutomation:"Automatisierung für diesen Stecker aktivieren",autoOn:"Auto Ein",autoOnDescription:"Einschalten wenn Druck startet",autoOff:"Auto Aus",autoOffDescription:"Ausschalten wenn Druck abgeschlossen (einmalig)",autoOffPersistent:"Aktiviert lassen",autoOffPersistentDescription:"Zwischen Drucken aktiviert bleiben statt einmalig",turnOffDelayMode:"Ausschaltverzögerungsmodus",time:"Zeit",temp:"Temp",delayMinutes:"Verzögerung (Minuten)",tempThreshold:"Temperaturschwelle (°C)",tempThresholdDescription:"Schaltet aus wenn die Düse unter diese Temperatur abkühlt",edit:"Bearbeiten",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen? Dies kann nicht rückgängig gemacht werden.',turnOnConfirm:'Möchten Sie "{{name}}" wirklich einschalten?',turnOffConfirm:'Möchten Sie "{{name}}" wirklich ausschalten? Dies unterbricht die Stromversorgung des angeschlossenen Geräts.',failedToTurn:'{{name}}" konnte nicht {{action}} werden',unknown:"Unbekannt",addTitle:"Smart Plug hinzufügen",editTitle:"Smart Plug bearbeiten",stopScanning:"Suche beenden",discoverTasmota:"Tasmota Geräte suchen",foundDevices:"{{count}} Gerät(e) gefunden - zum Auswählen klicken:",noDevicesFound:"Keine Tasmota Geräte in Ihrem Netzwerk gefunden",haNotConfigured:"Home Assistant ist nicht konfiguriert. Einrichtung unter",haSettingsPath:"Einstellungen → Netzwerk → Home Assistant",selectEntity:"Entität auswählen *",ipAddress:"IP-Adresse *",nameLabel:"Name *",username:"Benutzername",password:"Passwort",authHint:"Leer lassen, wenn Ihr Tasmota-Gerät keine Authentifizierung benötigt",linkToPrinter:"Mit Drucker verbinden",noPrinter:"Kein Drucker (nur manuelle Steuerung)",linkingDescription:"Verknüpfung ermöglicht automatisches Ein-/Ausschalten bei Druckstart/-ende",powerAlerts:"Leistungsalarme",alertAbove:"Alarm wenn über (W)",alertBelow:"Alarm wenn unter (W)",alertDescription:"Benachrichtigung wenn der Stromverbrauch diese Schwellenwerte überschreitet. Leer lassen um diese Richtung zu deaktivieren.",dailySchedule:"Tagesplan",turnOnAt:"Einschalten um",turnOffAt:"Ausschalten um",scheduleDescription:"Den Stecker automatisch täglich zu diesen Zeiten ein-/ausschalten. Leer lassen um diese Aktion zu überspringen.",showOnPrinterCard:"Auf Druckerkarte anzeigen",displayOnPrinterCard:"Schaltfläche auf Druckerkarte anzeigen",connectedResult:"Verbunden!",deviceLabel:"Gerät: {{name}} - ",stateLabel:"Status: {{state}}",test:"Test",delete:"Löschen",save:"Speichern",add:"Hinzufügen",cancel:"Abbrechen",failedToStartScan:"Suche konnte nicht gestartet werden",nameRequired:"Name ist erforderlich",entityRequired:"Entität ist für Home Assistant Stecker erforderlich",mqttTopicRequired:"Mindestens ein MQTT-Topic muss für Leistung, Energie oder Statusüberwachung konfiguriert sein",loadingEntities:"Entitäten werden geladen...",loading:"Laden...",failedToLoadEntities:"Entitäten konnten nicht geladen werden: {{error}}",noEntitiesMatching:'Keine Entitäten gefunden die "{{search}}" entsprechen',noEntitiesAvailable:"Keine Entitäten verfügbar",searchingEntities:"Alle Entitäten durchsuchen ({{count}} gefunden)",showingEntities:"Zeige switch, light, input_boolean ({{count}} verfügbar)",energyMonitoringOptional:"Energieüberwachung (Optional)",energyMonitoringHint:"Sensoren suchen und auswählen, die Leistungs-/Energiedaten liefern.",powerSensorW:"Leistungssensor (W)",energyTodayKwh:"Energie Heute (kWh)",totalEnergyKwh:"Gesamtenergie (kWh)",noMatchingSensors:"Keine passenden Sensoren",none:"Keine",mqttNotConfigured:"MQTT-Broker nicht konfiguriert. Broker-Adresse einstellen unter",mqttSettingsPath:"Einstellungen → Netzwerk → MQTT-Veröffentlichung",mqttNotConfiguredSuffix:"(Sie müssen die Veröffentlichung nicht aktivieren, nur die Broker-Details ausfüllen).",mqttMonitorOnlyDescription:"MQTT-Stecker empfangen Leistungs-/Energiedaten über MQTT-Abonnement. Ein-/Ausschalten ist nicht verfügbar - verwenden Sie Ihren MQTT-Broker oder Ihr Home-Automation-System.",powerMonitoring:"Leistungsüberwachung",energyMonitoring:"Energieüberwachung",stateMonitoring:"Statusüberwachung",optional:"optional",topic:"Topic",jsonPath:"JSON-Pfad",multiplier:"Multiplikator",onValue:"EIN-Wert",mqttPowerHint:`JSON-Pfad extrahiert Wert aus JSON-Payload (z.B. "power_l1"). Leer lassen wenn Topic rohe numerische Werte sendet.
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"Power URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"Power Multiplikator",restEnergyUrl:"Energie URL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Energie Multiplikator",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"Eigene URL für Leistungsdaten (nutzt Status URL wenn leer)",restEnergyUrlHint:"Eigene URL für Energiedaten (nutzt Status URL wenn leer)",restEnergyHint:"Jeder Wert kann eine eigene URL verwenden oder auf die Status URL zurückgreifen. Multiplikatoren für Einheitenumrechnung verwenden (z.B. 0.001 für Wh zu kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Keine Schalter in der Schaltleiste",enableSwitchbarHint:'"In Schaltleiste anzeigen" unter Einstellungen > Smart Plugs aktivieren'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-Mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTP-E-Mail-Benachrichtigungen",telegram:"Benachrichtigungen über Telegram-Bot",discord:"An Discord-Kanal per Webhook senden",ntfy:"Kostenlose, selbst-hostbare Push-Benachrichtigungen",pushover:"Einfache, zuverlässige Push-Benachrichtigungen",callmebot:"Kostenlose WhatsApp-Benachrichtigungen über CallMeBot",webhook:"Generischer HTTP-POST an beliebige URL",homeassistant:"Dauerhafte Benachrichtigungen im Home Assistant Dashboard"},lastSuccess:"Zuletzt: {{date}}",error:"Fehler",printer:"Drucker:",allPrinters:"Alle Drucker",sendTestNotification:"Testbenachrichtigung senden",eventSettings:"Ereigniseinstellungen",enabled:"Aktiviert",sendFromProvider:"Benachrichtigungen von diesem Anbieter senden",printEvents:"Druckereignisse",printerStatus:"Druckerstatus",amsAlarms:"AMS-Alarme",amsHtAlarms:"AMS-HT-Alarme",printQueue:"Druckwarteschlange",start:"Start",plateCheck:"Plattenkontrolle",complete:"Abgeschlossen",failed:"Fehlgeschlagen",stopped:"Gestoppt",progress:"Fortschritt",offline:"Offline",lowFilament:"Filament niedrig",maintenance:"Wartung",amsHumidity:"AMS-Feuchtigkeit",amsTemp:"AMS-Temperatur",amsHtHumidity:"AMS-HT-Feuchtigkeit",amsHtTemp:"AMS-HT-Temperatur",bedCooled:"Bett abgekühlt",firstLayer:"Erste Schicht",quiet:"Ruhe",digest:"Zusammenfassung {{time}}",printStarted:"Druck gestartet",plateNotEmpty:"Platte nicht leer",plateNotEmptyDescription:"Objekte vor dem Druck erkannt",printCompleted:"Druck abgeschlossen",bedCooledLabel:"Bett abgekühlt",bedCooledDescription:"Bett nach dem Druck unter Schwellenwert abgekühlt",firstLayerCompleteLabel:"Erste Schicht fertig",firstLayerCompleteDescription:"Benachrichtigung mit Foto nach erster Schicht",missingSpoolAssignmentLabel:"Fehlende Spulenzuordnung",missingSpoolAssignmentDescription:"Benachrichtigen, wenn ein Druck startet und benoetigte Schaechte keine zugeordnete Spule haben",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",progressMilestones:"Fortschrittsmeilensteine",progressMilestonesDescription:"Benachrichtigung bei 25%, 50%, 75%",printerOffline:"Drucker offline",printerError:"Druckerfehler",lowFilamentLabel:"Filament niedrig",maintenanceDue:"Wartung fällig",maintenanceDueDescription:"Benachrichtigen, wenn Wartung erforderlich ist",amsHumidityHigh:"AMS-Feuchtigkeit hoch",amsHumidityHighDescription:"Normale AMS-Feuchtigkeit überschreitet Schwellenwert",amsTemperatureHigh:"AMS-Temperatur hoch",amsTemperatureHighDescription:"Normale AMS-Temperatur überschreitet Schwellenwert",amsHtHumidityHigh:"AMS-HT-Feuchtigkeit hoch",amsHtHumidityHighDescription:"AMS-HT-Feuchtigkeit überschreitet Schwellenwert",amsHtTemperatureHigh:"AMS-HT-Temperatur hoch",amsHtTemperatureHighDescription:"AMS-HT-Temperatur überschreitet Schwellenwert",jobAdded:"Auftrag hinzugefügt",jobAddedDescription:"Auftrag zur Warteschlange hinzugefügt",jobAssigned:"Auftrag zugewiesen",jobAssignedDescription:"Modellbasierter Auftrag einem Drucker zugewiesen",jobStarted:"Auftrag gestartet",jobStartedDescription:"Warteschlangenauftrag hat Druck begonnen",jobWaiting:"Auftrag wartet",jobWaitingDescription:"Auftrag wartet auf Filament oder Drucker",jobSkipped:"Auftrag übersprungen",jobSkippedDescription:"Auftrag übersprungen (vorheriger fehlgeschlagen)",jobFailed:"Auftrag fehlgeschlagen",jobFailedDescription:"Auftrag konnte nicht gestartet werden",queueComplete:"Warteschlange abgeschlossen",queueCompleteDescription:"Alle Warteschlangenaufträge beendet",quietHours:"Ruhezeiten",noNotificationsDuring:"Keine Benachrichtigungen während dieser Zeiten",editProviderToChangeQuietHours:"Anbieter bearbeiten, um Ruhezeiten zu ändern",dailyDigest:"Tägliche Zusammenfassung",batchNotifications:"Benachrichtigungen zu einer täglichen Zusammenfassung bündeln",sendAt:"Senden um {{time}}",editProviderToChangeDigestTime:"Anbieter bearbeiten, um Zusammenfassungszeit zu ändern",edit:"Bearbeiten",deleteProvider:"Benachrichtigungsanbieter löschen",deleteConfirm:'Sind Sie sicher, dass Sie "{{name}}" löschen möchten? Dies kann nicht rückgängig gemacht werden.',delete:"Löschen",addTitle:"Benachrichtigungsanbieter hinzufügen",editTitle:"Benachrichtigungsanbieter bearbeiten",nameLabel:"Name *",namePlaceholder:"Meine Benachrichtigungen",providerTypeLabel:"Anbietertyp *",configuration:"Konfiguration",testConfiguration:"Konfiguration testen",printerFilter:"Druckerfilter",onlyFromPrinter:"Nur Benachrichtigungen für Ereignisse von diesem Drucker senden",quietHoursDnd:"Ruhezeiten (Nicht stören)",quietStart:"Start",quietEnd:"Ende",dailyDigestLabel:"Tägliche Zusammenfassung",sendDigestAt:"Zusammenfassung senden um",digestCollected:"Ereignisse werden gesammelt und als einzelne Zusammenfassung zu dieser Zeit gesendet",notificationEvents:"Benachrichtigungsereignisse",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(nach Druckabschluss)",cancel:"Abbrechen",save:"Speichern",add:"Hinzufügen",nameRequired:"Name ist erforderlich",fieldRequired:"{{field}} ist erforderlich",phoneNumber:"Telefonnummer",apiKey:"API-Schlüssel",serverUrl:"Server-URL",topic:"Thema",authToken:"Auth-Token",userKey:"Benutzerschlüssel",appToken:"App-Token",priority:"Priorität",botToken:"Bot-Token",chatId:"Chat-ID",smtpServer:"SMTP-Server",smtpPort:"SMTP-Port",security:"Sicherheit",authentication:"Authentifizierung",username:"Benutzername",password:"Passwort",fromEmail:"Absender-E-Mail",toEmail:"Empfänger-E-Mail",webhookUrl:"Webhook-URL",payloadFormat:"Payload-Format",authorization:"Autorisierung",titleFieldName:"Titel-Feldname",messageFieldName:"Nachrichten-Feldname",editTemplate:"Vorlage bearbeiten: {{name}}",titleLabel:"Titel",bodyLabel:"Inhalt",titlePlaceholder:"Benachrichtigungstitel...",bodyPlaceholder:"Benachrichtigungsinhalt...",availableVariables:"Verfügbare Variablen",clickToInsert:"Klicken, um an Cursorposition im Inhalt einzufügen",livePreview:"Live-Vorschau",hide:"Ausblenden",show:"Anzeigen",loadingPreview:"Vorschau wird geladen...",enterTemplateContent:"Vorlageninhalt eingeben, um Vorschau zu sehen",titlePreview:"Titel:",bodyPreview:"Inhalt:",resetToDefault:"Auf Standard zurücksetzen",titleRequired:"Titel ist erforderlich",bodyRequired:"Inhalt ist erforderlich",notificationLog:"Benachrichtigungsprotokoll",showFailedOnly:"Nur fehlgeschlagene",last24Hours:"Letzte 24 Stunden",last7Days:"Letzte 7 Tage",last30Days:"Letzte 30 Tage",last90Days:"Letzte 90 Tage",justNow:"Gerade eben",noFailedNotifications:"Keine fehlgeschlagenen Benachrichtigungen",noNotificationsLogged:"Keine Benachrichtigungen protokolliert",unknownProvider:"Unbekannter Anbieter",logTitle:"Titel",logMessage:"Nachricht",logError:"Fehler",logProvider:"Anbieter: {{type}}",logTime:"Zeit: {{time}}",refresh:"Aktualisieren",clearOld:"Alte löschen",statsSummary:"Letzte {{days}} Tage:",statsNotifications:"Benachrichtigungen",statsSent:"{{count}} gesendet",statsFailed:"{{count}} fehlgeschlagen",eventTypes:{print_start:"Druck gestartet",print_complete:"Druck abgeschlossen",print_failed:"Druck fehlgeschlagen",print_stopped:"Druck gestoppt",print_progress:"Fortschritt",printer_offline:"Drucker offline",printer_error:"Druckerfehler",filament_low:"Filament niedrig",maintenance_due:"Wartung fällig",test:"Test"},userEmail:{title:"Benachrichtigungen",emailNotifications:"E-Mail-Benachrichtigungen",emailNotificationsDesc:"Erhalten Sie E-Mail-Benachrichtigungen für Ihre eigenen Druckaufträge. E-Mails werden über die in der erweiterten Authentifizierung konfigurierten SMTP-Einstellungen gesendet.",sendingTo:"Benachrichtigungen werden gesendet an",noEmailWarning:"Ihr Konto hat keine E-Mail-Adresse. Wenden Sie sich an einen Administrator, um eine hinzuzufügen.",printJobNotifications:"Druckauftrags-Benachrichtigungen",printJobNotificationsDesc:"Wählen Sie aus, welche Ereignisse E-Mail-Benachrichtigungen für von Ihnen gesendete Druckaufträge auslösen.",printJobStarts:"Druckauftrag startet",printJobStartsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag beginnt.",printJobFinishes:"Druckauftrag fertig",printJobFinishesDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag erfolgreich abgeschlossen wurde.",printErrors:"Druckfehler",printErrorsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag fehlschlägt oder auf einen Fehler stößt.",printJobStops:"Druckauftrag gestoppt",printJobStopsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag abgebrochen oder gestoppt wird.",saveSuccess:"Benachrichtigungseinstellungen gespeichert.",saveError:"Benachrichtigungseinstellungen konnten nicht gespeichert werden."}},richTextEditor:{bold:"Fett",italic:"Kursiv",underline:"Unterstrichen",bulletList:"Aufzählungsliste",numberedList:"Nummerierte Liste",alignLeft:"Linksbündig",alignCenter:"Zentriert",alignRight:"Rechtsbündig",addLink:"Link hinzufügen",removeLink:"Link entfernen"},externalLinks:{noLinksConfigured:"Keine externen Links konfiguriert",deleteLink:"Link löschen",removeCustomIcon:"Benutzerdefiniertes Symbol entfernen",openInNewTab:"In neuem Tab öffnen",placeholders:{linkName:"Mein Link"}},keyboardShortcuts:{title:"Tastaturkürzel",navigation:"Navigation",archivesSection:"Archive",kProfilesSection:"K-Profile",generalSection:"Allgemein",shortcuts:{goToPrinters:"Zu Drucker gehen",goToArchives:"Zu Archiv gehen",goToQueue:"Zur Warteschlange gehen",goToStats:"Zu Statistiken gehen",goToProfiles:"Zu Cloud-Profilen gehen",goToSettings:"Zu Einstellungen gehen",focusSearch:"Suche fokussieren",openUploadModal:"Upload-Modal öffnen",clearSelection:"Auswahl löschen / Eingabe aufheben",contextMenu:"Kontextmenü auf Karten",refreshProfiles:"Profile aktualisieren",newProfile:"Neues Profil",exitSelectionMode:"Auswahlmodus beenden",showHelp:"Diese Hilfe anzeigen"},footer:"Drücken Sie Esc oder klicken Sie außerhalb, um zu schließen"},notificationLog:{title:"Benachrichtigungsprotokoll",events:{printStarted:"Druck gestartet",printComplete:"Druck abgeschlossen",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",progress:"Fortschritt",printerOffline:"Drucker offline",printerError:"Druckerfehler",lowFilament:"Wenig Filament",maintenanceDue:"Wartung fällig",test:"Test"},timeAgo:{justNow:"Gerade eben",minutesAgo:"vor {{minutes}}m",hoursAgo:"vor {{hours}}h"}},restoreBackup:{title:"Backup wiederherstellen",restoring:"Wird wiederhergestellt...",restoreComplete:"Wiederherstellung abgeschlossen",restoreFailed:"Wiederherstellung fehlgeschlagen",importSettings:"Einstellungen aus Backup-Datei importieren",pleaseWait:"Bitte warten Sie, während Ihre Daten wiederhergestellt werden",clickToSelect:"Klicken Sie, um Backup-Datei auszuwählen (.json oder .zip)",howDuplicateHandling:"So funktioniert die Duplikatbehandlung:",categories:{printers:"Drucker",smartPlugs:"Smart Plugs",notificationProviders:"Benachrichtigungsanbieter",filaments:"Filamente",archives:"Archive",pendingUploads:"Ausstehende Uploads",settingsTemplates:"Einstellungen & Vorlagen"},matchingInfo:{printers:"abgeglichen nach Seriennummer",smartPlugs:"abgeglichen nach IP-Adresse",notificationProviders:"abgeglichen nach Name",filaments:"abgeglichen nach Name + Typ + Marke",archives:"abgeglichen nach Inhalts-Hash",pendingUploads:"abgeglichen nach Dateiname",settingsTemplates:"immer überschrieben"},replaceExisting:"Vorhandene Daten ersetzen",keepExisting:"Vorhandene Daten behalten",replaceDescription:"Bereits vorhandene Elemente mit Backup-Daten überschreiben",keepDescription:"Nur Elemente wiederherstellen, die noch nicht existieren",caution:"Vorsicht:",cautionText:"Das Überschreiben ersetzt Ihre aktuellen Konfigurationen durch Backup-Daten. Drucker-Zugangscodes werden aus Sicherheitsgründen niemals überschrieben.",itemsRestored:"Wiederhergestellte Elemente",itemsSkipped:"Übersprungene Elemente",restored:"Wiederhergestellt",skipped:"Übersprungen (existieren bereits)",filesLabel:"Dateien (3MF, Thumbnails, etc.)",newApiKeysGenerated:"Neue API-Schlüssel generiert",newApiKeysWarning:"Diese Schlüssel werden nur einmal angezeigt. Kopieren Sie sie jetzt!",processingBackup:"Backup-Datei wird verarbeitet...",noDataFound:"In der Backup-Datei wurden keine wiederherzustellenden Daten gefunden.",failedToRestore:"Backup konnte nicht wiederhergestellt werden. Bitte überprüfen Sie das Dateiformat."},backupExport:{title:"Backup exportieren",selectData:"Zu exportierende Daten auswählen",selectAll:"Alle auswählen",selectNone:"Keine auswählen",categoryDescriptions:{settings:"Sprache, Theme, Update-Einstellungen",notifications:"ntfy, Pushover, Discord, usw.",templates:"Benutzerdefinierte Nachrichtenvorlagen",smartPlugs:"Tasmota-Plug-Konfigurationen",externalLinks:"Seitenleiste Links zu externen Diensten",printers:"Druckerinformationen (Zugangscodes ausgeschlossen)",plateDetection:"Leere Platten-Referenzbilder",filaments:"Filamenttypen und -kosten",maintenance:"Benutzerdefinierte Wartungspläne",archives:"Alle Druckdaten + Dateien (3MF, Thumbnails, Fotos)",projects:"Projekte, BOM-Elemente und Anhänge",pendingUploads:"Virtueller Drucker-Uploads zur Überprüfung",apiKeys:"Webhook-API-Schlüssel (neue Schlüssel bei Import generiert)"},requiresPrinters:"Drucker müssen ausgewählt sein",zipFileWarning:"ZIP-Datei wird erstellt.",zipFileDescription:"Enthält alle 3MF-Dateien, Thumbnails, Zeitraffer und Fotos. Dies kann eine Weile dauern und zu einer großen Datei führen.",includeAccessCodes:"Zugangscodes einschließen",includeAccessCodesDescription:"Für die Übertragung auf eine andere Maschine",includeAccessCodesWarning:"Zugangscodes werden im Klartext eingeschlossen. Bewahren Sie diese Backup-Datei sicher auf!",categoriesSelected:"{{selectedCount}} Kategorien ausgewählt"},pendingUploads:{placeholders:{notes:"Notizen zu diesem Druck hinzufügen..."},discardUpload:"Upload verwerfen",archiveAllUploads:"Alle Uploads archivieren",discardAllUploads:"Alle Uploads verwerfen",archive:"Archivieren",timeAgo:{justNow:"Gerade eben",minutesAgo:"vor {{minutes}}m",hoursAgo:"vor {{hours}}h",daysAgo:"vor {{days}}d"}},apiBrowser:{placeholders:{requestBody:"JSON-Anforderungstext...",searchEndpoints:"Endpunkte suchen..."}},configureAmsSlot:{title:"AMS-Slot konfigurieren",slotConfigured:"Slot konfiguriert!",configuringSlot:"Slot wird konfiguriert:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Voreinstellungen suchen...",colorPlaceholder:"Farbname oder Hex (z.B. braun, FF8800)",clearCustomColor:"Benutzerdefinierte Farbe löschen",noCloudPresets:"Keine Cloud-Voreinstellungen. Melden Sie sich bei Bambu Cloud an, um zu synchronisieren.",noPresetsAvailable:"Keine Voreinstellungen verfügbar. Melden Sie sich bei Bambu Cloud an oder importieren Sie lokale Profile.",noMatchingPresets:"Keine passenden Voreinstellungen gefunden.",custom:"Benutzerdefiniert",builtin:"Integriert",settingsSentToPrinter:"Einstellungen an Drucker gesendet",filamentProfile:"Filamentprofil",kProfileLabel:"K-Profil (Pressure Advance)",filteringFor:"Filtern nach: {{material}}",noKProfile:"Kein K-Profil (Standard 0.020 verwenden)",noMatchingKProfiles:"Keine passenden K-Profile gefunden. Standard K=0.020 wird verwendet.",selectFilamentFirst:"Zuerst ein Filamentprofil auswählen",kFromCalibration:"K={{value}} aus Druckerkalibrierung",customColorLabel:"Benutzerdefinierte Farbe (optional)",presetColors:"{{name}} Farben:",showLessColors:"Weniger Farben anzeigen",showMoreColors:"Mehr Farben anzeigen",clear:"Löschen",hexLabel:"Hex: #{{hex}}",resetting:"Wird zurückgesetzt...",resetSlot:"Slot zurücksetzen",cancel:"Abbrechen",configuring:"Wird konfiguriert...",configureSlot:"Slot konfigurieren"},githubBackup:{title:"GitHub-Backup",history:"Verlauf",downloadBackup:"Backup herunterladen",restoreBackup:"Backup wiederherstellen",noBackupsYet:"Noch keine Backups"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Tags suchen...",renameTag:"Tag umbenennen",deleteTag:"Tag löschen"},notificationTemplates:{placeholders:{title:"Benachrichtigungstitel...",body:"Benachrichtigungstext..."}},batchTag:{placeholders:{newTag:"Neuen Tag eingeben..."}},photoGallery:{deletePhoto:"Foto löschen"},filamentHoverCard:{copySpoolUuid:"Spulen-UUID kopieren"},kProfilesView:{hasNote:"Hat Notiz",copyProfile:"Profil kopieren"},layout:{openMenu:"Menü öffnen",noPermissionSystemInfo:"Sie haben keine Berechtigung zum Anzeigen von Systeminformationen"},dashboard:{dragToReorder:"Ziehen zum Neuordnen",hideWidget:"Widget ausblenden"},notificationProviderCard:{deleteNotificationProvider:"Benachrichtigungsanbieter löschen"},fileManagerModal:{closeFileManager:"Dateimanager schließen",sortFiles:"Dateien sortieren",goToParentFolder:"Zum übergeordneten Ordner gehen",threeView:"3D-Ansicht"},embeddedCameraViewer:{refreshStream:"Stream aktualisieren",close:"Schließen",zoomOut:"Verkleinern",resetZoom:"Zoom zurücksetzen",zoomIn:"Vergrößern",dragToResize:"Ziehen zum Größe ändern"},timelapseViewer:{skipBack5s:"5s zurückspringen",skipForward5s:"5s vorspringen"},notificationProviders:{descriptions:{email:"SMTP-E-Mail-Benachrichtigungen",telegram:"Benachrichtigungen über Telegram-Bot",discord:"An Discord-Kanal über Webhook senden",ntfy:"Kostenlose, selbst hostbare Push-Benachrichtigungen",pushover:"Einfache, zuverlässige Push-Benachrichtigungen",callmebot:"Kostenlose WhatsApp-Benachrichtigungen über CallMeBot",webhook:"Generischer HTTP POST zu beliebiger URL"}},logViewer:{searchPlaceholder:"Nachricht oder Logger-Name suchen...",noLogEntries:"Keine Logeinträge gefunden"},switchbarPopover:{noSwitchesInSwitchbar:"Keine Schalter in Schalterleiste"},projectPageModal:{placeholders:{title:"Titel",designer:"Designer",license:"Lizenz",description:"Beschreibung eingeben...",profileTitle:"Profil-Titel",profileDescription:"Profilbeschreibung..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"Wartend",justNow:"Gerade eben",now:"Jetzt",minsAgo:"vor {{count}}m",inMins:"in {{count}}m",hoursAgo:"vor {{count}}h",inHours:"in {{count}}h",daysAgo:"vor {{count}}d",inDays:"in {{count}}d"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventar",writeTag:"Schreiben",settings:"Einstellungen"},status:{nfcReady:"NFC bereit",nfcOff:"NFC aus",offline:"Offline",online:"Online",noPrinters:"Keine Drucker",deviceOffline:"Gerät offline",waitingConnection:"Warte auf Geräteverbindung...",systemReady:"System bereit",status:"Status"},dashboard:{readyToScan:"Bereit zum Scannen",idleMessage:"Spule auf die Waage legen zum Identifizieren",nfcHint:"NFC-Tag wird automatisch gelesen",device:"Gerät",syncWeight:"Gewicht sync.",weightSynced:"Synchronisiert!",unknownTag:"Unbekannter Tag",newTag:"Neuer Tag erkannt",onScale:"auf der Waage",linkSpool:"Mit Spule verknüpfen",linkTagTitle:"Tag mit Spule verknüpfen",linkTag:"Tag verknüpfen",selectSpool:"Spule zum Verknüpfen auswählen:",noUntagged:"Keine Spulen ohne Tags gefunden",tagDetected:"Tag erkannt",noTag:"Kein Tag",tagId:"Tag",grossWeight:"Bruttogewicht",spoolSize:"Spulengröße",close:"Schließen",currentSpool:"Aktuelle Spule"},modal:{spoolDetected:"Spule erkannt",assignToAms:"AMS zuweisen",syncWeight:"Gewicht sync.",weightSynced:"Synchronisiert!",syncing:"Synchronisiere...",newTagDetected:"Neuer Tag erkannt",addToInventory:"Zum Inventar hinzufügen",assignToAmsTitle:"AMS zuweisen",selectSlot:"Slot auswählen",assign:"Zuweisen",assigning:"Zuweisen...",assignSuccess:"Zugewiesen!",assignError:"Fehler beim Zuweisen. Bitte erneut versuchen.",noPrinterSelected:"Drucker auswählen...",noAmsDetected:"Kein AMS an diesem Drucker erkannt",slot:"Slot"},weight:{noReading:"Kein Messwert",stable:"Stabil",measuring:"Messen...",tare:"Tarieren",calibrate:"Kalibrieren"},spool:{remaining:"Verbleibend",material:"Material",brand:"Marke",color:"Farbe",coreWeight:"Kern",labelWeight:"Etikett",scaleWeight:"Waage",netWeight:"Netto",lastUsed:"Zuletzt verwendet"},ams:{noData:"Kein AMS erkannt",connectAms:"AMS anschließen um Filament-Slots zu sehen",noPrinter:"Kein Drucker ausgewählt",selectPrinter:"Drucker in der oberen Leiste auswählen",printerDisconnected:"Drucker getrennt",humidity:"Feuchtigkeit",level:"Stufe",active:"Aktiv",slot:"Slot",empty:"Leer"},inventory:{search:"Spulen suchen...",empty:"Keine Spulen im Inventar",noResults:"Keine passenden Spulen",spools:"Spulen",addSpool:"Spule hinzufügen"},settings:{tabDevice:"Gerät",tabDisplay:"Anzeige",tabScale:"Waage",tabUpdates:"Updates",nfcReader:"NFC-Leser",type:"Typ",connection:"Verbindung",notConnected:"N/A",deviceInfo:"Geräteinfo",hostname:"Host",uptime:"Betriebszeit",systemConfig:"Backend & Auth",backendUrl:"Bambuddy Backend URL",apiToken:"API-Token",apiTokenPlaceholder:"API-Token eingeben",saveConfig:"Konfiguration speichern",systemQueued:"Konfiguration in Warteschlange.",nfcDiagnostic:"NFC-Diagnose",scaleDiagnostic:"Waagen-Diagnose",readTagDiagnostic:"Tag-Lese-Diagnose",testNfc:"Leser testen",testScale:"Genauigkeit testen",testReadTag:"Tag lesen",systemFieldsRequired:"Backend-URL ist erforderlich.",brightness:"Helligkeit",saved:"Gespeichert",noBacklight:"Keine DSI-Hintergrundbeleuchtung erkannt. Helligkeitssteuerung erfordert ein DSI-Display.",screenBlank:"Bildschirm-Abschaltzeit",screenBlankDesc:"Bildschirm schaltet sich nach Inaktivität ab. Zum Aufwecken berühren.",displayNote:"Helligkeit wird als Software-Filter angewendet.",scaleCalibration:"Waagen-Kalibrierung",currentWeight:"Aktuelles Gewicht",tareOffset:"Tara",calFactor:"Faktor",knownWeight:"Bekanntes Gewicht",calStep1:"Alle Gegenstände von der Waage entfernen und Nullpunkt setzen.",calStep2:"Bekanntes Gewicht auf die Waage legen.",setZero:"Nullpunkt setzen",calibrateNow:"Kalibrieren",calibrated:"Kalibriert",tareSet:"Tara-Befehl gesendet. Warte auf Gerät...",tareFailed:"Tara-Befehl fehlgeschlagen",zeroSet:"Nullpunkt gesetzt. Bekanntes Gewicht auf die Waage legen.",calibrationDone:"Kalibrierung abgeschlossen!",calibrationFailed:"Kalibrierung fehlgeschlagen",lastCalibrated:"Zuletzt kalibriert",stable:"Stabil",settling:"Stabilisierung...",firmware:"Firmware",scale:"Waage",noDevice:"Kein SpoolBuddy-Gerät gefunden",daemonVersion:"Daemon-Version",currentVersion:"Aktuell",versionPending:"Warte auf Daemon...",checking:"Prüfe...",checkUpdates:"Nach Updates suchen",updateAvailable:"Update verfügbar",updateInstructions:"Update per SSH: SpoolBuddy-Installationsskript ausführen.",upToDate:"Aktuell",includeBeta:"Beta-Versionen einschließen"},writeTag:{tabExisting:"Vorhandene Spule",tabNew:"Neue Spule",tabReplace:"Tag ersetzen",searchPlaceholder:"Suche nach Material, Farbe, Marke...",noUntaggedSpools:"Keine Spulen ohne Tags",noTaggedSpools:"Keine Spulen mit Tags",selectSpool:"Spule auswählen, dann einen NTAG auf den Leser legen",placeTag:"NTAG auf den Leser legen",tagReady:"Tag erkannt — bereit zum Schreiben",writeTag:"Tag beschreiben",replaceTag:"Tag ersetzen",writing:"Tag wird beschrieben...",waiting:"Warte auf SpoolBuddy...",writeSuccess:"Tag erfolgreich beschrieben!",writeFailed:"Schreiben fehlgeschlagen",queueFailed:"Schreibbefehl konnte nicht eingereiht werden",tryAgain:"Erneut versuchen",cancel:"Abbrechen",replaceWarning:"Alter Tag wird getrennt. Neuer Tag ersetzt ihn.",deviceOffline:"SpoolBuddy ist offline",material:"Material",colorName:"Farbname",color:"Farbe",brand:"Marke",weight:"Gewicht (g)",createSpool:"Spule erstellen",creating:"Wird erstellt...",spoolCreated:"Spule erstellt! Bereit zum Schreiben.",createFailed:"Spule konnte nicht erstellt werden"},quickMenu:{printerPower:"Drucker-Strom",systemControls:"System",restartDaemon:"Daemon neustarten",restartBrowser:"Browser neustarten",reboot:"Neustart",shutdown:"Herunterfahren",swipeToClose:"Nach unten wischen zum Schließen",confirmTitle:"Bestätigen",confirmShutdown:"Möchten Sie das SpoolBuddy wirklich herunterfahren? Sie benötigen physischen Zugang, um es wieder einzuschalten.",confirmReboot:"Möchten Sie das SpoolBuddy wirklich neu starten?",confirmRestartDaemon:"SpoolBuddy-Daemon neustarten? NFC und Waage sind vorübergehend nicht verfügbar.",confirmRestartBrowser:"Kiosk-Browser neustarten? Das Display wird kurz schwarz.",confirm:"Bestätigen",confirmPlugOn:"{{name}} einschalten?",confirmPlugOff:"{{name}} ausschalten?",turnOn:"Einschalten",turnOff:"Ausschalten"}},bugReport:{title:"Fehler melden",description:"Beschreibung",descriptionPlaceholder:"Was ist schiefgelaufen? Bitte beschreiben Sie das Problem...",email:"E-Mail (optional)",emailPlaceholder:"ihre@email.de",emailPrivacy:"Falls angegeben, wird Ihre E-Mail in einem eingeklappten Abschnitt des GitHub-Issues aufgeführt, damit der Betreuer sich melden kann.",screenshot:"Screenshot",uploadOrPaste:"Bild hochladen, einfügen oder ziehen",dataCollectedSummary:"Welche Daten werden im Bericht gesendet?",dataIncluded:"Enthalten:",dataIncludedList:"App-Version, Betriebssystem, Architektur, Python-Version, Datenbankstatistiken (nur Anzahl), Druckermodelle, Düsenanzahl, Firmware-Versionen, Verbindungsstatus, Integrationsstatus (Spoolman, MQTT, HA), nicht-sensible Einstellungen, Netzwerkschnittstellenanzahl, Docker-Details, Abhängigkeitsversionen.",dataNeverIncluded:"Nie enthalten:",dataNeverIncludedList:"Druckernamen, Seriennummern, Zugangscodes, Passwörter, IP-Adressen, E-Mail-Adressen, API-Schlüssel, Tokens, Webhook-URLs, Hostnamen oder Benutzernamen.",submit:"Absenden",startLogging:"Debug-Protokollierung starten",stepEnableLogging:"Debug-Protokollierung aktiviert",stepReproduce:"Problem jetzt reproduzieren",stepStopLogging:"Stoppen & Bericht senden",stopAndSubmit:"Stoppen & Senden",maxDuration:"Stoppt automatisch nach {{minutes}} Min.",stoppingLogs:"Protokolle sammeln & senden...",submitting:"Fehlerbericht wird gesendet...",submitSuccess:"Fehlerbericht erfolgreich gesendet!",submitFailed:"Fehlerbericht konnte nicht gesendet werden",thankYou:"Vielen Dank!",submitted:"Ihr Fehlerbericht wurde eingereicht.",viewIssue:"Issue ansehen",unexpectedError:"Ein unerwarteter Fehler ist aufgetreten"}},kue={nav:{printers:"Imprimantes",archives:"Archives",queue:"File d'attente",stats:"Statistiques",profiles:"Profils",maintenance:"Maintenance",projects:"Projets",inventory:"Filament",files:"Gestionnaire de fichiers",notifications:"Notifications",settings:"Paramètres",system:"Système",collapseSidebar:"Réduire la barre latérale",expandSidebar:"Développer la barre latérale",update:"Mise à jour",updateAvailable:"Mise à jour disponible : v{{version}}",updateAvailableBanner:"La version {{version}} est disponible !",viewUpdate:"Voir la mise à jour",viewOnGithub:"Voir sur GitHub",keyboardShortcuts:"Raccourcis clavier (?)",switchToLight:"Passer au mode clair",switchToDark:"Passer au mode sombre",smartSwitches:"Interrupteurs intelligents",logout:"Déconnexion"},common:{save:"Enregistrer",saving:"Enregistrement...",cancel:"Annuler",delete:"Supprimer",edit:"Modifier",add:"Ajouter",close:"Fermer",confirm:"Confirmer",loading:"Chargement...",error:"Erreur",success:"Succès",warning:"Avertissement",enabled:"Activé",disabled:"Désactivé",yes:"Oui",no:"Non",on:"On",off:"Off",all:"Tous",none:"Aucun",search:"Rechercher",filter:"Filtrer",sort:"Trier",refresh:"Actualiser",download:"Télécharger",upload:"Téléverser",uploading:"Téléversement...",uploadFailed:"Échec du téléversement",actions:"Actions",status:"Statut",name:"Nom",description:"Description",date:"Date",time:"Heure",hours:"heures",minutes:"minutes",seconds:"secondes",days:"jours",enable:"Activer",disable:"Désactiver",permissions:"Autorisations",noPrinters:"Aucune imprimante configurée",noData:"Aucune donnée disponible",linkNotFound:"Lien non trouvé",required:"Requis",optional:"Optionnel",dismiss:"Ignorer",apply:"Appliquer",reset:"Réinitialiser",export:"Exporter",import:"Importer",clear:"Effacer",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",noChange:"— Aucun changement —",unchanged:"Inchangé",unassigned:"Non assigné",unknown:"Inconnu",unknownError:"Erreur inconnue",today:"Aujourd'hui",tomorrow:"Demain",asap:"Dès que possible",overdue:"En retard",now:"Maintenant",collapse:"Réduire",expand:"Développer",viewArchive:"Voir l'archive",viewInFileManager:"Voir dans le gestionnaire de fichiers",addedBy:"Ajouté par {{username}}",prints:"impressions",more:"+{{count}} de plus",ascending:"Croissant",descending:"Décroissant",printer:"Imprimante",remove:"Retirer",type:"Type",print:"Imprimer",rename:"Renommer",move:"Déplacer",create:"Créer",duplicate:"Dupliquer",left:"Gauche",right:"Droite"},printers:{title:"Imprimantes",addPrinter:"Ajouter une imprimante",editPrinter:"Modifier l'imprimante",deletePrinter:"Supprimer l'imprimante",printerName:"Nom de l'imprimante",serialNumber:"Numéro de série",ipAddress:"Adresse IP / Nom d'hôte",accessCode:"Code d'accès",model:"Modèle",nozzleCount:"Nombre de buses",autoArchive:"Auto-archivage",status:{available:"Disponible",idle:"Inactif",printing:"Impression en cours",paused:"En pause",offline:"Hors ligne",problem:"Problème",error:"Erreur",finished:"Terminé",unknown:"Inconnu"},temperatures:{nozzle:"Buse",bed:"Plateau",chamber:"Chambre"},progress:"{{percent}}% terminé",timeRemaining:"{{time}} restant",deleteConfirm:'Êtes-vous sûr de vouloir supprimer "{{name}}" ?',maintenanceOk:"Maintenance OK",maintenanceWarning:"{{count}} avertissement",maintenanceWarning_plural:"{{count}} avertissements",maintenanceDue:"{{count}} échéance",maintenanceDue_plural:"{{count}} échéances",sort:{name:"Nom",status:"Statut",model:"Modèle",location:"Emplacement",ascending:"Tri croissant",descending:"Tri décroissant"},cardSize:{small:"Petites cartes",medium:"Cartes moyennes",large:"Grandes cartes",extraLarge:"Très grandes cartes"},hideOffline:"Masquer hors ligne",nextAvailable:"Prochaine disponible",powerOn:"Allumer",offlinePrintersWithPlugs:"Imprimantes hors ligne avec prises connectées",noPrintersConfigured:"Aucune imprimante configurée pour le moment",search:"Rechercher des imprimantes...",noSearchResults:"Aucune imprimante ne correspond à votre recherche ou à vos filtres",filter:{allStatuses:"Tous les statuts",allLocations:"Tous les emplacements"},readyToPrint:"Prête à imprimer",external:"Externe",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Supprimer les archives d'impression",noLabel:"Pas d'étiquette",printPreview:"Aperçu avant impression",width:"Largeur",height:"Hauteur",noObjectsFound:"Aucun objet trouvé",objectsLoadedOnPrintStart:"Les objets sont chargés au début de l'impression",willBeSkipped:"Sera sauté",name:"Nom",serialCannotBeChanged:"Le numéro de série ne peut pas être modifié",locationHelp:"Utilisé pour grouper les imprimantes et filtrer la file d'attente",wifiSignal:{veryWeak:"Très faible",weak:"Faible",fair:"Moyen",good:"Bon",excellent:"Excellent"},maintenanceUpToDate:"Maintenance à jour - Cliquez pour voir",chamberLightOn:"Allumer la lumière de la chambre",chamberLightOff:"Éteindre la lumière de la chambre",files:"Fichiers",browseFiles:"Parcourir les fichiers de l'imprimante",autoOffAfterPrint:"Extinction auto après impression",autoOffExecuted:"Extinction auto exécutée - rallumez pour réinitialiser",hmsErrors:"Erreurs HMS",viewHmsErrors:"Voir {{count}} erreur(s) HMS",resume:"Reprendre",pause:"Pause",stop:"Arrêter",camera:"Caméra",skipObject:"Sauter l'objet",reconnect:"Reconnecter",mqttDebug:"Débogage MQTT",printerInformation:"Informations imprimante",copyToClipboard:"Copier",copied:"Copié !",state:"État",wifiSignalLabel:"Signal WiFi",developerMode:"Mode développeur",enabled:"Activé",disabled:"Désactivé",addedOn:"Ajoutée le",sdCard:"Carte SD",inserted:"Insérée",notInserted:"Non insérée",totalPrintHours:"Heures d'impression",activeNozzle:"Active : buse {{nozzle}}",nozzleRack:"Rack à buses",nozzleDocked:"Rangée",nozzleMounted:"Montée",nozzleActive:"Active",nozzleIdle:"Inactive",nozzleDiameter:"Diamètre",nozzleType:"Type",nozzleStatus:"Statut",nozzleFilament:"Filament",nozzleWear:"Usure",nozzleMaxTemp:"Temp Max",nozzleSerial:"Série",nozzleHardenedSteel:"Acier Trempé",nozzleStainlessSteel:"Acier Inoxydable",nozzleTungstenCarbide:"Carbure de Tungstène",nozzleFlow:"Débit",nozzleHighFlow:"Haut débit",nozzleStandardFlow:"Standard",firmwareUpdate:"Mise à jour Firmware",firmwareInstructions:"Sur l'écran de l'imprimante, allez dans",firmwareNav:"Naviguez vers",settings:"Paramètres",firmware:"Firmware",discoverPrinters:"Découvrir les imprimantes",searching:"Recherche...",manualEntry:"Saisie manuelle",addFromCloud:"Ajouter depuis le Cloud",toast:{printerDeleted:"Imprimante supprimée",missingSpoolAssignment:"Impression démarrée sur {{printer}}. Attribution de bobine manquante pour : {{slots}}",printerAdded:"Imprimante ajoutée",printerUpdated:"Imprimante mise à jour",failedToDelete:"Échec de la suppression",failedToAdd:"Échec de l'ajout",failedToUpdate:"Échec de la mise à jour",commandSent:"Commande envoyée",failedToSendCommand:"Échec de l'envoi de la commande",turnedOn:"{{name}} allumée",failedToPowerOn:"Échec de l'allumage de {{name}}",scriptTriggered:"Script déclenché",printStopped:"Impression arrêtée",printPaused:"Impression en pause",printResumed:"Impression reprise",referenceDeleted:"Référence supprimée",detectionAreaSaved:"Zone de détection enregistrée",failedToRunScript:"Échec du script",failedToStopPrint:"Échec de l'arrêt",failedToPausePrint:"Échec de la mise en pause",failedToResumePrint:"Échec de la reprise",failedToControlChamberLight:"Échec du contrôle de la lumière",failedToSetSpeed:"Échec du réglage de la vitesse",failedToUpdateSetting:"Échec de mise à jour du paramètre",failedToSkipObjects:"Échec du saut d'objets",failedToRereadRfid:"Échec lecture RFID",failedToCheckPlate:"Échec vérification plateau",failedToUpdateLabel:"Échec mise à jour étiquette",failedToDeleteReference:"Échec suppression référence",failedToSaveDetectionArea:"Échec enregistrement zone",plateCheckEnabled:"Vérification plateau activée",plateCheckDisabled:"Vérification plateau désactivée",calibrationSaved:"Calibration enregistrée !",calibrationFailed:"Échec de la calibration",rfidRereadInitiated:"Lecture RFID initiée"},connection:{connected:"Connecté",offline:"Hors ligne"},queue:{inQueue:"{{count}} impression en file",inQueue_plural:"{{count}} impressions en file"},controls:"Contrôles",rfid:{reread:"Relire RFID"},permission:{noAdd:"Pas d'autorisation pour ajouter",noEdit:"Pas d'autorisation pour modifier",noDelete:"Pas d'autorisation pour supprimer",noControl:"Pas d'autorisation pour contrôler",noFiles:"Pas d'autorisation pour les fichiers",noAmsRfid:"Pas d'autorisation pour le RFID",noSmartPlugControl:"Pas d'autorisation pour les prises",noCamera:"Pas d'autorisation pour les caméras"},modal:{addTitle:"Ajouter une imprimante",editTitle:"Modifier l'imprimante",myPrinter:"Mon imprimante",selectModel:"Choisir un modèle...",locationGroup:"Emplacement / Groupe (optionnel)",locationPlaceholder:"ex: Atelier, Bureau",autoArchiveLabel:"Auto-archiver les impressions terminées",fromPrinterSettings:"Depuis les paramètres imprimante",modelOptional:"Modèle (optionnel)",saveChanges:"Enregistrer les modifications"},skipObjects:{tooltip:"Sauter des objets",onlyWhilePrinting:"Sauter (uniquement pendant l'impression)",requiresMultiple:"Sauter (nécessite 2+ objets)",title:"Sauter des objets",matchIdsInfo:"Faites correspondre les IDs avec l'écran de l'imprimante",printerShowsIds:"L'écran affiche les IDs des objets sur le plateau",skipSelected:"Sauter la sélection",skipping:"Saut en cours...",noObjectsSelected:"Aucun objet sélectionné",selectObjectsToSkip:"Sélectionnez les objets à ignorer",skipped:"sauté",objectsSkipped:"Objets sautés",activeCount:"{{count}} actifs",waitForLayer:"Attendez la couche 2 pour sauter des objets (actuelle : {{layer}})",skip:"Sauter",confirmTitle:"Sauter l'objet ?",confirmMessage:'Voulez-vous vraiment sauter "{{name}}" ? Cette action est irréversible.'},confirm:{deleteTitle:"Supprimer l'imprimante",deleteMessage:'Supprimer "{{name}}" ? Cela retirera tous les paramètres de connexion.',deleteArchivesNote:"Tout l'historique sera définitivement supprimé.",keepArchivesNote:"L'historique sera conservé mais plus associé à cette imprimante.",stopTitle:"Arrêter l'impression",stopMessage:`Arrêter l'impression sur "{{name}}" ?`,stopButton:"Arrêter",pauseTitle:"Mettre en pause",pauseMessage:`Mettre en pause l'impression sur "{{name}}" ?`,pauseButton:"Pause",resumeTitle:"Reprendre l'impression",resumeMessage:`Reprendre l'impression sur "{{name}}" ?`,resumeButton:"Reprendre",powerOnTitle:"Allumer l'imprimante",powerOnMessage:'Allumer "{{name}}" ?',powerOnButton:"Allumer",powerOffTitle:"Éteindre l'imprimante",powerOffMessage:'Éteindre "{{name}}" ?',powerOffWarning:`ATTENTION : "{{name}}" imprime ! L'éteindre maintenant peut endommager l'imprimante.`,powerOffButton:"Éteindre"},bulk:{select:"Sélectionner",selectAll:"Tout sélectionner",selectByLocation:"Sélectionner par emplacement",selected:"{{count}} sélectionné(s)",actions:{stop:"Arrêter",pause:"Pause",resume:"Reprendre",clearPlate:"Vider le plateau",clearHMS:"Effacer les notifications"},confirm:{stopTitle:"Arrêter {{count}} impressions",stopMessage:"Cela annulera les impressions actives sur {{count}} imprimante(s). Cette action est irréversible.",stopButton:"Tout arrêter",pauseTitle:"Mettre en pause {{count}} impressions",pauseMessage:"Cela mettra en pause les impressions actives sur {{count}} imprimante(s).",pauseButton:"Tout mettre en pause",clearPlateTitle:"Vider {{count}} plateaux",clearPlateMessage:"Cela videra le plateau sur {{count}} imprimante(s) et pourrait lancer les travaux en file d'attente.",clearPlateButton:"Tout vider"},success:"{{action}} terminé sur {{count}} imprimante(s)",partial:"{{succeeded}} réussi(s), {{failed}} échoué(s)",noneApplicable:"Aucune imprimante sélectionnée n'est dans le bon état pour cette action",selectByState:"Sélectionner par état"},discovery:{title:"Découvrir les imprimantes",searching:"Recherche...",scanning:"Scan en cours...",scanProgress:"Scan... {{scanned}}/{{total}}",foundPrinters:"{{count}} imprimante(s) trouvée(s)",noPrintersFound:"Aucune imprimante trouvée",noPrintersFoundSubnet:"Aucune imprimante dans ce sous-réseau.",noPrintersFoundNetwork:"Aucune imprimante sur le réseau.",allConfigured:"Toutes les imprimantes trouvées sont déjà configurées.",alreadyAdded:"Déjà ajoutée",select:"Sélectionner",manualEntry:"Saisie manuelle",addFromCloud:"Ajouter depuis le Cloud",subnetToScan:"Sous-réseau à scanner",dockerNote:"Docker détecté. Entrez le sous-réseau en notation CIDR. Nécessite network_mode: host.",scanSubnet:"Scanner le sous-réseau",discoverNetwork:"Découvrir sur le réseau",scanningSubnet:"Scan du sous-réseau pour imprimantes Bambu...",scanningNetwork:"Scan du réseau...",serialRequired:"Série requis",unknown:"Inconnu",failedToStart:"Échec du démarrage de la découverte"},drying:{start:"Démarrer le séchage",stop:"Arrêter le séchage",temperature:"Température",duration:"Durée",hours:"heures",timeRemaining:"{{time}} restant",active:"Séchage",notSupported:"Séchage non pris en charge",powerRequired:"Brancher l'adaptateur secteur AMS pour activer le séchage",startingDrying:"Démarrage du séchage...",stoppingDrying:"Arrêt du séchage...",rotateTray:"Tourner la bobine pendant le séchage"},filaments:"Filaments",openCameraOverlay:"Ouvrir la caméra en superposition",openCameraWindow:"Ouvrir la caméra dans une fenêtre",firmwareUpdateAvailable:"Mise à jour firmware : {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — À jour",firmwareUpdateButton:"Mettre à jour",plateDetection:{noPermission:"Pas d'autorisation de modification",enabledClick:"Vérification activée - Cliquez pour désactiver",disabledClick:"Vérification désactivée - Cliquez pour activer",manageCalibration:"Gérer la calibration de détection",calibrationRequired:"Calibration requise",calibrationInstructions:"Videz le plateau, puis cliquez sur Calibrer.",calibrationDescription:"Capture une image de référence du plateau vide.",calibrationTip:"Conseil : Stockez jusqu'à 5 références. Le système utilise la meilleure correspondance.",plateEmpty:"Le plateau semble vide",objectsDetected:"Objets détectés sur le plateau",confidence:"Confiance",difference:"Différence",analysisPreview:"Aperçu de l'analyse :",analysisLegend:"Cadre vert = zone, Rouge = différences",savedReferences:"Références ({{count}}/{{max}})",deleteReference:"Supprimer la référence",labelPlaceholder:"Étiquette...",clickToEdit:"{{label}} - Modifier",clickToAddLabel:"Ajouter une étiquette"},speed:{title:"Vitesse d'impression",silent:"Silencieux (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},fans:{partCooling:"Ventilateur pièce",auxiliary:"Ventilateur auxiliaire",chamber:"Ventilateur chambre"},clickToViewHmsErrors:"Cliquez pour voir les erreurs HMS",estimatedCompletion:"Fin estimée",plateNumber:"Plaque {{number}}",slotOptions:"Options du slot",amsPopup:{friendlyName:"Nom AMS",friendlyNamePlaceholder:"ex. Nom convivial AMS",serialNumber:"Numéro de série",firmwareVersion:"Firmware",save:"Enregistrer",clear:"Effacer",noEditPermission:"Vous n'avez pas la permission de renommer les unités AMS"},firmwareModal:{title:"Mise à jour Firmware",titleUpToDate:"Infos Firmware",currentVersion:"Actuelle :",latestVersion:"Dernière :",releaseNotes:"Notes de version",checkingPrereqs:"Vérification des prérequis...",sdCardReady:"Carte SD prête. Cliquez pour téléverser.",uploadedSuccess:"Firmware téléversé !",applyInstructions:"Pour appliquer sur l'imprimante :",step1:"Sur l'écran, allez dans Paramètres",step2:"Allez dans Firmware",step3:'Sélectionnez "Mettre à jour depuis carte SD"',step4:"Prévoyez 10-20 minutes",done:"Terminé",starting:"Démarrage...",uploadFirmware:"Téléverser le Firmware",uploadFailed:"Échec du téléversement : {{error}}",uploadedToast:"Firmware téléversé ! Lancez la mise à jour sur l'écran."},accessCodePlaceholder:"Laissez vide pour garder l'actuel",roi:{title:"Zone de détection (ROI)",xStart:"Début X",yStart:"Début Y",width:"Largeur",height:"Hauteur",instruction:"Ajustez le cadre vert pour cibler le plateau."},developerModeWarning:"Le mode développeur LAN n'est pas activé sur : {{names}}. Certaines fonctionnalités peuvent ne pas fonctionner.",howToEnable:"Comment activer",incompatibleFile:"Ce fichier a été tranché pour {{slicedFor}}, mais cette imprimante est une {{printerModel}}",dropNotPrintable:"Seuls les fichiers .gcode et .gcode.3mf peuvent être imprimés",dropToPrint:"Déposer pour imprimer",cannotPrint:"Imprimante occupée"},archives:{title:"Archives d'impression",searchPlaceholder:"Chercher dans les archives...",filterByPrinter:"Par imprimante",filterByStatus:"Par statut",sortBy:"Trier par",sortNewest:"Plus récent",sortOldest:"Plus ancien",sortName:"Nom",sortDuration:"Durée",sortLargest:"Plus volumineux",sortSmallest:"Plus léger",sortSize:"Taille",noArchives:"Aucune archive trouvée",noArchivesSearch:"Aucune archive ne correspond",originalPrintNotVisible:"Impression d'origine non visible - essayez d'effacer les filtres",noArchivesYet:"Pas encore d'archive",prints:"impressions",pagination:{showing:"Affichage",to:"à",of:"sur",show:"Afficher",page:"Page",all:"Tout"},loadingArchives:"Chargement...",releaseToUpload:"Relâcher pour téléverser",showAll:"Tout afficher",showFavoritesOnly:"Favoris uniquement",gridView:"Grille",listView:"Liste",calendarView:"Calendrier",logView:"Journal d'impression",manageTags:"Gérer les tags",showFailedPrints:"Afficher les échecs",hideFailedPrints:"Masquer les échecs",hideDuplicates:"Masquer les doublons",viewOriginalPrint:"Cliquez pour afficher l'impression originale (#{{id}})",printTime:"Temps d'impression",filamentUsed:"Filament utilisé",cost:"Coût",reprint:"Réimprimer",preview:"Aperçu",deleteArchive:"Supprimer l'archive",deleteConfirm:"Supprimer cette archive ?",favorite:"Favori",unfavorite:"Retirer des favoris",viewDetails:"Détails",status:{completed:"Réussi",failed:"Échoué",stopped:"Arrêté"},toast:{source3mfAttached:"Source 3MF attachée : {{filename}}",failedUploadSource3mf:"Échec téléversement 3MF",source3mfRemoved:"Source 3MF retirée",failedRemoveSource3mf:"Échec retrait 3MF",f3dAttached:"F3D attaché : {{filename}}",failedUploadF3d:"Échec téléversement F3D",f3dRemoved:"F3D retiré",failedRemoveF3d:"Échec retrait F3D",timelapseAttached:"Timelapse attaché : {{filename}}",timelapseAlreadyAttached:"Timelapse déjà présent",noMatchingTimelapse:"Pas de timelapse correspondant",failedScanTimelapse:"Échec scan timelapse",failedAttachTimelapse:"Échec attache timelapse",timelapseRemoved:"Timelapse supprimé",failedRemoveTimelapse:"Échec de la suppression du timelapse",timelapseUploaded:"Timelapse importé : {{filename}}",failedUploadTimelapse:"Échec de l'importation du timelapse",archiveDeleted:"Archive supprimée",failedDeleteArchive:"Échec suppression",addedToFavorites:"Ajouté aux favoris",removedFromFavorites:"Retiré des favoris",projectUpdated:"Projet mis à jour",failedUpdateProject:"Échec mise à jour projet",linkCopied:"Lien copié",failedCopyLink:"Échec copie lien",photoDeleted:"Photo supprimée",failedDeletePhoto:"Échec suppression photo",failedDeleteArchives:"Échec suppression archives",failedUpdateFavorites:"Échec mise à jour favoris",exportDownloaded:"Export téléchargé",exportFailed:"Échec export"},menu:{print:"Imprimer",schedule:"Planifier",openInBambuStudio:"Ouvrir dans le Slicer",slice:"Découper",externalLink:"Lien externe",viewOnMakerWorld:"Voir sur MakerWorld",preview3d:"Aperçu 3D",viewTimelapse:"Voir le Timelapse",scanForTimelapse:"Scanner pour Timelapse",uploadTimelapse:"Importer un timelapse",removeTimelapse:"Supprimer le timelapse",downloadSource3mf:"Télécharger Source 3MF",uploadSource3mf:"Téléverser Source 3MF",replaceSource3mf:"Remplacer Source 3MF",removeSource3mf:"Retirer Source 3MF",uploadF3d:"Téléverser F3D",replaceF3d:"Remplacer F3D",downloadF3d:"Télécharger F3D",removeF3d:"Retirer F3D",download:"Télécharger",copyDownloadLink:"Copier lien de téléchargement",qrCode:"Code QR",viewPhotos:"Voir les photos",viewPhotosCount:"Voir les photos ({{count}})",projectPage:"Page du Projet",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",edit:"Modifier",goToProject:"Aller au Projet : {{name}}",addToProject:"Ajouter au Projet",removeFromProject:"Retirer du Projet",loading:"Chargement...",noProjectsAvailable:"Aucun projet disponible",select:"Sélectionner",deselect:"Désélectionner",delete:"Supprimer"},permission:{noReprint:"Pas d'autorisation de réimpression",noAddToQueue:"Pas d'autorisation pour la file",noUpdateArchives:"Pas d'autorisation de mise à jour",noUploadFiles:"Pas d'autorisation de téléversement",noDownload:"Pas d'autorisation de téléchargement",noCopyLink:"Pas d'autorisation de copie lien",noDelete:"Pas d'autorisation de suppression",noCreate:"Pas d'autorisation de création"},card:{previousPlate:"Plateau précédent",nextPlate:"Plateau suivant",plateNumber:"Plateau {{index}}",moreOptions:"Clic droit pour plus d'options",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",cancelled:"annulé",failed:"échoué",duplicate:"doublon",duplicateTitle:"Ce modèle a déjà été imprimé",openSource3mf:"Ouvrir 3MF dans Bambu Studio (clic droit pour plus)",downloadF3d:"Télécharger fichier Fusion 360",viewTimelapse:"Voir timelapse",viewPhoto:"Voir 1 photo",viewPhotos:"Voir {{count}} photos",openFolder:"Ouvrir le dossier : {{name}}",slicedFile:"Fichier découpé - prêt",sourceFile:"Fichier source uniquement - pas de mapping AMS",gcode:"GCODE",source:"SOURCE",project:"Projet : {{name}}",estimated:"Estimé : {{time}}",actual:"Réel : {{time}}",accuracy:"Précision : {{percent}}%",filament:"{{weight}}g",layer:"{{count}} couche",layers:"{{count}} couches",object:"{{count}} objet",objects:"{{count}} objets",slicedFor:"Découpé pour {{model}}",uploadedBy:"Téléversé par",noPermissionReprint:"Pas d'autorisation de réimpression",noFileForReprint:"Aucun fichier 3MF disponible — le fichier n'a pas pu être téléchargé depuis l'imprimante lors de l'enregistrement",noPermissionEdit:"Pas d'autorisation de modification",noPermissionDelete:"Pas d'autorisation de suppression",reprint:"Réimprimer",schedulePrint:"Planifier",schedule:"Planifier",openInBambuStudio:"Ouvrir dans le Slicer",openInBambuStudioToSlice:"Ouvrir dans le Slicer pour découper",slice:"Découper",externalLink:"Lien externe",makerWorld:"MakerWorld : {{designer}}",viewProject:"Voir projet",noExternalLink:"Aucun lien externe",preview3d:"Aperçu 3D",download:"Télécharger",edit:"Modifier",delete:"Supprimer"},modal:{deleteArchive:"Supprimer l'archive",deleteConfirm:'Supprimer "{{name}}" ? Cette action est irréversible.',deleteButton:"Supprimer",removeSource3mf:"Retirer Source 3MF",removeSource3mfConfirm:'Retirer le fichier 3MF de "{{name}}" ?',removeButton:"Retirer",removeF3d:"Retirer F3D",removeF3dConfirm:'Retirer le fichier Fusion 360 de "{{name}}" ?',removeTimelapse:"Supprimer le timelapse",removeTimelapseConfirm:'Êtes-vous sûr de vouloir supprimer la vidéo timelapse de "{{name}}" ?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Choisir un Timelapse",selectTimelapseDesc:"Sélectionnez manuellement le timelapse :",deleteArchives:"Supprimer les archives",deleteArchivesConfirm:"Supprimer {{count}} archive(s) ?",deleteCount:"Supprimer {{count}}"},page:{title:"Archives",printsCount:"{{filtered}} sur {{total}} impressions",dropFilesHere:"Déposez les fichiers .3mf ici",releaseToUpload:"Relâcher pour téléverser",only3mfSupported:"Seuls les fichiers .3mf sont supportés",close:"Fermer",selected:"{{count}} sélectionnés",selectAll:"Tout sélectionner",tags:"Tags",project:"Projet",favorite:"Favori",delete:"Supprimer",toggledFavorites:"Favoris mis à jour pour {{count}} archive(s)",failedUpdateFavorites:"Échec mise à jour favoris",archivesDeleted:"{{count}} archive(s) supprimée(s)",failedDeleteArchives:"Échec suppression",photoDeleted:"Photo supprimée",failedDeletePhoto:"Échec suppression photo"},list:{name:"Nom",printer:"Imprimante",date:"Date",size:"Taille",actions:"Actions",hasTimelapse:"A un timelapse"},log:{date:"Date",printName:"Nom de l'impression",printer:"Imprimante",user:"Utilisateur",status:"Statut",duration:"Durée",filament:"Filament",allPrinters:"Toutes les imprimantes",allUsers:"Tous les utilisateurs",allStatuses:"Tous les statuts",cancelled:"Annulé",skipped:"Ignoré",dateFrom:"Du",dateTo:"Au",noEntries:"Aucune entrée de journal trouvée",showing:"{{count}} sur {{total}} entrées",rowsPerPage:"Lignes",page:"Page",prev:"Préc.",next:"Suiv.",clearLog:"Effacer le journal",clearLogTitle:"Effacer le journal d'impression",clearLogConfirm:"Toutes les entrées du journal d'impression seront supprimées définitivement. Les archives et les éléments de file d'attente ne sont pas affectés. Cette action est irréversible. Êtes-vous sûr ?",clearLogButton:"Tout effacer",cleared:"{{count}} entrées de journal effacées",clearFailed:"Échec de l'effacement du journal d'impression"}},queue:{title:"File d'attente",subtitle:"Gérez vos travaux d'impression",addToQueue:"Ajouter à la file",print:"Imprimer",reprint:"Réimprimer",schedulePrint:"Planifier",editQueueItem:"Modifier l'élément",printToPrinters:"Imprimer sur {{count}} imprimantes",queueToPrinters:"Ajouter à la file pour {{count}} imprimantes",queueSelectedPlates:"Ajouter {{count}} plaques à la file",selectAllPlates:"Sélectionner les {{count}} plaques",deselectAll:"Tout désélectionner",printQueued:"Impression ajoutée à la file",itemsQueued:"{{count}} éléments ajoutés à la file",sending:"Envoi...",sendingProgress:"Envoi {{current}}/{{total}}...",adding:"Ajout...",addingProgress:"Ajout {{current}}/{{total}}...",savingProgress:"Enregistrement {{current}}/{{total}}...",clearQueue:"Vider la file",clearHistory:"Effacer l'historique",emptyQueue:"La file est vide",position:"Position",scheduledTime:"Heure prévue",moveUp:"Monter",moveDown:"Descendre",startNow:"Démarrer maintenant",printingInProgress:"Impression en cours...",viewArchive:"Voir l'archive",viewInFileManager:"Voir dans le gestionnaire",itemCount:"{{count}} élément",itemCount_plural:"{{count}} éléments",dragToReorder:"Glisser pour réordonner (ASAP uniquement)",reorderHint:"La position n'affecte que les éléments ASAP.",sjf:{label:"SJF",tooltip:"Travail le plus court en premier — le planificateur priorise les impressions plus courtes"},addedBy:"Ajouté par {{name}}",nextInQueue:"Prochain en file",clearPlate:"Vider plateau & lancer suivant",clearPlateSuccess:"Plateau vidé — prêt pour l'impression suivante",plateReady:"Plateau vidé — prêt pour l'impression suivante",plateNumber:"Plateau {{index}}",quantity:"Quantité",quantityHint:"Crée {{count}} éléments de file d'attente",activeBatches:"Lots actifs",batchProgress:"{{completed}} sur {{total}} terminés",cancelBatch:"Annuler les restants",batchCancelled:"Éléments restants du lot annulés",cancelBatchConfirmTitle:"Annuler le lot",cancelBatchConfirmMessage:"Annuler tous les éléments en attente restants dans ce lot ?",batch:"Lot",sections:{currentlyPrinting:"En cours",queued:"En attente",history:"Historique"},status:{pending:"En attente",waiting:"En attente",printing:"Impression",paused:"En pause",completed:"Terminé",failed:"Échoué",skipped:"Sauté",cancelled:"Annulé"},summary:{printing:"Impressions",queued:"En attente",totalTime:"Temps total estimé",totalWeight:"Poids total estimé",history:"Historique"},filter:{allPrinters:"Toutes les imprimantes",unassigned:"Non assigné",allStatus:"Tous les statuts",allLocations:"Tous les emplacements",any:"Tout"},sort:{byPosition:"Par position",byName:"Par nom",byPrinter:"Par imprimante",bySchedule:"Par planification",byDate:"Par date",ascendingOldest:"Croissant (plus vieux)",descendingNewest:"Décroissant (plus récent)"},badges:{staged:"Préparé",requiresPrevious:"Nécessite succès précédent",autoPowerOff:"Extinction auto",gcodeInjection:"G-code"},empty:{title:"Aucune impression prévue",description:"Planifiez depuis les Archives ou glissez des fichiers ici."},time:{asap:"Dès que possible",overdue:"En retard",now:"Maintenant",lessThanMinute:"Dans moins d'une minute",inMinutes:"Dans {{count}} min",inHours:"Dans {{count}} heures"},actions:{stopPrint:"Arrêter",startPrint:"Démarrer",requeue:"Remettre en file"},bulkEdit:{title:"Modifier {{count}} élément",title_plural:"Modifier {{count}} éléments",description:"Seuls les changements seront appliqués.",printer:"Imprimante",noChange:"— Aucun changement —",queueOptions:"Options de file",staged:"Préparé (manuel)",autoPowerOff:"Extinction auto après",requirePrevious:"Requiert succès précédent",printOptions:"Options d'impression",bedLevelling:"Nivellement plateau",flowCalibration:"Calibration débit",vibrationCalibration:"Vibration (Input Shaper)",layerInspection:"Inspection 1ère couche",timelapse:"Timelapse",useAms:"Utiliser AMS",applyChanges:"Appliquer",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",selected:"{{count}} sélectionnés",editSelected:"Modifier la sélection",cancelSelected:"Annuler la sélection"},confirm:{cancelTitle:"Annuler l'impression prévue",cancelMessage:'Annuler "{{name}}" ?',stopTitle:"Arrêter l'impression",stopMessage:`Arrêter "{{name}}" sur l'imprimante ?`,removeTitle:"Retirer de l'historique",removeMessage:`Retirer "{{name}}" de l'historique ?`,clearHistoryTitle:"Effacer l'historique",clearHistoryMessage:"Retirer les {{count}} éléments ?",cancelButton:"Annuler l'impression",stopButton:"Arrêter l'impression",thisPrint:"cette impression",thisItem:"cet élément"},toast:{cancelled:"Élément annulé",cancelFailed:"Échec annulation",removed:"Élément retiré",removeFailed:"Échec retrait",stopped:"Impression arrêtée",stopFailed:"Échec arrêt",released:"Libéré dans la file",startFailed:"Échec démarrage",reorderFailed:"Échec réorganisation",historyCleared:"{{count}} éléments effacés",clearHistoryFailed:"Échec effacement",updateFailed:"Échec mise à jour",bulkCancelled:"{{count}} éléments annulés",bulkCancelFailed:"Échec annulation"},timeline:{listView:"Liste",timelineView:"Chronologie",unassigned:"Non attribué",noData:"Aucune impression planifiée pour ce jour",allDoneBy:"Toutes les impressions terminées vers {{time}}",staged:"En attente",filterAll:"Tout afficher",filterPrinting:"En cours",filterQueued:"En file",time:{anyMoment:"imminent",minutesLeft:"{{minutes}}m restantes",hoursLeft:"{{hours}}h restantes",hoursMinutesLeft:"{{hours}}h {{minutes}}m restantes"},day:{previous:"Jour précédent",next:"Jour suivant",today:"Aujourd'hui"}},permissions:{noStopPrint:"Pas d'autorisation d'arrêt",noStartPrint:"Pas d'autorisation de démarrage",noEdit:"Pas d'autorisation de modification",noCancel:"Pas d'autorisation d'annulation",noRequeue:"Pas d'autorisation de remise en file",noRemove:"Pas d'autorisation de retrait",noClearHistory:"Pas d'autorisation historique",noEditItems:"Pas d'autorisation modification groupée",noCancelItems:"Pas d'autorisation annulation groupée"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded",printStartedRemaining:"{{completed}} impression(s) lancée(s), {{remaining}} en cours d'envoi..."}},stats:{title:"Tableau de bord",subtitle:"Glissez les widgets pour réorganiser. Cliquez sur l'œil pour masquer.",overview:"Vue d'ensemble",totalPrints:"Total impressions",successRate:"Taux de succès",totalPrintTime:"Temps total d'impression",printTime:"Temps d'impression",totalFilament:"Total filament utilisé",filamentUsed:"Filament utilisé",filamentCost:"Coût filament",totalCost:"Coût total",energyUsed:"Énergie consommée",energyCost:"Coût énergie",averagePrintTime:"Temps moyen par impression",printsPerDay:"Impressions par jour",byPrinter:"Par imprimante",printsByPrinter:"Impressions par imprimante",byMaterial:"Par matériau",byMonth:"Par mois",last7Days:"7 derniers jours",last30Days:"30 derniers jours",last90Days:"90 derniers jours",allTime:"Tout le temps",quickStats:"Stats rapides",printActivity:"Activité d'impression",filamentTypes:"Types de filament",filamentTrends:"Tendances filament",failureAnalysis:"Analyse des échecs",timeAccuracy:"Précision du temps",successful:"Succès :",failed:"Échecs :",perfectEstimate:"100% = estimation parfaite",noTimeAccuracyData:"Pas encore de données de précision",noFilamentData:"Aucune donnée de filament",noPrinterData:"Aucune donnée d'imprimante",noPrintData:"Aucune donnée d'impression",noPrintDataLast30Days:"Aucune impression ces 30 derniers jours",failureReasons:"Raisons des échecs",topFailureReasons:"Top raisons d'échec",failedPrintsCount:"{{failed}} / {{total}} impressions ont échoué",lastWeekRate:"Semaine dernière : {{rate}}%",resetLayout:"Réinitialiser la mise en page",recalculateCosts:"Recalculer les coûts",recalculateCostsHint:"Recalcule les coûts avec les prix actuels des filaments",exportStats:"Exporter les stats",exportAsCsv:"Exporter en CSV",exportAsExcel:"Exporter en Excel",hiddenCount:"{{count}} Masqués",exportDownloaded:"Export téléchargé",exportFailed:"Échec export",layoutReset:"Mise en page réinitialisée",recalculatedCosts:"Coûts recalculés pour {{count}} archives",recalculateFailed:"Échec du calcul",loadingStats:"Chargement des statistiques...",noPermissionResetLayout:"Pas d'autorisation de réinitialisation",noPermissionRecalculate:"Pas d'autorisation de recalcul",noPrintDataInRange:"Aucune donnée dans la période sélectionnée",periodFilament:"Filament utilisé",periodCost:"Coût",avgPerPrint:"Moy. par impression",usageOverTime:"Utilisation dans le temps",filamentByWeight:"Poids",printDuration:"Durée d'impression",printerUtilization:"Utilisation imprimante",filamentSuccess:"Succès par matériau",printHabits:"Habitudes d'impression",printTimeOfDay:"Heure d'impression",colorDistribution:"Distribution des couleurs",noColorData:"Aucune donnée de couleur disponible",records:"Records",longestPrint:"Plus longue impression",heaviestPrint:"Plus lourde impression",mostExpensivePrint:"Plus chère",busiestDay:"Jour le plus actif",successStreak:"Série de succès",streakPrint:"impression consécutive",streakPrints:"{{count}} impressions consécutives",printerStats:"Stats imprimante",hours:"heures",avgPrints:"Moy. impressions",noArchiveData:"Aucune donnée d'impression disponible",filamentByTime:"Temps",avgWeight:"Moy. poids",avgTime:"Moy. temps",filamentByPrints:"Impressions",timeframe:{today:"Aujourd'hui","this-week":"Cette semaine","this-month":"Ce mois","last-7":"7 derniers jours","last-30":"30 derniers jours","last-90":"90 derniers jours","this-year":"Cette année","all-time":"Tout",custom:"Personnalisé",from:"Du",to:"Au"},allUsers:"Tous les utilisateurs",noUser:"Aucun utilisateur (Système)",filterByUser:"Filtrer par utilisateur"},maintenance:{title:"Maintenance",overview:"Vue d'ensemble",allOk:"Toute la maintenance est à jour",dueCount:"{{count}} tâche à faire",dueCount_plural:"{{count}} tâches à faire",warningCount:"{{count}} avertissement",warningCount_plural:"{{count}} avertissements",totalPrintTime:"Temps d'impression total",nextMaintenance:"Prochaine maintenance",nothingDue:"Rien de prévu",tasks:"Tâches",lastPerformed:"Dernière réalisation",interval:"Intervalle",hoursRemaining:"{{hours}}h restantes",hoursOverdue:"{{hours}}h de retard",markDone:"Marquer comme fait",performMaintenance:"Effectuer la maintenance",history:"Historique",noHistory:"Aucun historique",editPrintHours:"Modifier les heures d'impression",currentHours:"Heures actuelles",statusTab:"Statut",settingsTab:"Paramètres",overdueCount:"{{count}} en retard",dueSoonCount:"{{count}} bientôt",dueSoon:"Bientôt",allGood:"Tout va bien",overdueBy:"Retard de {{duration}}",dueIn:"Dans {{duration}}",timeLeft:"{{duration}} restant",day:"1 jour",days:"{{count}} jours",week:"1 semaine",weeks:"{{count}} semaines",month:"1 mois",months:"{{count}} mois",year:"1 an",maintenanceTypes:"Types de maintenance",maintenanceTypesDescription:"Types système et tâches personnalisées",addCustomType:"Ajouter un type",restoreDefaults:"Restaurer les tâches par défaut",intervalType:"Type d'intervalle",intervalValue:"Intervalle ({{type}})",icon:"Icône",documentationLink:"Lien documentation (optionnel)",assignToPrinters:"Assigner aux imprimantes",selectAtLeastOnePrinter:"Sélectionnez au moins une imprimante",addType:"Ajouter le type",custom:"Personnalisé",printHours:"Heures d'impression",calendarDays:"Jours calendaires",exampleName:"ex: Remplacement filtre HEPA",viewDocumentation:"Voir documentation",timeBasedInterval:"Intervalle temporel",intervalOverrides:"Exceptions d'intervalle",intervalOverridesDescription:"Intervalles spécifiques par imprimante",assignedToPrinters:"Assigné aux imprimantes :",noPrintersAssigned:"Aucune imprimante assignée",addPrinterShort:"Ajouter :",printersAssignedClick:"{{count}} imprimante(s) assignée(s) - gérer",removeFromPrinter:"Retirer de cette imprimante",types:{lubricateCarbonRods:"Lubrifier les tiges carbone",lubricateRails:"Lubrifier les rails linéaires",cleanNozzle:"Nettoyer la buse / hotend",checkBelts:"Vérifier la tension des courroies",cleanBuildPlate:"Nettoyer le plateau",checkExtruder:"Vérifier les engrenages de l'extrudeur",checkCooling:"Vérifier les ventilateurs",generalInspection:"Inspection générale",cleanCarbonRods:"Nettoyer les tiges carbone",lubricateSteelRods:"Lubrifier les tiges en acier",cleanSteelRods:"Nettoyer les tiges en acier",cleanLinearRails:"Nettoyer les rails linéaires",checkPtfeTube:"Vérifier le tube PTFE",replaceHepaFilter:"Remplacer le filtre HEPA",replaceCarbonFilter:"Remplacer le filtre charbon",lubricateLeftNozzleRail:"Lubrifier le rail de buse gauche"},maintenanceComplete:"Maintenance marquée comme faite",typeUpdated:"Type mis à jour",typeDeleted:"Type supprimé",defaultsRestored:"{{count}} tâche(s) par défaut restaurée(s)",printHoursUpdated:"Heures mises à jour",printerAssigned:"Imprimante assignée",printerRemoved:"Imprimante retirée",deleteTypeConfirm:'Supprimer "{{name}}" ?',deleteSystemTypeTitle:"Supprimer la tâche de maintenance par défaut ?",deleteSystemTypeMessage:'Êtes-vous sûr de vouloir supprimer la tâche de maintenance par défaut "{{name}}" ?',noPermissionUpdate:"Pas d'autorisation de mise à jour",noPermissionPerform:"Pas d'autorisation d'action",noPermissionEditTypes:"Pas d'autorisation de modification types",noPermissionDeleteTypes:"Pas d'autorisation de suppression types",noPermissionEditHours:"Pas d'autorisation de modification heures",noPermissionRemovePrinter:"Pas d'autorisation retrait imprimante",noPermissionAssignPrinter:"Pas d'autorisation assignation",noPermissionEditIntervals:"Pas d'autorisation modification intervalles",configureSettings:"Configurer types et intervalles"},settings:{title:"Paramètres",general:"Général",tabs:{general:"Général",smartPlugs:"Prises connectées",notifications:"Notifications",queue:"Workflow",filament:"Filament",network:"Réseau",apiKeys:"Clés API",virtualPrinter:"Imprimante virtuelle",users:"Authentification",backup:"Sauvegarde",emailAuth:"Authentification Email",ldap:"LDAP"},ldap:{title:"Authentification LDAP",enabledDesc:"L'authentification LDAP est activée",disabledDesc:"L'authentification LDAP est désactivée",disabledHint:"Configurez et enregistrez les paramètres LDAP ci-dessous, puis activez.",enabled:"Authentification LDAP activée",disabled:"Authentification LDAP désactivée",feature1:"Les utilisateurs peuvent se connecter avec leurs identifiants LDAP",feature2:"Le compte administrateur local reste disponible en secours",feature3:"Les groupes LDAP sont associés aux groupes BamBuddy à la connexion",serverConfig:"Configuration du serveur LDAP",serverUrl:"URL du serveur",serverUrlHint:"Utilisez ldap:// pour standard ou ldaps:// pour les connexions SSL",security:"Sécurité",securityHint:"StartTLS met à niveau une connexion simple vers TLS. LDAPS utilise TLS dès le début.",bindDn:"DN de liaison (compte de service)",bindPassword:"Mot de passe de liaison",searchBase:"DN de base de recherche",userFilter:"Filtre de recherche utilisateur",userFilterHint:"{username} est remplacé par le nom d'utilisateur. Utilisez (uid={username}) pour OpenLDAP.",autoProvision:"Provisionnement automatique",autoProvisionHint:"Créer automatiquement un compte BamBuddy lors de la première connexion LDAP",defaultGroup:"Groupe par défaut",defaultGroupNone:"— Aucun (pas de repli) —",defaultGroupHint:"Groupe de repli attribué lorsqu'un utilisateur LDAP s'authentifie mais n'est dans aucun groupe LDAP mappé. Laissez vide pour laisser les utilisateurs non mappés sans autorisations.",groupMapping:"Mappage de groupes (JSON)",groupMappingHint:"Associer les DN de groupes LDAP aux groupes BamBuddy. Groupes disponibles : ",testConnection:"Tester la connexion",settingsSaved:"Paramètres LDAP enregistrés",errors:{serverRequired:"L'URL du serveur LDAP est requise",searchBaseRequired:"Le DN de base de recherche est requis",enableAuthFirst:"Activez d'abord l'authentification",configureLdapFirst:"Enregistrez d'abord les paramètres LDAP"}},email:{smtpSettings:"Configuration SMTP",smtpHost:"Serveur SMTP",smtpPort:"Port SMTP",security:"Sécurité",authentication:"Authentification",username:"Utilisateur",password:"Mot de passe",fromEmail:"Email expéditeur",fromName:"Nom expéditeur",testConnection:"Tester la connexion SMTP",testRecipient:"Email test destinataire",sendTest:"Envoyer email test",sending:"Envoi...",save:"Enregistrer les paramètres",saving:"Enregistrement...",advancedAuth:"Authentification avancée",advancedAuthEnabled:"L'authentification avancée est activée",advancedAuthEnabledDesc:"La gestion des utilisateurs par email est active. Les nouveaux utilisateurs recevront un mot de passe auto-généré.",advancedAuthDisabled:"Authentification avancée désactivée",advancedAuthDisabledDesc:"Activez pour les fonctionnalités liées à l'email (mot de passe oublié, etc).",enable:"Activer",disable:"Désactiver",feature1:"Génération auto et envoi de mots de passe par email",feature2:"Connexion par utilisateur ou email",feature3:"Réinitialisation mot de passe oublié disponible",feature4:"Réinitialisation admin par email",errors:{requiredFields:"Remplissez tous les champs requis",usernameRequired:"L'utilisateur est requis pour l'authentification",enterTestEmail:"Entrez une adresse email de test",smtpServerAndEmail:"Serveur et expéditeur requis pour le test",usernamePasswordRequired:"Utilisateur et mot de passe requis pour l'auth",configureSmtpFirst:"Configurez et testez le SMTP d'abord",enableAuthFirst:"Veuillez d'abord activer l'authentification pour utiliser les fonctionnalités basées sur le courrier électronique."},success:{settingsSaved:"Paramètres SMTP enregistrés"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"Aucun (Port 25)"},authOptions:{enabled:"Activée",disabled:"Désactivée"}},appearance:"Apparence",notifications:"Notifications",smartPlugs:"Prises connectées",spoolman:"Spoolman",updates:"Mises à jour",language:"Langue",languageDescription:"Choisissez votre langue",theme:"Thème",themeLight:"Clair",themeDark:"Sombre",themeSystem:"Système",defaultView:"Vue par défaut",defaultViewDescription:"Page affichée au démarrage",checkForUpdates:"Vérifier les mises à jour",autoUpdate:"Mise à jour auto",currentVersion:"Version actuelle",latestVersion:"Dernière version",upToDate:"Bambuddy est à jour",updateAvailable:"Mise à jour disponible",notificationLanguage:"Langue des notifications",notificationLanguageDescription:"Langue pour les notifications push",bedCooledThreshold:"Seuil de refroidissement du plateau",bedCooledThresholdDescription:"Température en dessous de laquelle le plateau est considéré comme refroidi",userNotificationsEnabled:"Notifications utilisateur",userNotificationsEnabledDescription:"Active le menu de notifications utilisateur et les notifications par e-mail pour les événements d'impression. Nécessite l'authentification avancée.",userNotificationsDisabledHint:"Activez l'authentification avancée pour utiliser les notifications utilisateur.",notificationProviders:"Fournisseurs de notifications",addProvider:"Ajouter un fournisseur",editProvider:"Modifier le fournisseur",providerType:"Type de fournisseur",testNotification:"Tester la notification",testSuccess:"Notification de test envoyée",testFailed:"Échec de l'envoi du test",quietHours:"Heures de silence",quietHoursDescription:"Ne pas déranger pendant ces heures",quietHoursStart:"Début",quietHoursEnd:"Fin",events:{title:"Événements de notification",printStart:"Impression démarrée",printComplete:"Impression terminée",printFailed:"Impression échouée",printStopped:"Impression arrêtée",printProgress:"Jalons de progression",printProgressDescription:"Notifier à 25%, 50%, 75%",printerOffline:"Imprimante hors ligne",printerError:"Erreur imprimante",filamentLow:"Filament bas",maintenanceDue:"Maintenance due",maintenanceDueDescription:"Notifier quand une tâche est due"},smartPlug:{title:"Prises connectées",add:"Ajouter une prise",edit:"Modifier la prise",name:"Nom",ipAddress:"Adresse IP",linkedPrinter:"Imprimante liée",autoOn:"Allumage auto",autoOnDescription:"Allumer au début de l'impression",autoOff:"Extinction auto",autoOffDescription:"Éteindre après l'impression",offDelay:"Délai d'extinction",offDelayMinutes:"Minutes après fin",offDelayTemp:"Quand la buse est sous",currentState:"État actuel",turnOn:"Allumer",turnOff:"Éteindre"},filamentTracking:"Suivi de Filament",filamentTrackingDesc:"Choisissez comment suivre vos bobines. Utilisez l'inventaire intégré ou connectez un serveur Spoolman.",filamentChecks:"Vérifications du filament",disableFilamentWarnings:"Désactiver les avertissements de filament",disableFilamentWarningsDesc:"Ne pas afficher les avertissements de filament insuffisant lors de l'impression ou de la mise en file d'attente",preferLowestFilament:"Préférer le filament le plus bas",preferLowestFilamentDesc:"Lorsque plusieurs bobines correspondent, utiliser celle avec le moins de filament restant",trackingModeBuiltIn:"Inventaire Intégré",trackingModeBuiltInDesc:"Correspondance RFID et suivi de consommation inclus",trackingModeSpoolmanDesc:"Serveur de gestion externe",builtInFeatureRfid:"Détecte auto les bobines RFID Bambu Lab dans l'AMS",builtInFeatureUsage:"Suit la consommation par impression",builtInFeatureCatalog:"Gère bobines, couleurs et profils facteur K",builtInFeatureThirdParty:"Les bobines tierces peuvent être assignées aux bobines d'inventaire",amsSyncButton:"Synchroniser les poids depuis l'AMS",amsSyncTitle:"Synchroniser les poids des bobines depuis l'AMS",amsSyncMessage:"Tous les poids des bobines de l'inventaire seront écrasés par les valeurs actuelles de l'AMS des imprimantes connectées. Utilisez ceci pour récupérer des données de poids corrompues. Les imprimantes doivent être en ligne.",amsSyncing:"Synchronisation...",amsSyncSuccess:"{{synced}} bobine(s) synchronisée(s), {{skipped}} ignorée(s)",amsSyncError:"Échec de la synchronisation des poids depuis l'AMS",spoolmanUrl:"URL Spoolman",spoolmanUrlHint:"URL de votre serveur Spoolman (ex: http://localhost:7912)",spoolmanConnected:"Connecté",spoolmanDisconnected:"Déconnecté",status:"Statut",connect:"Connecter",disconnect:"Déconnecter",howSyncWorks:"Fonctionnement de la Sync",syncInfoRfidOnly:"Seules les bobines officielles RFID sont synchronisées",syncInfoAutoCreate:"Les bobines sont créées dans Spoolman à la 1ère sync",syncInfoThirdPartySkipped:"Les bobines tierces ou rechargées sont ignorées",linkingExistingSpools:"Lier des bobines existantes",linkingExistingSpoolsDesc:'Pour lier une bobine Spoolman, survolez un slot AMS et cliquez sur "Lier à Spoolman".',syncMode:"Mode de Sync",syncModeAuto:"Automatique",syncModeManual:"Manuel uniquement",syncModeAutoDesc:"Sync auto lors de changements AMS",syncModeManualDesc:"Sync uniquement sur déclenchement manuel",syncAmsData:"Synchroniser AMS",syncAmsDataDesc:"Synchroniser manuellement les données vers Spoolman",allPrinters:"Toutes les imprimantes",noDefaultPrinter:"Aucune par défaut (demander à chaque fois)",sidebarOrder:"Ordre de la barre latérale",saveThumbnails:"Enregistrer les vignettes",captureFinishPhoto:"Prendre une photo à la fin",noPrintersConfigured:"Aucune imprimante configurée",archiveMode:{always:"Toujours créer une archive",never:"Ne jamais créer d'archive",ask:"Demander à chaque fois"},checkForUpdatesLabel:"Vérifier les mises à jour",checkPrinterFirmware:"Vérifier le firmware imprimante",includeBetaUpdates:"Inclure les versions bêta",includeBetaUpdatesDesc:"Notifier des versions bêta et préliminaires lors de la vérification des mises à jour",enableRetry:"Activer la rétentative",homeAssistantDescription:"Contrôler les prises via Home Assistant",environmentManagedLabel:"(Géré par l'environnement)",autoEnabledViaEnv:"Activé via variables d'environnement",urlFromEnvReadOnly:"Valeur HA_URL (lecture seule)",tokenFromEnvReadOnly:"Valeur HA_TOKEN (lecture seule)",mqttConnectedTo:"Connecté à",prometheusDescription:"Exposer les données au format Prometheus",noSmartPlugsTitle:"Aucune prise configurée",noSmartPlugsDescription:"Ajoutez une prise Tasmota pour suivre l'énergie et automatiser.",noProvidersTitle:"Aucun fournisseur configuré",noProvidersDescription:"Ajoutez un fournisseur pour recevoir des alertes.",noTemplatesAvailable:"Aucun modèle dispo. Redémarrez pour les générer.",apiPermissionView:"Voir statut et file",apiPermissionEdit:"Gérer la file d'attente",apiKeysEmptyTitle:"Aucune clé API",apiKeysEmptyDescription:"Créez une clé pour vos intégrations.",noUsersFound:"Aucun utilisateur trouvé",noGroupsFound:"Aucun groupe trouvé",noGroupsAvailable:"Aucun groupe disponible",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",systemGroupWarning:"Les noms des groupes système sont fixes",authDisabledTitle:"Authentification désactivée",authDisabledFeature1:"Requis pour accéder au système",authDisabledFeature2:"Gestion multi-utilisateurs et groupes",authDisabledFeature3:"Plus de 50 permissions granulaires",userHasCreated:"Cet utilisateur a créé :",userItemsQuestion:"Que faire de ces éléments ?",deleteUserConfirm:"Supprimer cet utilisateur ?",actionCannotBeUndone:"Cette action est irréversible.",addFirstSmartPlug:"Ajoutez votre première prise",providers:"Fournisseurs",log:"Journal",testAll:"Tout tester",testResults:"Résultats du test",testPassedCount:"{{count}} succès",testFailedCount:"{{count}} échecs",messageTemplates:"Modèles de message",messageTemplatesDescription:"Personnalisez les messages par événement.",apiKeys:"Clés API",apiKeysDescription:"Créez des clés pour webhooks et API.",createKey:"Créer une clé",apiKeyCreated:"Clé API créée avec succès",apiKeyCopyWarning:"Copiez cette clé maintenant - elle ne sera plus affichée !",useInApiBrowser:"Utiliser dans l'explorateur API",createNewApiKey:"Nouvelle clé API",keyName:"Nom de la clé",keyNamePlaceholder:"ex: Home Assistant, OctoPrint",readStatus:"Lire le statut",readStatusDescription:"Voir les imprimantes et la file",manageQueue:"Gérer la file",manageQueueDescription:"Ajouter/retirer des éléments",controlPrinter:"Contrôler l'imprimante",controlPrinterDescription:"Pause, reprise, arrêt",unnamedKey:"Clé sans nom",lastUsed:"Dernière utilisation",read:"Lecture",control:"Contrôle",createFirstKey:"Créez votre première clé",webhookEndpoints:"Points de terminaison Webhook",webhookApiKeyHint:"Utilisez la clé dans l'en-tête X-API-Key.",webhook:{getAllStatus:"Tous les statuts",getSpecificStatus:"Statut spécifique",addToQueue:"Ajouter à la file",pausePrint:"Pause",resumePrint:"Reprise",stopPrint:"Arrêt"},apiBrowser:"Explorateur API",apiBrowserDescription:"Testez les endpoints API.",apiKeyForTesting:"Clé API pour test",apiKeyPlaceholder:"Collez votre clé pour tester...",apiKeyHint:"Sera envoyée via l'en-tête X-API-Key.",deleteApiKeyTitle:"Supprimer la clé API",deleteApiKeyMessage:"Les intégrations utilisant cette clé cesseront de fonctionner.",deleteKey:"Supprimer la clé",amsDisplayThresholds:"Seuils d'affichage AMS",amsThresholdsDescription:"Seuils de couleur pour humidité et température.",humidity:"Humidité",goodGreen:"Bon (vert)",fairOrange:"Moyen (orange)",aboveFairBad:"Au-dessus = rouge (mauvais)",fairAlsoDryingThreshold:"Ce seuil est aussi utilisé pour déclencher le séchage automatique",temperature:"Température",goodBlue:"Bon (bleu)",aboveFairHot:"Au-dessus = rouge (chaud)",historyRetention:"Rétention d'historique",keepSensorHistory:"Garder l'historique pendant",historyRetentionDescription:"Les anciennes données seront supprimées.",defaultPrintOptions:"Options d'impression par défaut",defaultPrintOptionsDescription:"Définir les valeurs par défaut des options d'impression. Modifiables dans la boîte de dialogue d'impression.",defaultBedLevelling:"Nivellement du lit",defaultBedLevellingDesc:"Niveler automatiquement le lit avant l'impression",defaultFlowCali:"Calibration du flux",defaultFlowCaliDesc:"Calibrer le flux d'extrusion",defaultVibrationCali:"Calibration des vibrations",defaultVibrationCaliDesc:"Réduire les artefacts de ringing",defaultLayerInspect:"Inspection première couche",defaultLayerInspectDesc:"Inspection IA de la première couche",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Enregistrer une vidéo timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Confirmation de plateau libre",requirePlateClear:"Exiger la confirmation de plateau libre",requirePlateClearDescription:"Lorsque activé, le planificateur attend la confirmation de plateau libre par imprimante avant de lancer les impressions en file d'attente sur les imprimantes ayant terminé. Désactivez pour les workflows de ferme où les plateaux sont vérifiés physiquement.",gcodeInjection:"Injection de G-code",gcodeInjectionDescription:"Configurez du G-code personnalisé à injecter au début et/ou à la fin des impressions pour les systèmes d'auto-impression comme Farmloop, SwapMod, AutoClear et Printflow 3D. Les snippets sont configurés par modèle d'imprimante et appliqués lorsque « Injecter le G-code » est activé sur un élément de file d'attente.",gcodeInjectionNoPrinters:"Aucune imprimante trouvée. Ajoutez des imprimantes pour configurer les snippets G-code.",gcodeStartLabel:"G-code de début",gcodeEndLabel:"G-code de fin",gcodeStartPlaceholder:"G-code ajouté avant le début de l'impression...",gcodeEndPlaceholder:"G-code ajouté après la fin de l'impression...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Séchage automatique",queueDryingDescription:"Sécher automatiquement le filament AMS lorsque l'imprimante est inactive entre les impressions. Utilise le seuil d'humidité ci-dessus.",queueDryingEnabled:"Activer le séchage automatique",queueDryingEnabledDescription:"Démarrer le séchage AMS automatiquement lorsque l'imprimante est inactive et l'humidité dépasse le seuil",queueDryingBlock:"Attendre la fin du séchage",queueDryingBlockDescription:"Bloquer la file d'attente jusqu'à la fin du séchage. Désactivé, les impressions sont prioritaires.",ambientDryingEnabled:"Séchage ambiant",ambientDryingEnabledDescription:"Sécher automatiquement le filament sur les imprimantes inactives lorsque l'humidité dépasse le seuil, même sans impressions en file.",dryingPresets:"Préréglages de séchage",dryingPresetsDescription:"Température et durée par type de filament. AMS 2 Pro utilise des températures plus basses, AMS-HT supporte des températures plus élevées.",dryingFilament:"Filament",printModal:"Fenêtre d'impression",expandCustomMapping:"Étendre le mapping personnalisé par défaut",expandCustomMappingDescription:"Affiche le mapping AMS par imprimante étendu.",authentication:"Authentification",authEnabledDescription:"L'instance est sécurisée",authDisabledDescription:"Activez pour restreindre l'accès",authDisabledMessage:"Activez l'authentification pour gérer comptes et permissions.",enableAuthentication:"Activer l'authentification",currentUser:"Utilisateur actuel",changePassword:"Changer le mot de passe",admin:"Admin",users:"Utilisateurs",addUser:"Ajouter un utilisateur",groups:"Groupes",addGroup:"Ajouter un groupe",system:"Système",noDescription:"Pas de description",userCount:"{{count}} utilisateurs",permissionCount:"{{count}} permissions",createUser:"Créer un utilisateur",username:"Nom d'utilisateur",enterUsername:"Entrez l'utilisateur",password:"Mot de passe",enterPassword:"Mot de passe (min 6 char)",confirmPassword:"Confirmer le mot de passe",confirmPasswordPlaceholder:"Confirmez le mot de passe",viewReleaseOnGitHub:"Voir la version sur GitHub",turnAllPlugsOn:"Tout allumer",turnAllPlugsOff:"Tout éteindre",clearNotificationLogs:"Effacer les journaux",clearLogsMessage:"Efface définitivement les logs de plus de 30 jours.",clearLogs:"Effacer les logs",resetUiPreferences:"Réinitialiser l'UI",resetUiPreferencesMessage:"Réinitialise l'ordre, thème, widgets, etc. N'affecte pas vos données.",resetPreferences:"Réinitialiser",deleteGroupTitle:"Supprimer le groupe",deleteGroupMessage:"Les utilisateurs de ce groupe perdront ces permissions.",deleteGroup:"Supprimer le groupe",disableAuthenticationTitle:"Désactiver l'authentification",disableAuthenticationMessage:"Instance accessible sans connexion. Les comptes sont conservés.",disableAuthentication:"Désactiver",configureBambuddy:"Configurer Bambuddy",systemDefault:"Défaut système",archiveSettings:"Réglages Archives",newWindow:"Nouvelle fenêtre",embeddedOverlay:"Superposition intégrée",preferredSlicer:"Slicer préféré",preferredSlicerDescription:"Application pour ouvrir les fichiers",externalCameras:"Caméras externes",costTracking:"Suivi des coûts",printsOnly:"Impressions uniquement",totalConsumption:"Consommation totale",dataManagement:"Gestion des données",storageUsage:"Utilisation du stockage",storageUsageDescription:"Répartition de l'utilisation des données par catégorie",storageUsageTotal:"Total",storageUsageErrors:"Erreurs",storageUsageOtherBreakdown:"Autre (inclut ressources statiques, scripts et fichiers de configuration)",storageUsageSystem:"Système",storageUsageData:"Données",storageUsageUnavailable:"Informations d'utilisation du stockage non disponibles",clearNotificationLogsDescription:"Supprimer logs de plus de 30 jours",resetUiPreferencesDescription:"Réinitialise thèmes et affichage sans toucher aux données.",enableHomeAssistant:"Activer Home Assistant",enableMqtt:"Activer MQTT",useTls:"Utiliser TLS",enableMetricsEndpoint:"Activer l'endpoint Metrics",availableMetrics:"Metrics disponibles",editUser:"Modifier l'utilisateur",deleteUserTitle:"Supprimer l'utilisateur",groupName:"Nom du groupe",leaveEmptyForAnonymous:"Vide pour anonyme",leaveEmptyForNoAuth:"Vide si pas d'auth",enterNewPassword:"Nouveau mot de passe",confirmNewPassword:"Confirmer nouveau mdp",enterGroupName:"Entrez le nom du groupe",enterDescriptionOptional:"Description (optionnel)",enterCurrentPassword:"Mdp actuel",enterNewPasswordMin6:"Nouveau mdp (min 6 char)",toast:{keyCopied:"Clé copiée",copyFailed:"Échec copie",keyAddedToBrowser:"Clé ajoutée à l'explorateur",clearLogsFailed:"Échec effacement logs",uiPreferencesReset:"Préférences UI réinitialisées. Rafraîchissement...",authDisabled:"Authentification désactivée",authDisableFailed:"Échec désactivation",apiKeyCreated:"Clé API créée",apiKeyDeleted:"Clé API supprimée",userCreated:"Utilisateur créé",userUpdated:"Utilisateur mis à jour",userDeleted:"Utilisateur supprimé",groupCreated:"Groupe créé",groupUpdated:"Groupe mis à jour",groupDeleted:"Groupe supprimé",fillRequiredFields:"Remplissez les champs requis",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères",enterGroupName:"Entrez un nom de groupe",settingsSaved:"Paramètres enregistrés",cameraSettingsSaved:"Réglages caméra enregistrés",enterCameraUrl:"Entrez une URL caméra",passwordChanged:"Mot de passe modifié",connectionFailed:"Échec connexion",testFailed:"Échec test",cameraConnected:"Caméra connectée {{resolution}}"},testConnection:"Tester la connexion",catalog:{spoolCatalog:"Catalogue de Bobines",spoolCatalogDescription:"Poids des bobines vides par marque/type. Utilisé pour le calcul auto du poids restant.",searchCatalog:"Chercher dans le catalogue...",addNewEntry:"Nouvelle Entrée",namePlaceholder:"Nom (ex: Bambu Lab - Plastique)",weight:"Poids",type:"Type",default:"Défaut",custom:"Perso",noMatch:"Aucune entrée correspondante",empty:"Catalogue vide",deleteEntry:"Supprimer l'entrée",deleteConfirm:'Supprimer "{{name}}" ?',resetCatalog:"Réinitialiser le catalogue",resetConfirm:"Réinitialiser aux valeurs par défaut ? Vos entrées personnalisées seront supprimées.",loadFailed:"Échec chargement catalogue",nameWeightRequired:"Nom et poids requis",entryAdded:"Entrée ajoutée",addFailed:"Échec ajout",entryUpdated:"Entrée mise à jour",updateFailed:"Échec mise à jour",entryDeleted:"Entrée supprimée",deleteFailed:"Échec suppression",resetSuccess:"Catalogue réinitialisé",resetFailed:"Échec réinitialisation",exported:"{{count}} entrées exportées",imported:"{{added}} entrées importées ({{skipped}} ignorées)",importFailed:"Échec import : format JSON invalide",exportTooltip:"Exporter en JSON",importTooltip:"Importer depuis JSON",resetTooltip:"Réinitialiser par défaut",selectedCount:"{{count}} sélectionnés",deleteSelected:"Supprimer la sélection",bulkDeleteConfirm:"Supprimer {{count}} entrées ?",bulkDeleted:"{{count}} entrées supprimées",bulkDeleteFailed:"Échec de la suppression"},colorCatalog:{title:"Catalogue de Couleurs",description:"Couleurs de filament par fabricant. Utilisé pour la recherche auto lors de l'ajout de bobines.",searchColors:"Chercher couleurs...",allManufacturers:"Tous les fabricants",addNewColor:"Nouvelle Couleur",manufacturer:"Fabricant",colorName:"Nom couleur",hex:"Hex",materialOptional:"Matériau (optionnel)",showing:"Affichage {{filtered}} sur {{total}} couleurs",noMatch:"Aucune couleur correspondante",empty:"Catalogue vide",deleteColor:"Supprimer couleur",deleteConfirm:'Supprimer "{{name}}" ?',resetCatalog:"Réinitialiser catalogue couleurs",resetConfirm:"Réinitialiser aux valeurs par défaut ?",sync:"Sync",starting:"Démarrage...",syncTooltip:"Sync depuis FilamentColors.xyz (2000+ couleurs, peut être long)",loadFailed:"Échec chargement catalogue couleurs",fieldsRequired:"Fabricant, nom et code Hex requis",colorAdded:"Couleur ajoutée",addFailed:"Échec ajout",colorUpdated:"Couleur mise à jour",updateFailed:"Échec mise à jour",colorDeleted:"Couleur supprimée",deleteFailed:"Échec suppression",resetSuccess:"Catalogue réinitialisé",resetFailed:"Échec réinitialisation",syncUpToDate:"Déjà à jour ({{count}} couleurs vérifiées)",syncComplete:"{{added}} couleurs ajoutées ({{skipped}} déjà présentes)",syncError:"Erreur de sync",syncFailed:"Échec sync FilamentColors.xyz",exported:"{{count}} couleurs exportées",imported:"{{added}} couleurs importées ({{skipped}} ignorées)",importFailed:"Échec import : format JSON invalide",selectedCount:"{{count}} sélectionnés",deleteSelected:"Supprimer la sélection",bulkDeleteConfirm:"Supprimer {{count}} couleurs ?",bulkDeleted:"{{count}} couleurs supprimées",bulkDeleteFailed:"Échec de la suppression des couleurs"},dateFormat:"Format de date",dateFormatUs:"US (MM/JJ/AAAA)",dateFormatEu:"EU (JJ/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-JJ)",timeFormat:"Format horaire",timeFormat12:"12 heures (3:30 PM)",timeFormat24:"24 heures (15:30)",defaultPrinter:"Imprimante par défaut",defaultPrinterDescription:"Présélectionner cette imprimante pour les téléversements, réimpressions et autres opérations.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Glissez les éléments dans la barre latérale pour réorganiser. Réinitialiser l'ordre par défaut ici.",setDefault:"Définir par défaut",sidebarOrderSetDefaultHint:"Définir par défaut applique l'ordre actuel du menu aux utilisateurs qui n'ont pas encore personnalisé le leur.",sidebarDefaultSet:"L'ordre du menu par défaut a été défini.",sidebarDefaultCleared:"Ordre du menu par défaut effacé.",sidebarDefaultFailed:"Échec de la définition de l'ordre du menu par défaut.",reset:"Réinitialiser",darkMode:"Mode sombre",lightMode:"Mode clair",active:"(actif)",background:"Arrière-plan",accent:"Accent",style:"Style",bgNeutral:"Neutre",bgWarm:"Chaud",bgCool:"Froid",bgOled:"OLED Noir",bgSlate:"Bleu ardoise",bgForest:"Vert forêt",accentGreen:"Vert",accentTeal:"Sarcelle",accentBlue:"Bleu",accentOrange:"Orange",accentPurple:"Violet",accentRed:"Rouge",styleClassic:"Classique",styleGlow:"Lumineux",styleVibrant:"Vibrant",themeToggleHint:"Basculer entre le mode sombre et clair avec l'icône soleil/lune dans la barre latérale.",autoArchivePrints:"Archiver automatiquement les impressions",autoArchiveDescription:"Sauvegarder automatiquement les fichiers 3MF à la fin des impressions",saveThumbnailsDescription:"Extraire et sauvegarder les images d'aperçu des fichiers 3MF",captureFinishPhotoDescription:"Prendre une photo avec la caméra de l'imprimante à la fin de l'impression",ffmpegNotInstalled:"ffmpeg non installé",ffmpegRequired:"La capture caméra nécessite ffmpeg. Installez-le via <brew>brew install ffmpeg</brew> (macOS) ou <apt>apt install ffmpeg</apt> (Linux).",camera:"Caméra",cameraViewMode:"Mode d'affichage caméra",cameraOverlayDescription:"La caméra s'ouvre dans un overlay redimensionnable sur l'écran principal",cameraWindowDescription:"La caméra s'ouvre dans une fenêtre de navigateur séparée",externalCamerasDescription:"Configurer des caméras externes pour remplacer la caméra intégrée. Supporte les flux MJPEG, RTSP, snapshots HTTP et caméras USB (V4L2). Lorsqu'activée, la caméra externe est utilisée pour la vue en direct et les photos de fin.",cameraPlaceholderUsb:"Chemin du périphérique (/dev/video0)",cameraPlaceholderUrl:"URL caméra (rtsp://... ou http://...)",cameraTypeMjpeg:"Flux MJPEG",cameraTypeRtsp:"Flux RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Caméra USB (V4L2)",cameraRotation:"Rotation",test:"Tester",connected:"Connecté",disconnected:"Déconnecté",currency:"Devise",defaultFilamentCost:"Coût filament par défaut (par kg)",electricityCost:"Coût électricité par kWh",energyDisplayMode:"Mode d'affichage énergie",energyModePrintDescription:"Le tableau de bord affiche la somme de l'énergie utilisée pendant les impressions",energyModeTotalDescription:"Le tableau de bord affiche l'énergie totale des prises connectées",fileManager:"Gestionnaire de fichiers",createArchiveEntry:"Créer une entrée d'archive lors de l'impression",createArchiveEntryDescription:"Lors de l'impression depuis le gestionnaire de fichiers, créer optionnellement une entrée d'archive",lowDiskSpaceWarning:"Avertissement espace disque faible",lowDiskSpaceDescription:"Afficher un avertissement lorsque l'espace disque libre descend sous ce seuil",printerFirmware:"Firmware imprimante",checkFirmwareDescription:"Vérifier les mises à jour firmware de Bambu Lab",bambuddySoftware:"Logiciel Bambuddy",autoCheckDescription:"Vérifier automatiquement les nouvelles versions au démarrage",checkNow:"Vérifier maintenant",updateAvailableVersion:"Mise à jour disponible : v{{version}}",releaseNotes:"Notes de version",updateViaDocker:"Mettre à jour via Docker Compose :",installUpdate:"Installer la mise à jour",latestVersionRunning:"Vous utilisez la dernière version",failedToCheckUpdates:"Échec de la vérification des mises à jour : {{error}}",backupRestore:"Sauvegarde & Restauration",backupRestoreDescription:"Exporter/importer les paramètres et configurer la sauvegarde GitHub",goToBackup:"Aller à la sauvegarde",externalUrl:"URL externe",externalUrlDescription:"L'URL externe où Bambuddy est accessible. Utilisée pour les images de notification et les intégrations externes.",bambuddyUrl:"URL Bambuddy",externalUrlHint:"Inclure le protocole et le port (ex : http://192.168.1.100:8000)",ftpRetry:"Réessai FTP",ftpRetryDescription:"Réessayer les opérations FTP lorsque le WiFi de l'imprimante est instable. S'applique aux téléchargements 3MF, uploads d'impression, téléchargements timelapse et mises à jour firmware.",autoRetryDescription:"Réessayer automatiquement les opérations FTP échouées",retryAttempts:"Tentatives de réessai",retryDelay:"Délai de réessai",connectionTimeout:"Délai de connexion",time_one:"{{count}} fois",time_other:"{{count}} fois",second_one:"{{count}} seconde",second_other:"{{count}} secondes",nSeconds:"{{count}} secondes",increaseForWeakWifi:"Augmenter pour les imprimantes avec un WiFi faible",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Se connecter à Home Assistant pour contrôler les prises connectées via l'API REST HA. Supporte les entités switch, light, input_boolean et script.",homeAssistantUrl:"URL Home Assistant",longLivedAccessToken:"Token d'accès longue durée",haTokenHint:"Créer un token dans HA : Profil → Tokens d'accès longue durée → Créer un token",connectionSuccessful:"Connexion réussie",connectionFailed:"Connexion échouée",haConnectionSuccess:"Connexion à Home Assistant réussie.",haConnectionFailed:"Échec de la connexion à Home Assistant.",mqttPublishing:"Publication MQTT",mqttDescription:"Publier les événements BamBuddy vers un broker MQTT externe pour l'intégration avec Node-RED, Home Assistant et d'autres systèmes d'automatisation.",mqttEnableDescription:"Publier les événements vers un broker MQTT externe",brokerHostname:"Nom d'hôte du broker",port:"Port",usernameOptional:"Nom d'utilisateur (optionnel)",passwordOptional:"Mot de passe (optionnel)",topicPrefix:"Préfixe de topic",topicPrefixHint:"Les topics seront : {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Métriques Prometheus",prometheusEndpointDescription:"Exposer les métriques imprimante sur <code>/api/v1/metrics</code> pour la surveillance Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (optionnel)",bearerTokenHint:"Si défini, les requêtes doivent inclure <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"État de connexion",metricsPrinterState:"État imprimante (idle/printing/etc)",metricsPrintProgress:"Progression impression 0-100%",metricsBedTemp:"Température du plateau",metricsNozzleTemp:"Température de la buse",metricsPrintsTotal:"Total impressions par résultat",metricsMore:"...et plus (couches, ventilateurs, file d'attente, utilisation filament)",smartPlugsDescription:"Connecter des prises connectées (Tasmota ou Home Assistant) pour automatiser le contrôle de l'alimentation et suivre la consommation d'énergie de vos imprimantes.",allOn:"Tout allumer",allOff:"Tout éteindre",addSmartPlug:"Ajouter une prise",energySummary:"Résumé énergétique",currentPower:"Puissance actuelle",plugsOnline:"{{reachable}}/{{total}} prises en ligne",today:"Aujourd'hui",yesterday:"Hier",total:"Total",enablePlugsForSummary:"Activer les prises pour voir le résumé énergétique",addNotificationProvider:"Ajouter",systemBadge:"(Système)",creating:"Création...",changing:"Modification...",deleteUserAndItems:"Supprimer l'utilisateur ET ses éléments",deleteUserKeepItems:"Supprimer l'utilisateur, garder les éléments (deviennent sans propriétaire)",ok:"OK"},notification:{printStarted:{title:"Impression démarrée",body:"{{printer}} : {{filename}} commence l'impression"},printCompleted:{title:"Impression terminée",body:"{{printer}} : {{filename}} a réussi"},printFailed:{title:"Impression échouée",body:"{{printer}} : {{filename}} a échoué"},printStopped:{title:"Impression arrêtée",body:"{{printer}} : {{filename}} a été arrêtée"},printProgress:{title:"Progression d'impression",body:"{{printer}} : {{filename}} est à {{percent}}%"},printerOffline:{title:"Imprimante hors ligne",body:"{{printer}} est déconnectée"},printerError:{title:"Erreur imprimante",body:"{{printer}} : {{error}}"},filamentLow:{title:"Filament bas",body:"{{printer}} : Le filament est presque vide"},maintenanceDue:{title:"Maintenance due",body:"{{printer}} : {{items}} demandent votre attention"}},errors:{generic:"Une erreur est survenue",networkError:"Erreur réseau. Vérifiez votre connexion.",notFound:"Non trouvé",unauthorized:"Non autorisé",serverError:"Erreur serveur",validationError:"Vérifiez vos saisies",printerConnectionFailed:"Échec connexion imprimante",saveFailed:"Échec enregistrement",deleteFailed:"Échec suppression",loadFailed:"Échec chargement"},hmsErrors:{title:"Erreurs - {{name}}",noErrors:"Aucune erreur",viewOnWiki:"Voir sur le Wiki Bambu Lab",clearInstructions:"Effacez les erreurs sur l'imprimante pour les retirer ici.",clearErrors:"Effacer les erreurs",clearSuccess:"Erreurs HMS effacées",clearFailed:"Échec de l'effacement des erreurs HMS"},mqttDebug:{title:"Journal de débogage MQTT",searchPlaceholder:"Chercher topic ou message...",noMessages:"Aucun message enregistré",startLoggingHint:'Cliquez sur "Démarrer" pour capturer les messages MQTT',noMessagesMatch:"Aucun message ne correspond",adjustFilterHint:"Ajustez votre recherche",incoming:"Entrant",outgoing:"Sortant",loggingStopped:"Enregistrement arrêté",loggingActive:"Enregistrement actif - rafraîchissement auto",startLogging:"Démarrer",stopLogging:"Arrêter",clearLog:"Effacer le journal",topic:"Topic",timestamp:"Horodatage",direction:"Direction",all:"Tous"},printerFiles:{title:"Gestionnaire de fichiers",storageUsed:"Utilisé :",storageFree:"Libre :",filterPlaceholder:"Filtrer les fichiers...",deleteButton:"Supprimer",deleteFiles:"Supprimer {{count}} fichiers",deleteFileConfirm:'Supprimer "{{name}}" ?',deleteFilesConfirm:"Supprimer les {{count}} fichiers sélectionnés ?",noFiles:"Aucun fichier sur l'imprimante",loadingFiles:"Chargement...",failedToLoad:"Échec chargement fichiers",toast:{filesDeleted:"{{count}} fichier(s) supprimé(s)",deleteFailed:"Échec suppression : {{error}}"}},confirm:{delete:"Voulez-vous vraiment supprimer cet élément ?",unsavedChanges:"Changements non sauvegardés. Voulez-vous quitter ?",clearQueue:"Voulez-vous vraiment vider la file d'attente ?"},login:{title:"Connexion Bambuddy",subtitle:"Connectez-vous à votre compte",username:"Utilisateur",usernamePlaceholder:"Entrez votre utilisateur",usernameOrEmail:"Utilisateur ou Email",usernameOrEmailPlaceholder:"Utilisateur ou @ Email",password:"Mot de passe",passwordPlaceholder:"Entrez votre mot de passe",signIn:"Se connecter",signingIn:"Connexion...",forgotPassword:"Mot de passe oublié ?",loginSuccess:"Connecté avec succès",loginFailed:"Échec de connexion",enterCredentials:"Entrez vos identifiants",forgotPasswordTitle:"Mot de passe oublié",forgotPasswordMessage:"Contactez votre administrateur pour réinitialiser votre accès.",forgotPasswordEmailMessage:"Entrez votre email pour recevoir un nouveau mot de passe.",emailAddress:"Adresse Email",emailPlaceholder:"votre.email@exemple.com",cancel:"Annuler",sending:"Envoi...",sendResetEmail:"Envoyer l'email",howToReset:"Comment réinitialiser :",resetStep1:"Contactez votre admin Bambuddy",resetStep2:"Demandez une réinitialisation dans la Gestion Utilisateurs",resetStep3:"Il vous donnera un mot de passe temporaire",resetStep4:"Connectez-vous et changez-le dans les Paramètres",gotIt:"Compris"},setup:{title:"Configuration Bambuddy",subtitle:"Configurez l'authentification",enableAuth:"Activer l'authentification",adminAccount:"Compte Admin",adminAccountDesc:"Si des admins existent, ils seront utilisés. Sinon, créez-en un ci-dessous.",adminUsername:"Utilisateur Admin",adminPassword:"Mot de passe Admin",optionalIfAdminExists:"(optionnel si admin existe)",adminUsernamePlaceholder:"Nom admin (optionnel)",adminPasswordPlaceholder:"Mdp admin (optionnel)",confirmPassword:"Confirmer mdp",confirmPasswordPlaceholder:"Confirmez mdp admin",settingUp:"Configuration...",completeSetup:"Terminer la configuration",toast:{authEnabledAdminCreated:"Authentification activée et admin créé",authEnabledExistingAdmins:"Authentification activée avec admins existants",setupCompleted:"Configuration terminée",enterBothCredentials:"Entrez les deux ou laissez vide pour utiliser les admins existants",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères"}},changePassword:{title:"Changer le mot de passe",currentPassword:"Mot de passe actuel",currentPasswordPlaceholder:"Entrez mdp actuel",newPassword:"Nouveau mot de passe",newPasswordPlaceholder:"Nouveau mdp (min 6 char)",confirmPassword:"Confirmer nouveau mdp",confirmPasswordPlaceholder:"Confirmez nouveau mdp",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères",changing:"Changement...",success:"Mot de passe modifié",failed:"Échec modification"},plateAlert:{title:"Impression en Pause !",message:"Objets détectés sur le plateau. L'impression a été suspendue automatiquement. Videz le plateau avant de reprendre.",understand:"J'ai compris"},camera:{title:"Vue Caméra",invalidPrinterId:"ID imprimante invalide",live:"Direct",snapshot:"Instantané",restartStream:"Redémarrer le flux",refreshSnapshot:"Rafraîchir l'image",fullscreen:"Plein écran",exitFullscreen:"Quitter plein écran",connectingToCamera:"Connexion caméra...",capturingSnapshot:"Capture...",connectionLost:"Connexion perdue",connectionFailed:"Échec connexion caméra",reconnecting:"Reconnexion dans {{countdown}}s... (essai {{attempt}}/{{max}})",reconnectNow:"Reconnexion immédiate",cameraUnavailable:"Caméra indisponible",cameraUnavailableDesc:"Vérifiez que l'imprimante est allumée.",noCamera:"Aucune caméra disponible",retry:"Réessayer",cameraStream:"Flux caméra",zoomOut:"Zoom arrière",zoomIn:"Zoom avant",resetZoom:"Réinitialiser zoom",recording:"Enregistrement",startRecording:"Démarrer l'enregistrement",stopRecording:"Arrêter l'enregistrement",chamberLight:"Basculer lumière chambre"},groups:{title:"Gestion des Groupes",subtitle:"Gérez les permissions pour le contrôle d'accès",backToSettings:"Retour aux paramètres",createGroup:"Créer un groupe",noPermission:"Accès refusé.",system:"Système",noDescription:"Pas de description",usersCount:"{{count}} utilisateurs",permissionsCount:"{{count}} permissions",edit:"Modifier",delete:"Supprimer",toast:{created:"Groupe créé",updated:"Groupe mis à jour",deleted:"Groupe supprimé",enterGroupName:"Entrez un nom de groupe"},modal:{editGroup:"Modifier le groupe",createGroup:"Créer un groupe",cancel:"Annuler",saving:"Enregistrement...",creating:"Création...",saveChanges:"Enregistrer"},form:{groupName:"Nom du groupe",groupNamePlaceholder:"Nom du groupe",systemGroupWarning:"Les groupes système sont fixes",description:"Description",descriptionPlaceholder:"Description (optionnel)",permissions:"Permissions ({{count}} sélectionnées)"},deleteModal:{title:"Supprimer le groupe",message:"Les utilisateurs de ce groupe perdront ces permissions.",confirm:"Supprimer"},editor:{title:"Modifier le groupe",createTitle:"Créer un groupe",search:"Rechercher des permissions...",selectAll:"Tout sélectionner",clearAll:"Tout désélectionner",permissionsSelected:"{{count}} sélectionnée(s)",noResults:"Aucune permission ne correspond à votre recherche"}},users:{title:"Gestion des Utilisateurs",subtitle:"Gérez les accès à Bambuddy",backToSettings:"Retour aux paramètres",createUser:"Créer un utilisateur",noPermission:"Accès refusé.",admin:"Admin",noGroups:"Aucun groupe",active:"Actif",inactive:"Inactif",edit:"Modifier",delete:"Supprimer",system:"Système",noGroupsAvailable:"Aucun groupe disponible",table:{username:"Utilisateur",groups:"Groupes",status:"Statut",actions:"Actions"},toast:{created:"Utilisateur créé",updated:"Utilisateur mis à jour",deleted:"Utilisateur supprimé",fillRequired:"Remplissez les champs requis",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères"},modal:{createUser:"Créer utilisateur",editUser:"Modifier utilisateur",cancel:"Annuler",creating:"Création...",saving:"Enregistrement...",saveChanges:"Enregistrer",advancedAuthSubtitle:"avec Authentification Avancée"},form:{username:"Utilisateur",usernamePlaceholder:"Nom utilisateur",email:"Email",emailPlaceholder:"utilisateur@exemple.com",password:"Mot de passe",passwordPlaceholder:"Mot de passe",confirmPassword:"Confirmer mdp",confirmPasswordPlaceholder:"Confirmez mdp",newPasswordPlaceholder:"Nouveau mdp",confirmNewPasswordPlaceholder:"Confirmez nouveau mdp",leaveBlankToKeep:"Laissez vide pour conserver l'actuel",groups:"Groupes",optional:"optionnel",autoGeneratedPassword:"Un mot de passe sera généré et envoyé par email.",passwordManagedByAdvancedAuth:'Géré par Auth Avancée. Utilisez "Réinitialiser" pour envoyer un nouveau mdp par email.',resetPassword:"Réinitialiser le mot de passe",resettingPassword:"Réinitialisation..."},deleteModal:{title:"Supprimer utilisateur",message:"Cette action est irréversible.",confirm:"Supprimer"}},streamOverlay:{title:"Superposition Flux",invalidPrinterId:"ID invalide",cameraStream:"Flux caméra",progress:"Progression",eta:"Fin estimée",printerIdle:"Imprimante inactive",printerOffline:"Imprimante hors ligne",status:{printing:"Impression",paused:"En pause",finished:"Terminée",failed:"Échouée",idle:"Inactive",unknown:"Inconnue"}},profiles:{title:"Profils",subtitle:"Gérez vos presets slicer et calibrations Pressure Advance",tabs:{cloud:"Profils Cloud",local:"Profils Locaux",kprofiles:"K-Profiles"},localProfiles:{title:"Profils Locaux",subtitle:"Gérez vos presets OrcaSlicer",import:"Importer Profils",importDesc:"Déposez les fichiers .bbscfg, .bbsflmt, .orca_filament, .zip ou .json",importing:"Importation...",search:"Chercher un preset...",noPresets:"Aucun preset local",badge:"Local",edit:"Modifier",delete:"Supprimer",cancel:"Annuler",deleteConfirmTitle:"Supprimer Preset",deleteConfirm:"Supprimer définitivement ce preset ?",source:"Source",inheritsFrom:"Hérite de",filamentType:"Type",vendor:"Vendeur",compatiblePrinters:"Imprimantes",nozzleTemp:"Temp Buse",cost:"Coût",density:"Densité",pressureAdvance:"Pressure Advance",filament:"Filament",process:"Processus",printer:"Imprimante",toast:{importSuccess:"{{count}} profil(s) importé(s)",importSkipped:"{{count}} profil(s) ignoré(s) (doublons)",importError:"{{count}} erreur(s) d'import",deleted:"Preset supprimé",updated:"Preset mis à jour"}},connectedAs:"Connecté en tant que",logout:"Déconnexion",noLogoutPermission:"Pas d'autorisation de déconnexion",failedToLoad:"Échec chargement profils",retry:"Réessayer",time:{justNow:"À l'instant",minsAgo:"Il y a {{count}}m",hoursAgo:"Il y a {{count}}h",daysAgo:"Il y a {{count}}j"},toast:{loggedOut:"Déconnecté"},login:{title:"Connexion Bambu Cloud",subtitle:"Synchronisez vos presets slicer",email:"Email",password:"Mot de passe",region:"Région",regionGlobal:"Global",regionChina:"Chine",verificationCode:"Code de vérification",totpCode:"Code Authenticator",checkEmail:"Code envoyé à {{email}}",enterTotpHint:"Entrez le code 2FA",accessToken:"Jeton d'accès (Access Token)",accessTokenHint:"Collez le jeton (depuis Bambu Studio)",back:"Retour",loginButton:"Connexion",verifyButton:"Vérifier",setTokenButton:"Définir Jeton",useToken:"Utiliser jeton d'accès",useEmail:"Connexion par email",toast:{loggedIn:"Connecté avec succès",codeSent:"Code envoyé par email",enterTotp:"Entrez le code Authenticator",tokenSet:"Jeton défini"}},presets:{myPreset:"Mon preset (modifiable)",duplicate:"Dupliquer",editable:"Modifiable",failedToLoadDetails:"Échec détails preset",deleteConfirm:"Supprimer ce preset ?",deleteWarning:'Ceci supprimera "{{name}}" de Bambu Cloud définitivement.',noDuplicatePermission:"Pas d'autorisation duplication",noEditPermission:"Pas d'autorisation modification",noDeletePermission:"Pas d'autorisation suppression",types:{filament:"Preset filament",printer:"Preset imprimante",process:"Preset processus"},toast:{deleted:"Preset supprimé",created:"Preset créé",updated:"Preset mis à jour",duplicated:"Preset dupliqué",fieldAdded:'Champ "{{key}}" ajouté',exported:"Preset exporté"},baseLabel:"Base : {{name}}",currentLabel:"Actuel : {{name}}",newPreset:"Nouveau Preset",editPreset:"Modifier Preset",duplicatePreset:"Dupliquer Preset",createNewPreset:"Créer un nouveau Preset",customizeSettings:"Personnalisez vos réglages",compareWithBase:"Comparer avec la base",compare:"Comparer",basePreset:"Preset de base",selectBasePreset:"Choisir preset de base...",presetName:"Nom du preset",myCustomPreset:"Mon preset personnalisé",inheritsFrom:"Hérite de",dropJsonToImport:"Glissez JSON pour importer",tabs:{common:"Commun",allFields:"Tous les champs"},availableFields:"Champs disponibles",searchFieldsPlaceholder:"Chercher un champ...",noMatchingFields:"Aucun champ trouvé",allFieldsAdded:"Tous les champs sont ajoutés",addCustomField:"Ajouter un champ personnalisé",yourOverrides:"Vos modifications",noOverridesYet:"Aucune modification",clickFieldsToAdd:"Cliquez à gauche pour ajouter",saveAsTemplate:"Enregistrer comme modèle",jsonTip:"Conseil : Glissez un .json pour importer les réglages"},cloudView:{searchPlaceholder:"Chercher presets...",templates:"Modèles",refresh:"Rafraîchir",newPreset:"Nouveau Preset",clearFilters:"Effacer filtres",compareMode:"Mode Comparaison",selectAnotherPreset:"Choisir un autre preset {{type}}",clickTwoPresets:"Choisissez deux presets de même type",selectFirst:"1. Sélectionner premier",selectSecond:"2. Sélectionner second",compareNow:"Comparer maintenant",lastSynced:"Synchronisé :",showingCount:"{{showing}} sur {{total}} presets",noPresetsFound:"Aucun preset trouvé",columns:{filament:"Filament",process:"Processus",printer:"Imprimante"},noFilamentPresets:"Pas de preset filament",noProcessPresets:"Pas de preset processus",noPrinterPresets:"Pas de preset imprimante",filters:{type:"Type",owner:"Propriétaire",printer:"Imprimante",nozzle:"Buse",filament:"Filament",layer:"Couche",all:"Tous",myPresets:"Mes Presets",builtIn:"Inclus",process:"Processus"},noTemplatesPermission:"Pas d'autorisation modèles",noRefreshPermission:"Pas d'autorisation rafraîchissement",noCreatePermission:"Pas d'autorisation création"},templates:{title:"Modèles rapides",noTemplates:"Aucun modèle",createFirst:"Créez-en depuis l'éditeur de preset",typeFilter:"Type :",deleteTitle:"Supprimer modèle",deleteWarning:"Action irréversible",deleteConfirm:'Supprimer "{{name}}" ?',namePlaceholder:"Nom du modèle",descriptionPlaceholder:"Description",settingsJson:"Paramètres (JSON)",fieldsCount:"{{count}} champs",shownInModals:"Visible dans fenêtres",hiddenInModals:"Masqué dans fenêtres",apply:"Appliquer",toast:{deleted:"Modèle supprimé",updated:"Modèle mis à jour",created:"Modèle créé",applied:"Modèle appliqué"}}},support:{debugLoggingActive:"Débogage actif",manageLogs:"Gérer",collectItem7:"Connectivité et versions firmware",collectItem8:"Statut intégrations (Spoolman, MQTT, HA)",collectItem9:"Interfaces réseau (sous-réseaux)",collectItem10:"Versions packages Python",collectItem11:"Santé base de données",collectItem12:"Détails environnement Docker"},fileManager:{title:"Gestionnaire de fichiers",subtitle:"Organisez vos fichiers d'impression",uploadFiles:"Téléverser fichiers",newFolder:"Nouveau dossier",folderName:"Nom du dossier",folderNamePlaceholder:"ex: Pièces Utiles",renameFile:"Renommer fichier",renameFolder:"Renommer dossier",moveFiles:"Déplacer {{count}} fichier(s)",rootNoFolder:"Racine (aucun dossier)",current:"actuel",linkFolder:"Lier le dossier",linkFolderDescription:'Lier "{{name}}" à un projet ou archive.',project:"Projet",archive:"Archive",noProjectsFound:"Aucun projet trouvé",noArchivesFound:"Aucune archive trouvée",unlink:"Délier",link:"Lier",dragDropFiles:"Glissez les fichiers ici",dropFilesHere:"Déposez ici",orClickToBrowse:"ou cliquez pour parcourir",allFileTypesSupported:"Tous types supportés. ZIP extraits.",zipFilesDetected:"ZIP détectés",zipExtractOptions:"Choix de structure pour ZIP :",preserveZipStructure:"Garder structure ZIP",createFolderFromZip:"Dossier par nom du ZIP",stlThumbnailGeneration:"Vignettes STL",zipMayContainStl:"Extraction vignettes possible pour STL.",thumbnailsCanBeGenerated:"Génération vignettes (peut être long).",generateThumbnailsForStl:"Générer vignettes STL",threemfDetected:"Fichiers 3MF détectés",threemfExtractionInfo:"Réglages extraits auto du 3MF.",willBeExtracted:"Sera extrait",filesExtracted:"{{count}} fichiers extraits",uploadComplete:"Terminé : {{succeeded}} succès",uploadFailed:"Échec du téléversement",zipFilesFailed:"{{count}} fichiers échoués",uploading:"Téléversement...",changeLink:"Modifier lien...",linkTo:"Lier à...",linkToProjectOrArchive:"Lier à projet ou archive",addToQueue:"Ajouter à la file",schedulePrint:"Planifier",generateThumbnail:"Générer vignette",generateThumbnails:"Générer vignettes",generateThumbnailsForMissing:"Vignettes STL manquantes",gridView:"Grille",listView:"Liste",lowDiskSpaceWarning:"Espace disque faible",lowDiskSpaceDetails:"{{free}} libre sur {{total}}. Seuil : {{threshold}} Go.",files:"Fichiers",folders:"Dossiers",size:"Taille",free:"Libre",allFiles:"Tous les fichiers",wrap:"Retour ligne",enableTextWrapping:"Activer retour ligne",disableTextWrapping:"Désactiver retour ligne",dragToResizeTooltip:"Glisser pour redimensionner, double-clic reset",searchFiles:"Chercher fichiers...",allTypes:"Tous types",prints:"Impressions",ascending:"Croissant",descending:"Décroissant",resultsCount:"{{showing}} sur {{total}} fichiers",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",selected:"{{count}} sélectionnés",adding:"Ajout...",loadingFiles:"Chargement...",folderIsEmpty:"Dossier vide",noFilesYet:"Aucun fichier",folderEmptyDescription:"Téléversez ou déplacez des fichiers ici.",noFilesDescription:"Téléversez des fichiers pour organiser.",noMatchingFiles:"Aucun fichier correspondant",noMatchingFilesDescription:"Ajustez votre recherche.",clearFilters:"Effacer filtres",printedCount:"Imprimé {{count}}x",uploadedBy:"Téléversé par",deleteFolder:"Supprimer dossier",deleteFile:"Supprimer fichier",deleteFilesCount:"Supprimer {{count}} fichiers",deleteFolderConfirm:"Supprimer le dossier et son contenu ?",deleteFileConfirm:"Supprimer ce fichier ?",deleteFilesConfirm:"Supprimer {{count}} fichiers définitivement ?",deleting:"Suppression...",noPermissionRenameFolder:"Pas d'autorisation renommage",noPermissionLinkFolder:"Pas d'autorisation lien",noPermissionDeleteFolder:"Pas d'autorisation suppression dossier",noPermissionPrint:"Pas d'autorisation impression",noPermissionAddToQueue:"Pas d'autorisation file",noPermissionDownload:"Pas d'autorisation téléchargement",noPermissionRenameFile:"Pas d'autorisation renommage fichier",noPermissionGenerateThumbnail:"Pas d'autorisation vignettes",noPermissionDeleteFile:"Pas d'autorisation suppression fichier",noPermissionCreateFolder:"Pas d'autorisation nouveau dossier",noPermissionUpload:"Pas d'autorisation téléversement",noPermissionMoveFiles:"Pas d'autorisation déplacement",noPermissionDeleteFiles:"Pas d'autorisation suppression groupée",linkExternal:"Lier externe",linkExternalFolder:"Lier un dossier externe",linkExternalFolderDescription:"Monter un répertoire hôte (NAS, USB, partage réseau) dans le gestionnaire de fichiers. Les fichiers ne sont pas copiés — ils sont lus directement depuis le chemin d'origine.",externalFolderNamePlaceholder:"ex. Impressions NAS",externalPath:"Chemin hôte",externalPathHelp:"Chemin absolu du répertoire sur l'hôte Docker. Doit être monté en bind dans le conteneur.",readOnly:"Lecture seule",readOnlyHelp:"empêche les téléversements et suppressions",showHiddenFiles:"Afficher les fichiers cachés (fichiers point)",externalFolder:"Dossier externe",scanFolder:"Scanner",toast:{folderCreated:"Dossier créé",folderDeleted:"Dossier supprimé",fileDeleted:"Fichier supprimé",filesDeleted:"{{count}} fichiers supprimés",filesMoved:"Fichiers déplacés",folderLinked:"Dossier lié",folderUnlinked:"Dossier délié",externalFolderLinked:"Dossier externe lié et scanné",folderScanned:"Scan terminé : {{added}} ajoutés, {{removed}} supprimés",addedToQueue:"{{count}} fichier(s) ajouté(s)",addedToQueuePartial:"{{added}} ajoutés, {{failed}} échecs",failedToAddToQueue:"Échec ajout file : {{error}}",fileRenamed:"Fichier renommé",folderRenamed:"Dossier renommé",thumbnailsGenerated:"{{count}} vignette(s) générée(s)",thumbnailsGeneratedPartial:"{{succeeded}} succès, {{failed}} échecs",noStlMissingThumbnails:"Aucun STL sans vignette",failedToGenerateThumbnails:"Échec vignettes : {{error}}",thumbnailGenerated:"Vignette générée",failedToGenerateThumbnail:"Échec vignette : {{error}}"}},projects:{title:"Projets",subtitle:"Suivez vos projets d'impression 3D",newProject:"Nouveau Projet",editProject:"Modifier Projet",deleteProject:"Supprimer Projet",projectName:"Nom du Projet",description:"Description",noProjects:"Aucun projet",noProjectsFiltered:"Aucun projet {{status}}",noProjectsFilteredHelp:"Les projets apparaîtront ici quand leur statut changera.",createFirst:"Créez votre premier projet pour organiser vos builds.",createFirstButton:"Créer votre premier projet",create:"Créer",files:"Fichiers",prints:"Impressions",plates:"plateaux",parts:"pièces",lastModified:"Modifié le",deleteConfirm:"Supprimer ce projet ? Les archives seront déliées mais conservées.",addFiles:"Ajouter fichiers",removeFile:"Retirer fichier",viewDetails:"Détails",namePlaceholder:"ex: Build Voron 2.4",descriptionPlaceholder:"Description optionnelle...",color:"Couleur",targetPlates:"Plateaux cibles",targetPlatesPlaceholder:"ex: 25",targetPlatesHelp:"Nombre total de jobs",targetParts:"Pièces cibles",targetPartsPlaceholder:"ex: 150",targetPartsHelp:"Nombre total d'objets",tagsLabel:"Tags (séparés par virgules)",tagsPlaceholder:"ex: voron, cadeau",dueDate:"Échéance",priority:"Priorité",priorityLow:"Basse",priorityNormal:"Normale",priorityHigh:"Haute",priorityUrgent:"Urgente",statusActive:"Actif",statusCompleted:"Terminé",statusArchived:"Archivé",done:"Fait",completed:"terminé",failed:"échoué",inQueue:"en file",noPrintsYet:"Aucune impression",printJobs:"Jobs (plateaux)",partsPrinted:"Pièces imprimées",failedParts:"Pièces échouées",import:"Importer",export:"Exporter",importProject:"Importer projet",exportAll:"Exporter tous les projets",loading:"Chargement des projets...",noEditPermission:"Pas d'autorisation de modification",noDeletePermission:"Pas d'autorisation de suppression",noCreatePermission:"Pas d'autorisation de création",noImportPermission:"Pas d'autorisation d'import",noExportPermission:"Pas d'autorisation d'export",toast:{created:"Projet créé",updated:"Projet mis à jour",deleted:"Projet supprimé",imported:"Projet importé",multipleImported:"{{count}} projets importés",importFailed:"Échec d'import",exported:"Projets exportés (métadonnées)"}},projectDetail:{notFound:"Projet non trouvé",backToProjects:"Retour aux Projets",export:"Exporter",exportProject:"Exporter projet",noExportPermission:"Pas d'autorisation export",noEditPermission:"Pas d'autorisation modification",partOf:"Fait partie de :",priorityLabel:"Priorité :",noPrints:"Aucune impression dans ce projet",status:{active:"Actif",completed:"Terminé",archived:"Archivé"},priority:{low:"Basse",normal:"Normale",high:"Haute",urgent:"Urgente"},dueDate:{overdue:"En retard",today:"Aujourd'hui",daysLeft:"{{count}} jours restants"},progress:{platesProgress:"Progression Plateaux",partsProgress:"Progression Pièces",printJobs:"jobs d'impression",parts:"pièces",percentComplete:"{{percent}}% terminé",remaining:"{{count}} restant(s)"},stats:{printJobs:"Jobs d'Impression",total:"total",failed:"{{count}} échecs",partsPrinted:"{{count}} pièces imprimées",printTime:"Temps d'Impression",filamentUsed:"Filament utilisé"},cost:{title:"Suivi des coûts",filamentCost:"Coût Filament",energy:"Énergie",totalCost:"Coût Total",total:"Total",includesBom:"BOM incluse",budget:"Budget",remaining:"Restant"},subProjects:{title:"Sous-projets ({{count}})"},notes:{title:"Notes",noEditPermission:"Pas d'autorisation modification",placeholder:"Ajouter des notes...",empty:"Aucune note. Cliquez sur modifier."},files:{title:"Fichiers",linkFolders:"Liez des dossiers depuis le gestionnaire",forQuickAccess:"pour un accès rapide.",fileCount:"{{count}} fichier(s)",empty:"Aucun dossier lié."},bom:{title:"BOM (Liste matériel)",acquired:"{{completed}}/{{total}} acquis",showAll:"Tout afficher",hideDone:"Masquer acquis",addPart:"Ajouter matériel",noAddPermission:"Pas d'autorisation ajout",partNamePlaceholder:"Nom (ex: Vis M3x8)",partName:"Nom de pièce",qty:"Qté",price:"Prix ({{currency}})",sourcingUrlPlaceholder:"Lien d'achat (optionnel)",remarksPlaceholder:"Remarques (optionnel)",deletePart:"Supprimer pièce",deleteConfirm:'Supprimer "{{name}}" ?',noUpdatePermission:"Pas d'autorisation mise à jour",noEditPermission:"Pas d'autorisation modification",noDeletePermission:"Pas d'autorisation suppression",totalCost:"Coût total :",empty:"BOM vide. Ajoutez du matériel ou de l'électronique."},timeline:{title:"Historique d'activité",empty:"Aucune activité."},template:{saveAsTemplate:"Enregistrer comme modèle",noCreatePermission:"Pas d'autorisation modèle"},queue:{title:"File d'attente",viewAll:"Tout voir",printing:"{{count}} en cours",queued:"{{count}} en file"},prints:{title:"Impressions ({{count}})"},toast:{projectUpdated:"Projet mis à jour",partAdded:"Pièce ajoutée",partRemoved:"Pièce retirée",exportFailed:"Échec export",projectExported:"Projet exporté",templateCreated:"Modèle créé"}},system:{title:"Informations Système",version:"Version",uptime:"Temps de fonctionnement",cpuUsage:"Utilisation CPU",memoryUsage:"Utilisation RAM",diskUsage:"Utilisation Disque",networkInfo:"Infos Réseau",logs:"Journaux",debugMode:"Mode Débogage",enableDebug:"Activer débogage",disableDebug:"Désactiver débogage",downloadLogs:"Télécharger logs",clearLogs:"Effacer logs",dockerInfo:"Infos Docker",containerName:"Nom conteneur",imageName:"Nom image",platform:"Plateforme",architecture:"Architecture"},library:{title:"Bibliothèque Filament",addFilament:"Ajouter Filament",editFilament:"Modifier Filament",deleteFilament:"Supprimer Filament",vendor:"Vendeur",material:"Matériau",color:"Couleur",kFactor:"Facteur K",temperature:"Température",noFilaments:"Bibliothèque vide",deleteConfirm:"Supprimer ce filament ?",importFromPrinter:"Importer de l'imprimante",exportToFile:"Exporter vers fichier"},spoolman:{title:"Intégration Spoolman",enabled:"Spoolman Activé",url:"URL Spoolman",connected:"Connecté",disconnected:"Non Connecté",testConnection:"Tester connexion",sync:"Synchroniser",syncing:"Sync...",lastSync:"Dernière Sync",linkToSpoolman:"Lier à Spoolman",openInSpoolman:"Ouvrir Spoolman",unlinkSpool:"Délier bobine",unlinkConfirmTitle:"Dissocier la bobine?",unlinkConfirmMessage:"Cette opération déconnectera la bobine de Spoolman. Les données de la bobine dans Spoolman resteront inchangées.",selectSpool:"Choisir bobine",noUnlinkedSpools:"Pas de bobine libre",linkSuccess:"Lien réussi",linkFailed:"Échec lien",unlinkSuccess:"Bobine dissociée avec succès",unlinkFailed:"Échec de la dissociation de la bobine",spoolId:"ID Bobine",fillSourceLabel:"(Spoolman)",weight:"Poids",remaining:"Restant",disableWeightSync:"Désactiver Sync poids estimé AMS",disableWeightSyncDesc:"Ne pas utiliser les estimations AMS. Utile si vous préférez le suivi Spoolman.",reportPartialUsage:"Rapporter consommation partielle pour échecs",reportPartialUsageDesc:"Si l'impression échoue, rapporte le filament consommé selon les couches."},inventory:{title:"Inventaire de Bobines",addSpool:"Ajouter Bobine",editSpool:"Modifier Bobine",material:"Matériau",selectMaterial:"Choisir matériau...",subtype:"Sous-type",brand:"Marque",searchBrand:"Chercher marque...",useCustomBrand:'Utiliser "{{brand}}"',useCustomMaterial:"Utiliser un matériau personnalisé : {{material}}",colorName:"Nom de couleur",colorNamePlaceholder:"Jade White, Fire Red...",color:"Couleur",hexColor:"Code Hex",pickColor:"Choisir couleur perso",labelWeight:"Poids net",coreWeight:"Poids bobine vide",searchSpoolWeight:"Chercher poids bobine...",weightUsed:"Consommé",currentWeight:"Poids restant",measuredWeight:"Poids mesuré",spoolName:"Bobine",costPerKg:"Coût par kg",measuredWeightError:"Le poids mesuré doit être entre {{min}}g et {{max}}g.",slicerFilament:"Filament Slicer",slicerFilamentName:"Nom du Preset Slicer",slicerPreset:"Preset Slicer",searchPresets:"Chercher presets...",selectedPreset:"Sélectionné",noPresetsFound:"Aucun preset trouvé",tempOverrides:"Exceptions Température",note:"Note",notePlaceholder:"Notes additionnelles sur cette bobine...",archive:"Archiver",restore:"Restaurer",noSpools:"Aucune bobine. Ajoutez votre première bobine pour commencer.",noManualSpools:"Aucune bobine manuelle disponible. Ajoutez-en une d'abord.",kProfiles:"K-Profiles",addKProfile:"Ajouter K-Profile",assignSpool:"Assigner Bobine",unassignSpool:"Désassigner",assignSuccess:"Bobine assignée et slot AMS configuré",assignFailed:"Échec assignation",selectSpool:"Choisir une bobine pour ce slot",assigned:"Assigné",assigning:"Assignation...",searchSpools:"Chercher bobines...",showAllSpools:"Afficher toutes les bobines",allMaterials:"Tous Matériaux",filterByBrand:"Filtrer par marque...",showArchived:"Afficher archivées",quickAdd:"Ajout rapide (Stock)",quantity:"Quantité",stock:"Stock",configured:"Configuré",spoolsCreated:"{{count}} bobines créées",spoolCreated:"Bobine créée",spoolUpdated:"Bobine mise à jour",spoolDeleted:"Bobine supprimée",spoolArchived:"Bobine archivée",spoolRestored:"Bobine restaurée",deleteConfirm:"Supprimer définitivement cette bobine ?",archiveConfirm:"Voulez-vous vraiment archiver cette bobine ?",advancedSettings:"Paramètres Avancés",filamentInfoTab:"Infos Filament",paProfileTab:"Profil PA",filamentInfo:"Filament",additional:"Additionnel",loadingPresets:"Chargement des presets cloud...",cloudConnected:"Cloud connecté",cloudNotConnected:"Cloud déconnecté (valeurs par défaut)",recentColors:"Récentes",searchColors:"Chercher couleurs...",searchResults:"Résultats",allColors:"Toutes",commonColors:"Communes",showLess:"Moins",showAll:"Toutes",noColorsFound:"Aucune couleur correspondante",noResults:"Aucun résultat",selectMaterialFirst:"Veuillez choisir un matériau dans l'onglet Infos Filament.",noPrintersConfigured:"Ajoutez une imprimante pour utiliser les profils PA.",matchingFilter:"Correspondant",anyBrand:"Toute marque",anyVariant:"Toute variante",autoSelect:"Auto-sélection",matches:"correspondances",match:"correspondance",noMatches:"Aucune correspondance",connected:"Connecté",offline:"Hors ligne",printerOffline:"Imprimante hors ligne. Connectez-vous pour voir les profils.",noKProfilesMatch:"Aucun profil K ne correspond au filament.",leftNozzle:"Buse Gauche",rightNozzle:"Buse Droite",profilesSelected:"profil(s) de calibration sélectionné(s)",totalInventory:"Total Inventaire",totalConsumed:"Total Consommé",byMaterial:"Par Matériau",inPrinter:"Dans Imprimante",lowStock:"Stock Bas",sinceTracking:"Depuis le début du suivi",loadedInAms:"Chargé dans AMS/Ext",remaining:"Restant",weightCheck:"Vérification poids",lastWeighed:"Dernière pesée",neverWeighed:"Jamais pesé",search:"Chercher bobines...",showing:"Affichage",to:"à",of:"sur",show:"Voir",spools:"bobines",spool:"bobine",page:"Page",noSpoolsMatch:"Aucun résultat trouvé",noSpoolsMatchDesc:"Ajustez votre recherche ou vos filtres.",active:"Actif",archived:"Archivé",all:"Tous",used:"Occasion",new:"Neuf",clearFilters:"Effacer filtres",table:"Tableau",cards:"Cartes",net:"Net",groupSimilar:"Grouper",groupedSpools:"{{count}} bobines identiques",groupedRows:"lignes",columns:"Colonnes",configureColumns:"Configurer Colonnes",configureColumnsDesc:"Glissez pour ordonner ou utilisez les flèches. Cliquez sur l'œil pour masquer.",visible:"visible",reset:"Reset",cancel:"Annuler",applyChanges:"Appliquer",moveUp:"Monter",moveDown:"Descendre",hideColumn:"Masquer",showColumn:"Afficher",linkToSpool:"Lier à une Bobine",tagLinked:"Tag lié à la bobine",tagLinkFailed:"Échec lien tag",tagAlreadyLinked:"Tag déjà lié à une autre bobine",unknownTag:"Tag RFID inconnu détecté",usageHistory:"Historique de Consommation",noUsageHistory:"Aucune consommation enregistrée",printName:"Nom Impression",weightConsumed:"Poids consommé",clearHistory:"Effacer",historyCleared:"Historique effacé",fillSourceLabel:"(Inv)",lowStockThresholdError:"Le seuil doit être compris entre 0.1 et 99.9",assignMismatchTitle:"Incompatibilité de matériau",assignMismatchMessage:'Le matériau de la bobine sélectionnée "{{spoolMaterial}}" ne correspond pas au matériau du plateau "{{trayMaterial}}" pour {{location}}. Assigner quand même ?',assignMismatchConfirm:"Assigner quand même",assignPartialMismatchMessage:'Le matériau de la bobine "{{spoolMaterial}}" est similaire, mais ne correspond pas exactement à "{{trayMaterial}}" dans {{location}}. Voulez-vous continuer ?',assignProfileMismatchMessage:'Le profil de la bobine "{{spoolProfile}}" ne correspond pas au profil du plateau "{{trayProfile}}" dans {{location}}. Voulez-vous continuer ?'},timelapse:{title:"Timelapse",create:"Créer Timelapse",download:"Télécharger",delete:"Supprimer",preview:"Aperçu",frameRate:"Images/sec",quality:"Qualité",processing:"Traitement...",noTimelapses:"Aucun timelapse"},ams:{title:"AMS",slot:"Slot",empty:"Vide",emptySlot:"Slot vide",unknown:"Inconnu",humidity:"Humidité",temperature:"Température",filamentType:"Type filament",filamentColor:"Couleur",remaining:"Restant",history:"Historique AMS",noHistory:"Aucun historique",configureSlot:"Configurer Slot",externalSpool:"Bobine externe",profile:"Profil",kFactor:"Facteur K",fill:"Remplir",configure:"Configurer",used:"utilisé",remainingUnit:"restant"},printModal:{title:"Lancer l'impression",selectPrinter:"Choisir l'imprimante",selectPlate:"Choisir le plateau",filamentMapping:"Mapping Filament",totalCost:"Coût total :",slotRemainingShort:" - {{grams}}g rest.",printSettings:"Réglages d'impression",bedLeveling:"Nivellement plateau",flowCalibration:"Calibration débit",vibrationCalibration:"Vibration (Input Shaper)",layerInspection:"Inspection 1ère couche",timelapse:"Timelapse",startPrint:"Démarrer",addToQueue:"Ajouter à la file",cancel:"Annuler",noPrintersAvailable:"Aucune imprimante disponible",printerBusy:"L'imprimante est occupée",printerOffline:"L'imprimante est hors ligne",sameTypeDifferentColor:"Même type, couleur différente",filamentTypeNotLoaded:"Type de filament non chargé",openCalendar:"Ouvrir calendrier",leftNozzle:"G",rightNozzle:"D",leftNozzleTooltip:"Buse gauche",rightNozzleTooltip:"Buse droite",filamentOverride:"Remplacement de filament",filamentOverrideHint:"Remplacez optionnellement les filaments pour l'affectation par modèle. Le planificateur utilisera vos filaments sélectionnés au lieu des valeurs 3MF d'origine.",originalFilament:"Original",overrideWith:"Remplacer par",resetToOriginal:"Revenir à l'original",insufficientFilamentTitle:"Filament insuffisant",insufficientFilamentMessage:"Certaines bobines assignées ont moins de filament restant que nécessaire pour cette impression :",insufficientFilamentLine:"{{printer}} - {{slot}} : nécessite {{required}}g, restant {{remaining}}g",printAnyway:"Imprimer quand même",forceColorMatch:"Forcer correspondance des couleurs",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Échelonner sur {{count}} imprimantes",gcodeInjection:"Injecter le G-code auto-impression"},backup:{title:"Sauvegarde & Restauration",createBackup:"Créer Sauvegarde",restoreBackup:"Restaurer Sauvegarde",restoreDescription:"Remplace les données par un fichier de sauvegarde",downloadBackup:"Télécharger Sauvegarde",uploadBackup:"Téléverser Sauvegarde",lastBackup:"Dernière sauvegarde",autoBackup:"Sauvegarde auto",backupNow:"Sauvegarder maintenant",restoreWarning:"Attention : Écrase TOUTES les données actuelles.",includeArchives:"Inclure Archives",includeSettings:"Inclure Paramètres",includeProfiles:"Inclure Profils",backupSuccess:"Sauvegarde réussie",restoreSuccess:"Restauration réussie",backupFailed:"Échec sauvegarde",restoreFailed:"Échec restauration",restoreNote:"L'imprimante virtuelle sera arrêtée pendant la restauration",githubBackup:"Sauvegarde GitHub",enabled:"Activé",cloudLoginRequired:"Connexion Bambu Cloud requise. Connectez-vous sous Profils → Profils Cloud pour activer la sauvegarde GitHub.",cloudLoginRequiredShort:"Connexion Cloud requise",githubDescription:"Synchronisez automatiquement vos profils vers un dépôt GitHub privé pour la sauvegarde et l'historique des versions.",repositoryUrl:"URL du dépôt",personalAccessToken:"Jeton d'accès personnel",tokenSaved:"(enregistré)",enterNewToken:"Entrez un nouveau jeton pour mettre à jour",tokenHint:"Jeton à granularité fine avec permission de lecture/écriture du contenu",branch:"Branche",manualOnly:"Manuel uniquement",hourly:"Toutes les heures",daily:"Quotidien",weekly:"Hebdomadaire",includeInBackup:"Inclure dans la sauvegarde",kProfiles:"K-Profils",kProfilesDescription:"Calibration de l'avance de pression des imprimantes connectées",noPrintersConnected:"Aucune imprimante connectée",printersConnected:"{{connected}}/{{total}} connectées",cloudProfiles:"Profils Cloud",cloudProfilesDescription:"Préréglages de filament, imprimante et processus depuis Bambu Cloud",appSettings:"Paramètres de l'application",appSettingsDescription:"Configuration Bambuddy (base de données complète)",spoolInventory:"Inventaire des bobines",spoolInventoryDescription:"Bobines de filament, historique d'utilisation et suivi des coûts",printArchives:"Archives d'impression",printArchivesDescription:"Métadonnées de l'historique d'impression (pas de fichiers gcode/3MF)",lastBackupAt:"Dernière sauvegarde :",noBackupsYet:"Aucune sauvegarde pour l'instant",next:"Prochaine :",startingBackup:"Démarrage de la sauvegarde...",test:"Tester",enableBackup:"Activer la sauvegarde",testConnection:"Tester la connexion",enterRepoUrl:"Entrez l'URL du dépôt",enterRepoAndToken:"Entrez l'URL du dépôt et le jeton d'accès",repoRequired:"L'URL du dépôt est requise",tokenRequired:"Le jeton d'accès est requis",githubBackupEnabled:"Sauvegarde GitHub activée",tokenUpdated:"Jeton mis à jour",settingsSaved:"Paramètres enregistrés",failedToSave:"Échec de l'enregistrement : {{message}}",backupCompleteFiles:"Sauvegarde terminée - {{count}} fichiers mis à jour",backupSkippedNoChanges:"Sauvegarde ignorée - aucun changement",backupFailed2:"Échec de la sauvegarde : {{message}}",clearedLogs:"{{count}} journaux supprimés",failedToClearLogs:"Échec de la suppression des journaux : {{message}}",history:"Historique",clear:"Effacer",date:"Date",status:"Statut",commit:"Commit",localBackup:"Sauvegarde locale",localBackupDescription:"Créez une sauvegarde complète de vos données Bambuddy incluant la base de données, les archives, les téléchargements et tous les fichiers.",downloadBackupLabel:"Télécharger la sauvegarde",completeBackupZip:"Sauvegarde complète : base de données + tous les fichiers (ZIP)",download:"Télécharger",preparingBackup:"Préparation de la sauvegarde...",creatingArchive:"Création de l'archive de sauvegarde... Cela peut prendre un moment pour les archives volumineuses.",downloadingFile:"Téléchargement du fichier de sauvegarde...",backupDownloaded:"Sauvegarde téléchargée avec succès",failedToCreateBackup:"Échec de la création de la sauvegarde : {{message}}",restore:"Restaurer",restoreReplacesAll:"La restauration remplace toutes les données.",restoreReplacesAllDetail:"Votre base de données et vos fichiers actuels seront complètement remplacés. Un redémarrage est nécessaire après la restauration.",restoreConfirmTitle:"Restaurer la sauvegarde",restoreConfirmMessage:`Êtes-vous sûr de vouloir restaurer depuis "{{filename}}" ? Cela remplacera complètement votre base de données et tous vos fichiers. L'application devra être redémarrée après la restauration.`,restoreConfirmButton:"Restaurer la sauvegarde",uploadingFile:"Téléchargement du fichier de sauvegarde...",backupRestoredRestart:"Sauvegarde restaurée. Veuillez redémarrer Bambuddy.",failedToRestore:"Échec de la restauration. Veuillez vérifier le format du fichier.",reloadNow:"Recharger maintenant",creatingBackup:"Création de la sauvegarde",restoringBackup:"Restauration de la sauvegarde",preparing:"Préparation...",processing:"Traitement...",doNotClosePage:"Veuillez ne pas fermer cette page ni naviguer ailleurs. Cette opération peut prendre plusieurs minutes pour les sauvegardes volumineuses.",restoring:"Restauration...",restoreComplete:"Restauration terminée",restoreFailed2:"Échec de la restauration",importSettings:"Importer les paramètres depuis un fichier de sauvegarde",pleaseWaitRestoring:"Veuillez patienter pendant la restauration de vos données",selectBackupFile:"Cliquez pour sélectionner un fichier de sauvegarde (.json ou .zip)",duplicateHandling:"Comment fonctionne la gestion des doublons :",matchPrinters:"Imprimantes",matchPrintersBy:"correspondance par numéro de série",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"correspondance par adresse IP",matchNotificationProviders:"Fournisseurs de notifications",matchNotificationProvidersBy:"correspondance par nom",matchFilaments:"Filaments",matchFilamentsBy:"correspondance par nom + type + marque",matchArchives:"Archives",matchArchivesBy:"correspondance par hash de contenu (toujours ignoré)",matchPendingUploads:"Téléchargements en attente",matchPendingUploadsBy:"correspondance par nom de fichier",matchSettingsTemplates:"Paramètres et modèles",matchSettingsTemplatesBy:"toujours écrasés",replaceExisting:"Remplacer les données existantes",keepExisting:"Conserver les données existantes",overwriteDescription:"Écraser les éléments qui existent déjà avec les données de sauvegarde",keepDescription:"Restaurer uniquement les éléments qui n'existent pas encore",overwriteCaution:"Attention :",overwriteWarning:"L'écrasement remplacera vos configurations actuelles par les données de la sauvegarde. Les codes d'accès des imprimantes ne sont jamais écrasés pour des raisons de sécurité.",cancel:"Annuler",processingBackup:"Traitement du fichier de sauvegarde...",itemsRestored:"Éléments restaurés",itemsSkipped:"Éléments ignorés",restored:"Restaurés",skippedAlreadyExist:"Ignorés (existent déjà)",filesCategory:"Fichiers (3MF, miniatures, etc.)",andMore:"...et {{count}} de plus",newApiKeysGenerated:"Nouvelles clés API générées",keysShownOnce:"Ces clés ne sont affichées qu'une seule fois. Copiez-les maintenant !",copy:"Copier",noDataFound:"Aucune donnée à restaurer n'a été trouvée dans le fichier de sauvegarde.",close:"Fermer",categories:{settings:"Paramètres",notification_providers:"Fournisseurs de notifications",notification_templates:"Modèles de notifications",smart_plugs:"Smart Plugs",printers:"Imprimantes",filaments:"Filaments",maintenance_types:"Types de maintenance",archives:"Archives",projects:"Projets",pending_uploads:"Téléchargements en attente",external_links:"Liens externes",api_keys:"Clés API"}},tags:{title:"Tags",addTag:"Ajouter Tag",editTag:"Modifier Tag",deleteTag:"Supprimer Tag",tagName:"Nom du Tag",tagColor:"Couleur du Tag",noTags:"Aucun tag",deleteConfirm:"Supprimer ce tag ?",manageTags:"Gérer les Tags"},uploadModal:{title:"Téléverser des fichiers 3MF",dragDrop:"Glissez les fichiers .3mf ici",or:"ou",browseFiles:"Parcourir",extractionInfo:"Le modèle d'imprimante est extrait des métadonnées 3MF.",uploaded:"téléversé",failed:"échoué",uploading:"En cours...",upload:"Téléverser",uploadFailed:"Échec du téléversement"},editArchive:{title:"Modifier l'archive",name:"Nom",namePlaceholder:"Nom de l'impression",printer:"Imprimante",noPrinter:"Aucune imprimante",project:"Projet",noProject:"Aucun projet",itemsPrinted:"Nombre de pièces",itemsPrintedHelp:"Nombre d'objets produits",notes:"Notes",notesPlaceholder:"Notes sur l'impression...",externalLink:"Lien externe",externalLinkPlaceholder:"https://...",externalLinkHelp:"Lien vers Printables, Thingiverse, etc.",tags:"Tags",tagsPlaceholder:"Ajouter des tags...",addMoreTags:"Plus de tags...",matchingTags:'Correspondant à "{{query}}"',existingTags:"Tags existants",clickToAdd:"(cliquer pour ajouter)",status:"Statut",failureReason:"Raison de l'échec",selectReason:"Choisir raison...",photos:"Photos du résultat",photosHelp:"Cliquez sur + pour ajouter des photos",printResult:"Résultat d'impression",saving:"Enregistrement...",failureReasons:{adhesionFailure:"Défaut d'adhésion",spaghettiDetached:"Spaghetti / Détaché",layerShift:"Décalage de couche",cloggedNozzle:"Buse bouchée",filamentRunout:"Filament fini",warping:"Warping (Déformation)",stringing:"Stringing (Cheveux d'ange)",underExtrusion:"Sous-extrusion",powerFailure:"Coupure courant",userCancelled:"Annulé par l'utilisateur",other:"Autre"},statuses:{completed:"Réussie",failed:"Échouée",aborted:"Annulée",printing:"Impression"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Aucune imprimante configurée",addPrinterInSettings:"Ajoutez une imprimante pour gérer les K-profiles",noActivePrinters:"Aucune imprimante active",enablePrinterConnection:"Activez la connexion pour voir les K-profiles",loadingProfiles:"Chargement des K-Profiles...",printerOffline:"Imprimante hors ligne",printerOfflineDesc:"L'imprimante doit être allumée.",noMatchingProfiles:"Aucun profil correspondant",noMatchingProfilesDesc:"Ajustez votre recherche",noKProfiles:"Aucun K-Profile",noKProfilesDesc:"Aucun profil trouvé pour une buse de {{diameter}}mm",createFirstProfile:"Créer le premier profil",printer:"Imprimante",nozzle:"Buse",refresh:"Rafraîchir",addProfile:"Ajouter Profil",export:"Exporter",import:"Importer",select:"Choisir",selectAll:"Tout sélectionner",delete:"Supprimer",searchPlaceholder:"Nom ou filament...",allExtruders:"Tous les extrudeurs",leftOnly:"Gauche uniquement",rightOnly:"Droite uniquement",allFlow:"Tout débit",hfOnly:"HF uniquement",sOnly:"S uniquement",sortName:"Tri : Nom",sortKValue:"Tri : Valeur K",sortFilament:"Tri : Filament",leftExtruder:"Extrudeur gauche",rightExtruder:"Extrudeur droit",modal:{addTitle:"Ajouter K-Profile",editTitle:"Modifier K-Profile",profileName:"Nom du profil",profileNamePlaceholder:"ex: Mon profil PLA",kValue:"Valeur K",kValuePlaceholder:"0.020",kValueHelp:"Plage type : 0.01-0.06 (PLA), 0.02-0.10 (PETG)",filament:"Filament",selectFilament:"Choisir filament...",noFilamentsHelp:"Créez d'abord un profil dans Bambu Studio.",flowType:"Type de débit",highFlow:"Haut Débit (HF)",standard:"Standard",nozzleSize:"Taille buse",extruder:"Extrudeur",extruders:"Extrudeurs",left:"Gauche",right:"Droite",notes:"Notes (locales)",notesPlaceholder:"Notes sur ce profil...",notesHelp:"Enregistré dans Bambuddy, pas sur l'imprimante",syncing:"Sync avec l'imprimante...",savingExtruder:"Sauvegarde extrudeur {{current}}/{{total}}...",pleaseWait:"Patientez..."},deleteConfirm:{title:"Supprimer profil",cannotUndo:"Action irréversible",message:`Supprimer "{{name}}" de l'imprimante ?`},bulkDelete:{title:"Supprimer les profils",cannotUndo:"Action irréversible",message:"Supprimer les {{count}} profils de l'imprimante ?"},toast:{profileSaved:"Profil K enregistré",profilesSaved:"Profil K enregistré sur {{count}} extrudeur(s)",selectAtLeastOneExtruder:"Sélectionnez un extrudeur",profileDeleted:"Profil K supprimé",profilesDeleted:"{{count}} profils supprimés",exportedProfiles:"{{count}} profils exportés",importedProfiles:"{{count}} sur {{total}} profils importés",noProfilesToExport:"Rien à exporter",invalidFileFormat:"Format invalide",failedToParseImport:"Échec analyse fichier",failedToSaveBatch:"Échec enregistrement groupé",noteSaved:"Note enregistrée",failedToSaveNote:"Échec note"},permission:{noRead:"Pas d'autorisation lecture",noCreate:"Pas d'autorisation création",noUpdate:"Pas d'autorisation mise à jour",noDelete:"Pas d'autorisation suppression",noExport:"Pas d'autorisation export",noImport:"Pas d'autorisation import"}},virtualPrinter:{title:"Imprimante Virtuelle",running:"En cours",stopped:"Arrêtée",description:{default:"Active une imprimante qui apparaît dans Bambu Studio. Les fichiers envoyés sont archivés sans impression.",proxy:"Active un proxy qui relaie le trafic vers une imprimante réelle, permettant l'impression à distance."},enable:{title:"Activer l'imprimante virtuelle",visibleInSlicer:'Visible comme "Bambuddy" dans le Slicer',proxyingTo:"Proxy vers {{name}}",notActive:"Inactive"},model:{title:"Modèle d'imprimante",description:"Choisissez le modèle à émuler.",restartWarning:"Changer le modèle redémarrera le service"},accessCode:{title:"Code d'accès",isSet:"Code défini",notSet:"Code requis pour activer",placeholder:"Code 8 char",placeholderChange:"Entrez nouveau code",hint:"Exactement 8 caractères. Sert à l'auth du Slicer.",charCount:"({{count}}/8)"},targetPrinter:{title:"Imprimante cible",configured:"Cible configurée",notConfigured:"Imprimante requise pour mode Proxy",placeholder:"Choisir imprimante...",hint:"L'imprimante doit être en mode LAN.",noPrinters:"Ajoutez une imprimante réelle d'abord."},remoteInterface:{title:"Exception Interface Réseau",configured:"Override actif",optional:"Optionnel - si IP auto est fausse (VPN, Docker, multi-NIC).",placeholder:"Auto (défaut)...",hint:"Force l'IP annoncée via SSDP."},mode:{title:"Mode",archive:"Archiver",archiveDesc:"Archive immédiatement",review:"Revue",reviewDesc:"Attendre revue avant archive",queue:"File",queueDesc:"Archiver et ajouter à la file",proxy:"Proxy",proxyDesc:"Relais vers imprimante réelle"},autoDispatch:{title:"Lancement automatique",description:"Lancer automatiquement les impressions ajoutées à la file. Désactivé, les impressions attendent un lancement manuel."},setupRequired:{title:"Configuration requise",description:"Nécessite des réglages système (ports, pare-feu).",readGuide:"Lire le guide de configuration"},howItWorks:{title:"Fonctionnement",step1:"Sur le même LAN, les imprimantes virtuelles apparaissent automatiquement dans votre slicer (Bambu Studio / OrcaSlicer). Depuis d'autres réseaux, ajoutez-les manuellement par adresse IP et code d'accès.",step2:`En mode Archive, Revue et File d'attente, utilisez le bouton "Envoyer" dans votre slicer pour envoyer des fichiers 3MF à Bambuddy. Le slicer affichera "Impression réussie" — le fichier est stocké, pas imprimé.`,step3:"En mode Proxy, l'imprimante virtuelle relaie tout le trafic vers une vraie imprimante — les impressions démarrent immédiatement comme en connexion directe."},status:{title:"Détails du statut",printerName:"Nom",model:"Modèle",serialNumber:"Série",mode:"Mode",pendingFiles:"Fichiers en attente",targetPrinter:"Cible",ftpPort:"Port FTP",mqttPort:"Port MQTT",ftpConnections:"Connexions FTP",mqttConnections:"Connexions MQTT"},toast:{updated:"Réglages virtuels mis à jour",failedToUpdate:"Échec mise à jour",accessCodeRequired:"Code d'accès requis",targetPrinterRequired:"Imprimante cible requise",bindIpRequired:"Veuillez d'abord définir une adresse IP",accessCodeEmpty:"Le code ne peut pas être vide",accessCodeLength:"Le code doit faire 8 caractères",created:"Imprimante virtuelle créée",failedToCreate:"Échec de la création de l'imprimante virtuelle",deleted:"Imprimante virtuelle supprimée",failedToDelete:"Échec de la suppression de l'imprimante virtuelle"},list:{title:"Imprimantes virtuelles",add:"Ajouter",addFirst:"Ajouter une imprimante virtuelle",empty:"Aucune imprimante virtuelle configurée. Ajoutez-en une pour commencer."},bindIp:{title:"Interface réseau",placeholder:"Sélectionner interface...",hint:"Interface réseau sur laquelle cette imprimante virtuelle écoute. Doit être unique par imprimante."},proxy:{accessCodeHint:"En mode proxy, utilisez le code d'accès de l'imprimante cible dans le slicer. La connexion est transmise de manière transparente à l'imprimante réelle."},addDialog:{title:"Ajouter une imprimante virtuelle",name:"Nom",hint:"Vous pourrez configurer le code d'accès, l'imprimante cible et d'autres paramètres après la création.",create:"Créer"},deleteConfirm:{title:"Supprimer l'imprimante virtuelle",message:'Êtes-vous sûr de vouloir supprimer "{{name}}" ? Cela arrêtera tous les services de cette imprimante.'}},modelViewer:{openInSlicer:"Ouvrir dans le Slicer",tabs:{model:"Modèle 3D",gcode:"Aperçu G-code"},notAvailable:"indisponible",notSliced:"pas découpé",plates:"Plateaux",allPlates:"Tous les plateaux",plateNumber:"Plateau {{number}}",plateCount:"{{count}} plateau",plateCount_other:"{{count}} plateaux",objectCount:"{{count}} objet",objectCount_other:"{{count}} objets",filamentCount:"{{count}} filament",filamentCount_other:"{{count}} filaments",eta:"Fin {{minutes}} min",noPreview:"Aucun aperçu pour ce fichier",pagination:{pageOf:"Page {{current}} sur {{total}}",prev:"Préc",next:"Suiv"},errors:{failedToLoad:"Échec chargement fichier",noMeshes:"Aucun maillage trouvé dans le 3MF",unsupportedFormat:"Format non supporté"}},maintenanceDescriptions:{lubricateCarbonRods:"Appliquer du lubrifiant sur les tiges carbone pour un mouvement fluide",lubricateRails:"Appliquer du lubrifiant sur les rails linéaires",cleanNozzle:"Nettoyer buse et hotend anti-bouchage",checkBelts:"Tension des courroies pour la précision",cleanBuildPlate:"Nettoyage plateau pour l'adhésion",checkExtruder:"Usure des engrenages de l'extrudeur",checkCooling:"Bon fonctionnement des ventilateurs",generalInspection:"Inspection générale de la machine",cleanCarbonRods:"Nettoyer les tiges carbone (friction)",lubricateSteelRods:"Appliquer du lubrifiant sur les tiges en acier pour un mouvement fluide",cleanSteelRods:"Nettoyer les tiges en acier (friction)",cleanLinearRails:"Essuyer les rails linéaires (poussière/débris)",checkPtfeTube:"Usure ou dommage du tube PTFE",replaceHepaFilter:"Filtre HEPA pour la qualité de l'air",replaceCarbonFilter:"Filtre charbon actif (odeurs)",lubricateLeftNozzleRail:"Lubrifier le rail de buse gauche (Série H2)"},smartPlugs:{offline:"Hors ligne",admin:"Admin",openPlugAdminPage:"Page admin de la prise",deleteSmartPlug:"Supprimer la prise",turnOnSmartPlug:"Allumer la prise",turnOffSmartPlug:"Éteindre la prise",turnOn:"Allumer",turnOff:"Éteindre",addSmartPlug:{scanningNetwork:"Scan réseau...",chooseEntity:"Choisir une entité...",connectionFailed:"Échec connexion",searchEntities:"Chercher entités...",searchPowerSensors:"Capteurs puissance...",searchEnergySensors:"Capteurs énergie...",placeholders:{plugName:"Prise Salon",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Identique au topic puissance, ou différent"}},linkedTo:"Lié à :",monitorOnly:"Surveillance uniquement",alerts:"Alertes",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Puissance",kwhToday:"kWh Aujourd'hui",settings:"Paramètres",automationSettings:"Paramètres d'automatisation",showInSwitchbar:"Afficher dans la barre de commutateurs",quickAccessSidebar:"Accès rapide depuis la barre latérale",enabled:"Activé",enableAutomation:"Activer l'automatisation pour cette prise",autoOn:"Auto On",autoOnDescription:"Allumer au démarrage de l'impression",autoOff:"Auto Off",autoOffDescription:"Éteindre à la fin de l'impression (unique)",autoOffPersistent:"Garder activé",autoOffPersistentDescription:"Rester activé entre les impressions au lieu d'une seule fois",turnOffDelayMode:"Mode de délai d'extinction",time:"Temps",temp:"Temp",delayMinutes:"Délai (minutes)",tempThreshold:"Seuil de température (°C)",tempThresholdDescription:"S'éteint lorsque la buse refroidit en dessous de cette température",edit:"Modifier",deleteConfirm:'Êtes-vous sûr de vouloir supprimer "{{name}}" ? Cette action est irréversible.',turnOnConfirm:'Êtes-vous sûr de vouloir allumer "{{name}}" ?',turnOffConfirm:`Êtes-vous sûr de vouloir éteindre "{{name}}" ? Cela coupera l'alimentation de l'appareil connecté.`,failedToTurn:'Impossible de {{action}} "{{name}}"',unknown:"Inconnu",addTitle:"Ajouter une prise connectée",editTitle:"Modifier la prise connectée",stopScanning:"Arrêter le scan",discoverTasmota:"Découvrir les appareils Tasmota",foundDevices:"{{count}} appareil(s) trouvé(s) - cliquez pour sélectionner :",noDevicesFound:"Aucun appareil Tasmota trouvé sur votre réseau",haNotConfigured:"Home Assistant n'est pas configuré. Configurez-le dans",haSettingsPath:"Paramètres → Réseau → Home Assistant",selectEntity:"Sélectionner l'entité *",ipAddress:"Adresse IP *",nameLabel:"Nom *",username:"Nom d'utilisateur",password:"Mot de passe",authHint:"Laissez vide si votre appareil Tasmota ne nécessite pas d'authentification",linkToPrinter:"Lier à l'imprimante",noPrinter:"Pas d'imprimante (contrôle manuel uniquement)",linkingDescription:"La liaison permet l'allumage/extinction automatique au début/fin de l'impression",powerAlerts:"Alertes de puissance",alertAbove:"Alerte si au-dessus (W)",alertBelow:"Alerte si en dessous (W)",alertDescription:"Recevoir une notification lorsque la consommation dépasse ces seuils. Laisser vide pour désactiver cette direction.",dailySchedule:"Planification quotidienne",turnOnAt:"Allumer à",turnOffAt:"Éteindre à",scheduleDescription:"Allumer/éteindre automatiquement la prise à ces heures chaque jour. Laisser vide pour ignorer cette action.",showOnPrinterCard:"Afficher sur la carte imprimante",displayOnPrinterCard:"Afficher le bouton sur la carte imprimante",connectedResult:"Connecté !",deviceLabel:"Appareil : {{name}} - ",stateLabel:"État : {{state}}",test:"Tester",delete:"Supprimer",save:"Enregistrer",add:"Ajouter",cancel:"Annuler",failedToStartScan:"Impossible de démarrer le scan",nameRequired:"Le nom est requis",entityRequired:"L'entité est requise pour les prises Home Assistant",mqttTopicRequired:"Au moins un topic MQTT doit être configuré pour la puissance, l'énergie ou la surveillance d'état",loadingEntities:"Chargement des entités...",loading:"Chargement...",failedToLoadEntities:"Échec du chargement des entités : {{error}}",noEntitiesMatching:'Aucune entité trouvée correspondant à "{{search}}"',noEntitiesAvailable:"Aucune entité disponible",searchingEntities:"Recherche de toutes les entités ({{count}} trouvées)",showingEntities:"Affichage switch, light, input_boolean ({{count}} disponibles)",energyMonitoringOptional:"Surveillance énergétique (Optionnel)",energyMonitoringHint:"Recherchez et sélectionnez les capteurs fournissant des données de puissance/énergie.",powerSensorW:"Capteur de puissance (W)",energyTodayKwh:"Énergie aujourd'hui (kWh)",totalEnergyKwh:"Énergie totale (kWh)",noMatchingSensors:"Aucun capteur correspondant",none:"Aucun",mqttNotConfigured:"Broker MQTT non configuré. Définissez l'adresse du broker dans",mqttSettingsPath:"Paramètres → Réseau → Publication MQTT",mqttNotConfiguredSuffix:"(vous n'avez pas besoin d'activer la publication, remplissez simplement les détails du broker).",mqttMonitorOnlyDescription:"Les prises MQTT reçoivent les données de puissance/énergie via un abonnement MQTT. Le contrôle on/off n'est pas disponible - utilisez votre broker MQTT ou système domotique.",powerMonitoring:"Surveillance de puissance",energyMonitoring:"Surveillance énergétique",stateMonitoring:"Surveillance d'état",optional:"optionnel",topic:"Topic",jsonPath:"Chemin JSON",multiplier:"Multiplicateur",onValue:"Valeur ON",mqttPowerHint:`Le chemin JSON extrait la valeur du payload JSON (ex: "power_l1"). Laisser vide si le topic publie des valeurs numériques brutes.
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL de puissance",restPowerPath:"Power JSON Path",restPowerMultiplier:"Multiplicateur de puissance",restEnergyUrl:"URL d'énergie",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Multiplicateur d'énergie",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL séparée pour les données de puissance (utilise l'URL de statut si vide)",restEnergyUrlHint:"URL séparée pour les données d'énergie (utilise l'URL de statut si vide)",restEnergyHint:"Chaque valeur peut utiliser sa propre URL ou se rabattre sur l'URL de statut. Utilisez les multiplicateurs pour la conversion d'unités (ex : 0.001 pour convertir Wh en kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Aucun commutateur dans la barre",enableSwitchbarHint:'Activez "Afficher dans la barre de commutateurs" dans Paramètres > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notifications par e-mail SMTP",telegram:"Notifications via un bot Telegram",discord:"Envoyer vers un canal Discord via webhook",ntfy:"Notifications push gratuites, auto-hébergeables",pushover:"Notifications push simples et fiables",callmebot:"Notifications WhatsApp gratuites via CallMeBot",webhook:"POST HTTP générique vers n'importe quelle URL",homeassistant:"Notifications persistantes dans le tableau de bord Home Assistant"},lastSuccess:"Dernier : {{date}}",error:"Erreur",printer:"Imprimante :",allPrinters:"Toutes les imprimantes",sendTestNotification:"Envoyer une notification de test",eventSettings:"Paramètres des événements",enabled:"Activé",sendFromProvider:"Envoyer des notifications depuis ce fournisseur",printEvents:"Événements d'impression",printerStatus:"État de l'imprimante",amsAlarms:"Alarmes AMS",amsHtAlarms:"Alarmes AMS-HT",printQueue:"File d'attente d'impression",start:"Début",plateCheck:"Vérification du plateau",complete:"Terminé",failed:"Échoué",stopped:"Arrêté",progress:"Progression",offline:"Hors ligne",lowFilament:"Filament bas",maintenance:"Maintenance",amsHumidity:"Humidité AMS",amsTemp:"Temp. AMS",amsHtHumidity:"Humidité AMS-HT",amsHtTemp:"Temp. AMS-HT",bedCooled:"Plateau refroidi",firstLayer:"Première couche",quiet:"Silencieux",digest:"Résumé {{time}}",printStarted:"Impression démarrée",plateNotEmpty:"Plateau non vide",plateNotEmptyDescription:"Objets détectés avant l'impression",printCompleted:"Impression terminée",bedCooledLabel:"Plateau refroidi",bedCooledDescription:"Plateau refroidi sous le seuil après l'impression",firstLayerCompleteLabel:"Première couche terminée",firstLayerCompleteDescription:"Notification avec photo après la première couche",missingSpoolAssignmentLabel:"Affectation de bobine manquante",missingSpoolAssignmentDescription:"Notifier quand une impression démarre et que des bacs requis n'ont pas de bobine assignée",printFailed:"Impression échouée",printStopped:"Impression arrêtée",progressMilestones:"Jalons de progression",progressMilestonesDescription:"Notifier à 25 %, 50 %, 75 %",printerOffline:"Imprimante hors ligne",printerError:"Erreur de l'imprimante",lowFilamentLabel:"Filament bas",maintenanceDue:"Maintenance requise",maintenanceDueDescription:"Notifier lorsqu'une maintenance est nécessaire",amsHumidityHigh:"Humidité AMS élevée",amsHumidityHighDescription:"L'humidité de l'AMS standard dépasse le seuil",amsTemperatureHigh:"Température AMS élevée",amsTemperatureHighDescription:"La température de l'AMS standard dépasse le seuil",amsHtHumidityHigh:"Humidité AMS-HT élevée",amsHtHumidityHighDescription:"L'humidité de l'AMS-HT dépasse le seuil",amsHtTemperatureHigh:"Température AMS-HT élevée",amsHtTemperatureHighDescription:"La température de l'AMS-HT dépasse le seuil",jobAdded:"Tâche ajoutée",jobAddedDescription:"Tâche ajoutée à la file d'attente",jobAssigned:"Tâche assignée",jobAssignedDescription:"Tâche basée sur le modèle assignée à l'imprimante",jobStarted:"Tâche démarrée",jobStartedDescription:"La tâche de la file a commencé l'impression",jobWaiting:"Tâche en attente",jobWaitingDescription:"Tâche en attente de filament ou imprimante",jobSkipped:"Tâche ignorée",jobSkippedDescription:"Tâche ignorée (échec précédent)",jobFailed:"Tâche échouée",jobFailedDescription:"La tâche n'a pas pu démarrer",queueComplete:"File d'attente terminée",queueCompleteDescription:"Toutes les tâches de la file sont terminées",quietHours:"Heures silencieuses",noNotificationsDuring:"Aucune notification pendant ces heures",editProviderToChangeQuietHours:"Modifier le fournisseur pour changer les heures silencieuses",dailyDigest:"Résumé quotidien",batchNotifications:"Regrouper les notifications en un seul résumé quotidien",sendAt:"Envoyer à {{time}}",editProviderToChangeDigestTime:"Modifier le fournisseur pour changer l'heure du résumé",edit:"Modifier",deleteProvider:"Supprimer le fournisseur de notifications",deleteConfirm:"Êtes-vous sûr de vouloir supprimer « {{name}} » ? Cette action est irréversible.",delete:"Supprimer",addTitle:"Ajouter un fournisseur de notifications",editTitle:"Modifier le fournisseur de notifications",nameLabel:"Nom *",namePlaceholder:"Mes notifications",providerTypeLabel:"Type de fournisseur *",configuration:"Configuration",testConfiguration:"Tester la configuration",printerFilter:"Filtre d'imprimante",onlyFromPrinter:"Envoyer uniquement les notifications pour les événements de cette imprimante",quietHoursDnd:"Heures silencieuses (Ne pas déranger)",quietStart:"Début",quietEnd:"Fin",dailyDigestLabel:"Résumé quotidien",sendDigestAt:"Envoyer le résumé à",digestCollected:"Les événements seront collectés et envoyés en un seul résumé à cette heure",notificationEvents:"Événements de notification",progressPercent:"(25 %, 50 %, 75 %)",bedCooledAfterPrint:"(après la fin de l'impression)",cancel:"Annuler",save:"Enregistrer",add:"Ajouter",nameRequired:"Le nom est requis",fieldRequired:"{{field}} est requis",phoneNumber:"Numéro de téléphone",apiKey:"Clé API",serverUrl:"URL du serveur",topic:"Sujet",authToken:"Jeton d'authentification",userKey:"Clé utilisateur",appToken:"Jeton d'application",priority:"Priorité",botToken:"Jeton du bot",chatId:"ID du chat",smtpServer:"Serveur SMTP",smtpPort:"Port SMTP",security:"Sécurité",authentication:"Authentification",username:"Nom d'utilisateur",password:"Mot de passe",fromEmail:"E-mail expéditeur",toEmail:"E-mail destinataire",webhookUrl:"URL du webhook",payloadFormat:"Format du payload",authorization:"Autorisation",titleFieldName:"Nom du champ titre",messageFieldName:"Nom du champ message",editTemplate:"Modifier le modèle : {{name}}",titleLabel:"Titre",bodyLabel:"Corps",titlePlaceholder:"Titre de la notification...",bodyPlaceholder:"Corps de la notification...",availableVariables:"Variables disponibles",clickToInsert:"Cliquer pour insérer à la position du curseur dans le corps",livePreview:"Aperçu en direct",hide:"Masquer",show:"Afficher",loadingPreview:"Chargement de l'aperçu...",enterTemplateContent:"Saisir le contenu du modèle pour voir l'aperçu",titlePreview:"Titre :",bodyPreview:"Corps :",resetToDefault:"Réinitialiser par défaut",titleRequired:"Le titre est requis",bodyRequired:"Le corps est requis",notificationLog:"Journal des notifications",showFailedOnly:"Échecs uniquement",last24Hours:"Dernières 24 heures",last7Days:"7 derniers jours",last30Days:"30 derniers jours",last90Days:"90 derniers jours",justNow:"À l'instant",noFailedNotifications:"Aucune notification échouée",noNotificationsLogged:"Aucune notification enregistrée",unknownProvider:"Fournisseur inconnu",logTitle:"Titre",logMessage:"Message",logError:"Erreur",logProvider:"Fournisseur : {{type}}",logTime:"Heure : {{time}}",refresh:"Actualiser",clearOld:"Purger les anciens",statsSummary:"{{days}} derniers jours :",statsNotifications:"notifications",statsSent:"{{count}} envoyées",statsFailed:"{{count}} échouées",eventTypes:{print_start:"Impression démarrée",print_complete:"Impression terminée",print_failed:"Impression échouée",print_stopped:"Impression arrêtée",print_progress:"Progression",printer_offline:"Imprimante hors ligne",printer_error:"Erreur de l'imprimante",filament_low:"Filament bas",maintenance_due:"Maintenance requise",test:"Test"},userEmail:{title:"Notifications",emailNotifications:"Notifications par e-mail",emailNotificationsDesc:"Recevez des notifications par e-mail pour vos propres travaux d'impression. Les e-mails sont envoyés via les paramètres SMTP configurés dans l'authentification avancée.",sendingTo:"Les notifications seront envoyées à",noEmailWarning:"Votre compte n'a pas d'adresse e-mail. Contactez un administrateur pour en ajouter une.",printJobNotifications:"Notifications de travaux d'impression",printJobNotificationsDesc:"Choisissez quels événements déclenchent des notifications par e-mail pour les travaux d'impression que vous soumettez.",printJobStarts:"Démarrage du travail d'impression",printJobStartsDesc:"Être notifié quand votre travail d'impression commence.",printJobFinishes:"Fin du travail d'impression",printJobFinishesDesc:"Être notifié quand votre travail d'impression se termine avec succès.",printErrors:"Erreurs d'impression",printErrorsDesc:"Être notifié quand votre travail d'impression échoue ou rencontre une erreur.",printJobStops:"Travail d'impression arrêté",printJobStopsDesc:"Être notifié quand votre travail d'impression est annulé ou arrêté.",saveSuccess:"Préférences de notification sauvegardées.",saveError:"Impossible de sauvegarder les préférences de notification."}},richTextEditor:{bold:"Gras",italic:"Italique",underline:"Souligné",bulletList:"Liste à puces",numberedList:"Liste numérotée",alignLeft:"Aligner à gauche",alignCenter:"Centrer",alignRight:"Aligner à droite",addLink:"Ajouter lien",removeLink:"Retirer lien"},externalLinks:{noLinksConfigured:"Aucun lien externe configuré",deleteLink:"Supprimer lien",removeCustomIcon:"Retirer icône personnalisée",openInNewTab:"Ouvrir dans un nouvel onglet",placeholders:{linkName:"Mon Lien"}},keyboardShortcuts:{title:"Raccourcis Clavier",navigation:"Navigation",archivesSection:"Archives",kProfilesSection:"K-Profiles",generalSection:"Général",shortcuts:{goToPrinters:"Aller aux Imprimantes",goToArchives:"Aller aux Archives",goToQueue:"Aller à la File",goToStats:"Aller aux Stats",goToProfiles:"Aller aux Profils Cloud",goToSettings:"Aller aux Paramètres",focusSearch:"Focus recherche",openUploadModal:"Ouvrir téléversement",clearSelection:"Tout déselectionner",contextMenu:"Menu contextuel (cartes)",refreshProfiles:"Rafraîchir profils",newProfile:"Nouveau profil",exitSelectionMode:"Quitter mode sélection",showHelp:"Afficher cette aide"},footer:"Échap ou clic extérieur pour fermer"},notificationLog:{title:"Journal de Notification",events:{printStarted:"Début impression",printComplete:"Fin impression",printFailed:"Échec impression",printStopped:"Arrêt impression",progress:"Progression",printerOffline:"Hors ligne",printerError:"Erreur",lowFilament:"Filament bas",maintenanceDue:"Maintenance",test:"Test"},timeAgo:{justNow:"À l'instant",minutesAgo:"Il y a {{minutes}}m",hoursAgo:"Il y a {{hours}}h"}},restoreBackup:{title:"Restaurer Sauvegarde",restoring:"Restauration...",restoreComplete:"Restauration terminée",restoreFailed:"Échec restauration",importSettings:"Importer les réglages d'un fichier",pleaseWait:"Patientez pendant la restauration",clickToSelect:"Fichier .json ou .zip",howDuplicateHandling:"Gestion des doublons :",categories:{printers:"Imprimantes",smartPlugs:"Prises",notificationProviders:"Fournisseurs",filaments:"Filaments",archives:"Archives",pendingUploads:"Téléversements en attente",settingsTemplates:"Réglages & Modèles"},matchingInfo:{printers:"par numéro de série",smartPlugs:"par adresse IP",notificationProviders:"par nom",filaments:"par nom+type+marque",archives:"par empreinte numérique (hash)",pendingUploads:"par nom de fichier",settingsTemplates:"toujours écrasés"},replaceExisting:"Remplacer existant",keepExisting:"Garder existant",replaceDescription:"Écrase les doublons avec la sauvegarde",keepDescription:"Ne restaure que les éléments absents",caution:"Attention :",cautionText:"L'écrasement remplacera vos réglages. Les codes d'accès imprimantes sont exclus par sécurité.",itemsRestored:"Éléments restaurés",itemsSkipped:"Éléments ignorés",restored:"Restaurés",skipped:"Ignorés (déjà présents)",filesLabel:"Fichiers (3MF, vignettes, etc.)",newApiKeysGenerated:"Nouvelles clés API générées",newApiKeysWarning:"Copiées maintenant, elles ne seront plus visibles !",processingBackup:"Traitement du fichier...",noDataFound:"Aucune donnée trouvée dans le fichier.",failedToRestore:"Échec restaure. Vérifiez le format."},backupExport:{title:"Exporter Sauvegarde",selectData:"Données à inclure",selectAll:"Tout sélectionner",selectNone:"Ne rien sélectionner",categoryDescriptions:{settings:"Langue, thèmes, préférences",notifications:"ntfy, Pushover, Discord, etc.",templates:"Modèles de messages personnalisés",smartPlugs:"Configuration des prises Tasmota",externalLinks:"Liens externes de la barre latérale",printers:"Infos imprimantes (codes d'accès exclus par défaut)",plateDetection:"Images références des plateaux vides",filaments:"Types et coûts filaments",maintenance:"Plannings de maintenance personnalisés",archives:"Données impressions + fichiers (3MF, vignettes, etc.)",projects:"Projets, BOM, pièces jointes",pendingUploads:"En attente revue virtuelle",apiKeys:"Clés Webhook (nouvelles clés générées à l'import)"},requiresPrinters:"Nécessite sélection des imprimantes",zipFileWarning:"Fichier ZIP créé.",zipFileDescription:"Contient tous les médias. Peut être volumineux.",includeAccessCodes:"Inclure Codes d'accès",includeAccessCodesDescription:"Pour migrer vers une autre machine",includeAccessCodesWarning:"Codes en texte clair. Sécurisez ce fichier !",categoriesSelected:"{{selectedCount}} catégories choisies"},pendingUploads:{placeholders:{notes:"Notes sur l'impression..."},discardUpload:"Rejeter",archiveAllUploads:"Tout archiver",discardAllUploads:"Tout rejeter",archive:"Archiver",timeAgo:{justNow:"À l'instant",minutesAgo:"Il y a {{minutes}}m",hoursAgo:"Il y a {{hours}}h",daysAgo:"Il y a {{days}}j"}},apiBrowser:{placeholders:{requestBody:"Corps JSON...",searchEndpoints:"Chercher endpoints..."}},configureAmsSlot:{title:"Configurer le slot AMS",slotConfigured:"Slot configuré !",configuringSlot:"Configuration du slot :",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Chercher presets...",colorPlaceholder:"Nom couleur ou hex (ex: brown, FF8800)",clearCustomColor:"Effacer couleur perso",noCloudPresets:"Profils Cloud absents. Connectez-vous.",noPresetsAvailable:"Aucun preset disponible. Connectez-vous à Bambu Cloud ou importez des profils locaux.",noMatchingPresets:"Aucun profil trouvé.",custom:"Perso",builtin:"Inclus",settingsSentToPrinter:"Réglages envoyés",filamentProfile:"Profil Filament",kProfileLabel:"Profil K (Pressure Advance)",filteringFor:"Filtrage pour : {{material}}",noKProfile:"Pas de profil K (utiliser défaut 0.020)",noMatchingKProfiles:"Aucun profil K trouvé. K=0.020 par défaut sera utilisé.",selectFilamentFirst:"Sélectionnez d'abord un profil filament",kFromCalibration:"K={{value}} de la calibration imprimante",customColorLabel:"Couleur personnalisée (optionnel)",presetColors:"Couleurs {{name}} :",showLessColors:"Moins de couleurs",showMoreColors:"Plus de couleurs",clear:"Effacer",hexLabel:"Hex : #{{hex}}",resetting:"Réinitialisation...",resetSlot:"Réinitialiser le slot",cancel:"Annuler",configuring:"Configuration...",configureSlot:"Configurer le slot"},githubBackup:{title:"Sauvegarde GitHub",history:"Historique",downloadBackup:"Télécharger",restoreBackup:"Restaurer",noBackupsYet:"Aucune sauvegarde"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Chercher tags...",renameTag:"Renommer tag",deleteTag:"Supprimer tag"},notificationTemplates:{placeholders:{title:"Titre notification...",body:"Message notification..."}},batchTag:{placeholders:{newTag:"Nouveau tag..."}},photoGallery:{deletePhoto:"Supprimer photo"},filamentHoverCard:{copySpoolUuid:"Copier UUID bobine"},kProfilesView:{hasNote:"A une note",copyProfile:"Copier profil"},layout:{openMenu:"Ouvrir menu",noPermissionSystemInfo:"Pas d'autorisation système"},dashboard:{dragToReorder:"Glisser pour réorganiser",hideWidget:"Masquer widget"},notificationProviderCard:{deleteNotificationProvider:"Supprimer fournisseur"},fileManagerModal:{closeFileManager:"Fermer gestionnaire",sortFiles:"Trier fichiers",goToParentFolder:"Dossier parent",threeView:"Vue 3D"},embeddedCameraViewer:{refreshStream:"Actualiser flux",close:"Fermer",zoomOut:"Zoom -",resetZoom:"Reset zoom",zoomIn:"Zoom +",dragToResize:"Glisser pour dimension"},timelapseViewer:{skipBack5s:"-5s",skipForward5s:"+5s"},notificationProviders:{descriptions:{email:"Notifications par email SMTP",telegram:"Via bot Telegram",discord:"Via webhook Discord",ntfy:"Push auto-hébergé (ntfy)",pushover:"Push fiable (Pushover)",callmebot:"WhatsApp gratuit via CallMeBot",webhook:"Requête HTTP POST personnalisée"}},logViewer:{searchPlaceholder:"Message ou nom...",noLogEntries:"Aucune entrée journal"},switchbarPopover:{noSwitchesInSwitchbar:"Aucun interrupteur"},projectPageModal:{placeholders:{title:"Titre",designer:"Designer",license:"Licence",description:"Description...",profileTitle:"Titre du profil",profileDescription:"Description du profil..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"En attente",justNow:"À l'instant",now:"Maintenant",minsAgo:"il y a {{count}}m",inMins:"dans {{count}}m",hoursAgo:"il y a {{count}}h",inHours:"dans {{count}}h",daysAgo:"il y a {{count}}j",inDays:"dans {{count}}j"},spoolbuddy:{nav:{dashboard:"Tableau de bord",ams:"AMS",inventory:"Inventaire",writeTag:"Écrire",settings:"Paramètres"},status:{nfcReady:"NFC prêt",nfcOff:"NFC désactivé",offline:"Hors ligne",online:"En ligne",noPrinters:"Aucune imprimante",deviceOffline:"Appareil hors ligne",waitingConnection:"En attente de connexion...",systemReady:"Système prêt",status:"Statut"},dashboard:{readyToScan:"Prêt à scanner",idleMessage:"Placez une bobine sur la balance pour l'identifier",nfcHint:"Le tag NFC sera lu automatiquement",device:"Appareil",syncWeight:"Sync. poids",weightSynced:"Synchronisé !",unknownTag:"Tag inconnu",newTag:"Nouveau tag détecté",onScale:"sur la balance",linkSpool:"Lier à une bobine",linkTagTitle:"Lier le tag à une bobine",linkTag:"Lier le tag",selectSpool:"Sélectionnez une bobine à lier à ce tag :",noUntagged:"Aucune bobine sans tag trouvée",tagDetected:"Tag détecté",noTag:"Pas de tag",tagId:"Tag",grossWeight:"Poids brut",spoolSize:"Taille bobine",close:"Fermer",currentSpool:"Bobine actuelle"},modal:{spoolDetected:"Bobine détectée",assignToAms:"Assigner à l'AMS",syncWeight:"Synchroniser le poids",weightSynced:"Synchronisé !",syncing:"Synchronisation...",newTagDetected:"Nouveau tag détecté",addToInventory:"Ajouter à l'inventaire",assignToAmsTitle:"Assigner à l'AMS",selectSlot:"Sélectionner un emplacement",assign:"Assigner",assigning:"Attribution...",assignSuccess:"Assigné !",assignError:"Échec de l'attribution de la bobine. Veuillez réessayer.",noPrinterSelected:"Sélectionner une imprimante...",noAmsDetected:"Aucun AMS détecté sur cette imprimante",slot:"Emplacement"},weight:{noReading:"Pas de lecture",stable:"Stable",measuring:"Mesure...",tare:"Tarer",calibrate:"Calibrer"},spool:{remaining:"Restant",material:"Matériau",brand:"Marque",color:"Couleur",coreWeight:"Noyau",labelWeight:"Étiquette",scaleWeight:"Balance",netWeight:"Net",lastUsed:"Dernière utilisation"},ams:{noData:"Aucun AMS détecté",connectAms:"Connectez un AMS pour voir les slots",noPrinter:"Aucune imprimante sélectionnée",selectPrinter:"Sélectionnez une imprimante dans la barre supérieure",printerDisconnected:"Imprimante déconnectée",humidity:"Humidité",level:"Niveau",active:"Actif",slot:"Slot",empty:"Vide"},inventory:{search:"Rechercher des bobines...",empty:"Aucune bobine dans l'inventaire",noResults:"Aucune bobine correspondante",spools:"bobines",addSpool:"Ajouter une bobine"},settings:{tabDevice:"Appareil",tabDisplay:"Affichage",tabScale:"Balance",tabUpdates:"Mises à jour",nfcReader:"Lecteur NFC",type:"Type",connection:"Connexion",notConnected:"N/A",deviceInfo:"Info appareil",hostname:"Hôte",uptime:"Temps de fonctionnement",brightness:"Luminosité",saved:"Enregistré",noBacklight:"Aucun rétroéclairage DSI détecté. Le contrôle de luminosité nécessite un écran DSI.",screenBlank:"Délai d'extinction",screenBlankDesc:"L'écran s'éteint après inactivité. Touchez pour réveiller.",displayNote:"La luminosité est appliquée comme filtre logiciel.",scaleCalibration:"Calibration de la balance",currentWeight:"Poids actuel",tareOffset:"Tare",calFactor:"Facteur",knownWeight:"Poids connu",calStep1:"Retirez tout de la balance et appuyez sur Mettre à zéro.",calStep2:"Placez le poids connu sur la balance.",setZero:"Mettre à zéro",calibrateNow:"Calibrer",calibrated:"Calibré",tareSet:"Commande de tare envoyée. En attente de l'appareil...",tareFailed:"Échec de l'envoi de la commande de tare",zeroSet:"Point zéro défini. Placez le poids connu sur la balance.",calibrationDone:"Calibration terminée !",calibrationFailed:"Échec de la calibration",lastCalibrated:"Dernière calibration",stable:"Stable",settling:"Stabilisation...",firmware:"Firmware",scale:"Balance",noDevice:"Aucun appareil SpoolBuddy trouvé",daemonVersion:"Version du daemon",currentVersion:"Actuelle",versionPending:"En attente du daemon...",checking:"Vérification...",checkUpdates:"Vérifier les mises à jour",updateAvailable:"Mise à jour disponible",updateInstructions:"Mise à jour via SSH : exécutez le script d'installation SpoolBuddy.",upToDate:"À jour",includeBeta:"Inclure les versions bêta"},writeTag:{tabExisting:"Bobine existante",tabNew:"Nouvelle bobine",tabReplace:"Remplacer le tag",searchPlaceholder:"Rechercher par matériau, couleur, marque...",noUntaggedSpools:"Aucune bobine sans tag",noTaggedSpools:"Aucune bobine avec tag",selectSpool:"Sélectionnez une bobine, puis placez un NTAG sur le lecteur",placeTag:"Placez un NTAG sur le lecteur",tagReady:"Tag détecté — prêt à écrire",writeTag:"Écrire le tag",replaceTag:"Remplacer le tag",writing:"Écriture du tag...",waiting:"En attente de SpoolBuddy...",writeSuccess:"Tag écrit avec succès !",writeFailed:"Échec de l'écriture",queueFailed:"Impossible de mettre en file la commande d'écriture",tryAgain:"Réessayer",cancel:"Annuler",replaceWarning:"L'ancien tag sera dissocié. Le nouveau tag le remplacera.",deviceOffline:"SpoolBuddy est hors ligne",material:"Matériau",colorName:"Nom de la couleur",color:"Couleur",brand:"Marque",weight:"Poids (g)",createSpool:"Créer la bobine",creating:"Création...",spoolCreated:"Bobine créée ! Prêt à écrire.",createFailed:"Impossible de créer la bobine"},quickMenu:{printerPower:"Alimentation imprimante",systemControls:"Système",restartDaemon:"Redémarrer le daemon",restartBrowser:"Redémarrer le navigateur",reboot:"Redémarrer",shutdown:"Éteindre",swipeToClose:"Glisser vers le bas pour fermer",confirmTitle:"Confirmer",confirmShutdown:"Êtes-vous sûr de vouloir éteindre le SpoolBuddy ? Vous aurez besoin d'un accès physique pour le rallumer.",confirmReboot:"Êtes-vous sûr de vouloir redémarrer le SpoolBuddy ?",confirmRestartDaemon:"Redémarrer le daemon SpoolBuddy ? Le NFC et la balance seront temporairement indisponibles.",confirmRestartBrowser:"Redémarrer le navigateur kiosque ? L'écran sera brièvement noir.",confirm:"Confirmer",confirmPlugOn:"Allumer {{name}} ?",confirmPlugOff:"Éteindre {{name}} ?",turnOn:"Allumer",turnOff:"Éteindre"}},bugReport:{title:"Signaler un bug",description:"Description",descriptionPlaceholder:"Qu'est-ce qui n'a pas fonctionné ? Veuillez décrire le problème...",email:"E-mail (optionnel)",emailPlaceholder:"votre@email.fr",emailPrivacy:"Si fourni, votre e-mail sera inclus dans une section repliée de l'issue GitHub pour que le mainteneur puisse vous contacter.",screenshot:"Capture d'écran",uploadOrPaste:"Télécharger, coller ou glisser une image",dataCollectedSummary:"Quelles données sont incluses dans le rapport ?",dataIncluded:"Inclus :",dataIncludedList:"Version de l'app, OS, architecture, version Python, statistiques de base de données (compteurs uniquement), modèles d'imprimantes, nombre de buses, versions firmware, état de connexion, état des intégrations (Spoolman, MQTT, HA), paramètres non sensibles, nombre d'interfaces réseau, détails Docker, versions des dépendances.",dataNeverIncluded:"Jamais inclus :",dataNeverIncludedList:"Noms d'imprimantes, numéros de série, codes d'accès, mots de passe, adresses IP, adresses e-mail, clés API, tokens, URLs de webhook, noms d'hôtes ou noms d'utilisateurs.",submit:"Envoyer",startLogging:"Lancer la journalisation",stepEnableLogging:"Journalisation activée",stepReproduce:"Reproduisez le problème",stepStopLogging:"Arrêter & envoyer",stopAndSubmit:"Arrêter & Envoyer",maxDuration:"Arrêt auto après {{minutes}} min",stoppingLogs:"Collecte des journaux & envoi...",submitting:"Envoi du rapport de bug...",submitSuccess:"Rapport de bug envoyé avec succès !",submitFailed:"Échec de l'envoi du rapport de bug",thankYou:"Merci !",submitted:"Votre rapport de bug a été soumis.",viewIssue:"Voir l'issue",unexpectedError:"Une erreur inattendue est survenue"}},Nue={nav:{printers:"プリンター",archives:"アーカイブ",queue:"キュー",stats:"統計",profiles:"プロファイル",maintenance:"メンテナンス",projects:"プロジェクト",inventory:"フィラメント",files:"ファイル管理",notifications:"通知",settings:"設定",system:"システム",collapseSidebar:"サイドバーを閉じる",expandSidebar:"サイドバーを開く",update:"アップデート",updateAvailable:"アップデートあり: v{{version}}",updateAvailableBanner:"バージョン {{version}} が利用可能です!",viewUpdate:"アップデートを表示",viewOnGithub:"GitHubで表示",keyboardShortcuts:"キーボードショートカット (?)",switchToLight:"ライトモードに切替",switchToDark:"ダークモードに切替",smartSwitches:"スマートスイッチ",logout:"ログアウト"},common:{save:"保存",saving:"保存中...",cancel:"キャンセル",delete:"削除",edit:"編集",add:"追加",close:"閉じる",confirm:"確認",loading:"読み込み中...",error:"エラー",success:"成功",warning:"警告",enabled:"有効",disabled:"無効",yes:"はい",no:"いいえ",on:"オン",off:"オフ",all:"すべて",none:"なし",search:"検索",filter:"フィルター",sort:"並べ替え",refresh:"更新",download:"ダウンロード",upload:"アップロード",uploading:"アップロード中...",uploadFailed:"アップロード失敗",actions:"操作",status:"ステータス",name:"名前",description:"説明",date:"日付",time:"時間",hours:"時間",minutes:"分",seconds:"秒",days:"日",enable:"有効化",disable:"無効にする",permissions:"権限",noPrinters:"プリンターが登録されていません",noData:"データがありません",linkNotFound:"リンクが見つかりません",required:"必須",optional:"オプション",dismiss:"閉じる",apply:"適用",reset:"リセット",export:"エクスポート",import:"インポート",clear:"クリア",selectAll:"すべて選択",deselectAll:"すべて選択解除",noChange:"— 変更なし —",unchanged:"変更なし",unassigned:"未割当",unknown:"不明",unknownError:"不明なエラー",today:"今日",tomorrow:"明日",asap:"即時",overdue:"期限超過",now:"今すぐ",collapse:"折りたたむ",expand:"展開",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",addedBy:"{{username}}が追加",prints:"プリント",more:"もっと見る",ascending:"昇順",descending:"降順",printer:"プリンター",remove:"削除",type:"種類",print:"印刷",rename:"名前変更",move:"移動",create:"作成",duplicate:"複製",left:"左",right:"右"},printers:{title:"プリンター",addPrinter:"プリンターを追加",editPrinter:"プリンターを編集",deletePrinter:"プリンターを削除",printerName:"プリンター名",serialNumber:"シリアル番号",ipAddress:"IPアドレス / ホスト名",accessCode:"アクセスコード",model:"モデル",nozzleCount:"ノズル数",autoArchive:"自動アーカイブ",status:{available:"利用可能",idle:"待機中",printing:"印刷中",paused:"一時停止",offline:"オフライン",problem:"問題",error:"エラー",finished:"完了",unknown:"不明"},temperatures:{nozzle:"ノズル",bed:"ベッド",chamber:"チャンバー"},progress:"{{percent}}% 完了",timeRemaining:"残り {{time}}",deleteConfirm:"「{{name}}」を削除しますか?",maintenanceOk:"メンテナンス正常",maintenanceWarning:"{{count}}件の警告",maintenanceWarning_plural:"{{count}}件の警告",maintenanceDue:"{{count}}件のメンテナンス期限",maintenanceDue_plural:"{{count}}件の期限",sort:{name:"名前",status:"ステータス",model:"モデル",location:"ロケーション",ascending:"昇順で並べ替え",descending:"降順で並べ替え"},cardSize:{small:"小",medium:"中",large:"大",extraLarge:"特大"},hideOffline:"オフラインを非表示",nextAvailable:"次に完了",powerOn:"電源オン",offlinePrintersWithPlugs:"スマートプラグ付きオフラインプリンター",noPrintersConfigured:"プリンターが設定されていません",search:"プリンターを検索...",noSearchResults:"検索またはフィルターに一致するプリンターがありません",filter:{allStatuses:"すべてのステータス",allLocations:"すべての場所"},readyToPrint:"印刷可能",external:"外部",extL:"Ext-L",extR:"Ext-R",deleteArchives:"印刷アーカイブを削除",noLabel:"ラベルなし",printPreview:"印刷プレビュー",width:"幅",height:"高さ",noObjectsFound:"オブジェクトが見つかりません",objectsLoadedOnPrintStart:"オブジェクトは印刷開始時に読み込まれます",willBeSkipped:"スキップされます",name:"名前",serialCannotBeChanged:"シリアル番号は変更できません",locationHelp:"プリンターのグループ化とキュージョブのフィルタリングに使用",wifiSignal:{veryWeak:"非常に弱い",weak:"弱い",fair:"注意",good:"良好",excellent:"非常に良い"},maintenanceUpToDate:"すべてのメンテナンスが最新です",chamberLightOn:"チャンバーライトをオンにしました",chamberLightOff:"チャンバーライトをオフにしました",files:"ファイル",browseFiles:"プリンターのファイルを参照",autoOffAfterPrint:"印刷後に自動電源オフ",autoOffExecuted:"自動オフが実行されました - リセットするにはプリンターの電源を入れてください",hmsErrors:"クリックしてHMSエラーを表示",viewHmsErrors:"{{count}}件のHMSエラーを表示",resume:"再開",pause:"一時停止",stop:"停止",camera:"カメラ",skipObject:"オブジェクトスキップ",reconnect:"再接続",mqttDebug:"MQTTデバッグ",printerInformation:"プリンター情報",copyToClipboard:"コピー",copied:"コピーしました!",state:"状態",wifiSignalLabel:"WiFi信号",developerMode:"開発者モード",enabled:"有効",disabled:"無効",addedOn:"追加日",sdCard:"SDカード",inserted:"挿入済み",notInserted:"未挿入",totalPrintHours:"印刷時間",activeNozzle:"アクティブ: {{side}}ノズル",nozzleRack:"ノズルラック",nozzleDocked:"ドッキング中",nozzleMounted:"マウント中",nozzleActive:"アクティブ",nozzleIdle:"アイドル",nozzleDiameter:"直径",nozzleType:"タイプ",nozzleStatus:"ステータス",nozzleFilament:"フィラメント",nozzleWear:"摩耗",nozzleMaxTemp:"最高温度",nozzleSerial:"シリアル",nozzleHardenedSteel:"焼入れ鋼",nozzleStainlessSteel:"ステンレス鋼",nozzleTungstenCarbide:"タングステンカーバイド",nozzleFlow:"フロー",nozzleHighFlow:"ハイフロー",nozzleStandardFlow:"スタンダード",firmwareUpdate:"ファームウェアアップデート",firmwareInstructions:"プリンターのタッチスクリーンで",firmwareNav:"に移動",settings:"設定",firmware:"ファームウェア",discoverPrinters:"プリンターを検出",searching:"検索中...",manualEntry:"手動入力",addFromCloud:"クラウドから追加",toast:{printerDeleted:"プリンターを削除しました",missingSpoolAssignment:"{{printer}}で印刷を開始しました。以下のスプール割り当てがありません: {{slots}}",printerAdded:"プリンターを追加しました",printerUpdated:"プリンターを更新しました",failedToDelete:"プリンターの削除に失敗しました",failedToAdd:"プリンターの追加に失敗しました",failedToUpdate:"プリンターの更新に失敗しました",commandSent:"コマンドを送信しました",failedToSendCommand:"コマンドの送信に失敗しました",turnedOn:"{{name}} の電源をオンにしました",failedToPowerOn:"{{name}} の電源オンに失敗しました",scriptTriggered:"スクリプトを実行しました",printStopped:"印刷を停止しました",printPaused:"印刷を一時停止しました",printResumed:"印刷を再開しました",referenceDeleted:"リファレンスを削除しました",detectionAreaSaved:"検出エリアを保存しました",failedToRunScript:"スクリプトの実行に失敗しました",failedToStopPrint:"印刷の停止に失敗しました",failedToPausePrint:"印刷の一時停止に失敗しました",failedToResumePrint:"印刷の再開に失敗しました",failedToControlChamberLight:"チャンバーライトの制御に失敗しました",failedToSetSpeed:"印刷速度の設定に失敗しました",failedToUpdateSetting:"設定の更新に失敗しました",failedToSkipObjects:"オブジェクトのスキップに失敗しました",failedToRereadRfid:"RFIDの再読み取りに失敗しました",failedToCheckPlate:"プレートの確認に失敗しました",failedToUpdateLabel:"ラベルの更新に失敗しました",failedToDeleteReference:"リファレンスの削除に失敗しました",failedToSaveDetectionArea:"検出エリアの保存に失敗しました",plateCheckEnabled:"プレートチェックを有効にしました",plateCheckDisabled:"プレートチェックを無効にしました",calibrationSaved:"キャリブレーションを保存しました!",calibrationFailed:"キャリブレーションに失敗しました",rfidRereadInitiated:"RFID再読み取りを開始しました"},connection:{connected:"接続中",offline:"オフライン"},queue:{inQueue:"キュー内",inQueue_plural:"{{count}}件がキュー内"},controls:"コントロール",rfid:{reread:"RFID再読み取り"},permission:{noAdd:"プリンターを追加する権限がありません",noEdit:"プリンターを編集する権限がありません",noDelete:"プリンターを削除する権限がありません",noControl:"プリンターを制御する権限がありません",noFiles:"このディレクトリにファイルがありません",noAmsRfid:"AMS RFIDを再読み取りする権限がありません",noSmartPlugControl:"スマートプラグを制御する権限がありません",noCamera:"カメラを表示する権限がありません"},modal:{addTitle:"プリンターを追加",editTitle:"プリンターを編集",myPrinter:"マイプリンター",selectModel:"モデルを選択...",locationGroup:"ロケーション / グループ",locationPlaceholder:"例: 工房、オフィス、地下室",autoArchiveLabel:"完了した印刷を自動アーカイブ",fromPrinterSettings:"プリンターの設定から取得",modelOptional:"モデル(任意)",saveChanges:"変更を保存"},skipObjects:{tooltip:"オブジェクトスキップ",onlyWhilePrinting:"オブジェクトスキップ(印刷中のみ)",requiresMultiple:"オブジェクトスキップ(2個以上必要)",title:"オブジェクトスキップ",matchIdsInfo:"プリンター画面のIDと照合してください",printerShowsIds:"プリンター画面にビルドプレート上のオブジェクトIDが表示されます",skipSelected:"選択をスキップ",skipping:"スキップ中...",noObjectsSelected:"オブジェクトが選択されていません",selectObjectsToSkip:"現在の印刷からスキップするオブジェクトを選択してください",skipped:"スキップ済み",objectsSkipped:"オブジェクトをスキップしました",activeCount:"{{count}}個アクティブ",waitForLayer:"オブジェクトをスキップするにはレイヤー2以降をお待ちください(現在レイヤー{{layer}})",skip:"スキップ",confirmTitle:"オブジェクトをスキップしますか?",confirmMessage:"「{{name}}」をスキップしますか?この操作は元に戻せません。"},confirm:{deleteTitle:"プリンターを削除",deleteMessage:"「{{name}}」を削除しますか?すべての接続設定が削除されます。",deleteArchivesNote:"このプリンターのすべての印刷履歴が完全に削除されます。",keepArchivesNote:"印刷履歴は保持されますが、このプリンターとの関連は解除されます。",stopTitle:"印刷を停止",stopMessage:"「{{name}}」の現在の印刷を停止しますか?印刷ジョブがキャンセルされます。",stopButton:"印刷を停止",pauseTitle:"印刷を一時停止",pauseMessage:"「{{name}}」の現在の印刷を一時停止しますか?",pauseButton:"印刷を一時停止",resumeTitle:"印刷を再開",resumeMessage:"「{{name}}」の印刷を再開しますか?",resumeButton:"印刷を再開",powerOnTitle:"プリンターの電源をオン",powerOnMessage:"「{{name}}」の電源をオンにしますか?",powerOnButton:"電源オン",powerOffTitle:"プリンターの電源をオフ",powerOffMessage:"「{{name}}」の電源をオフにしますか?",powerOffWarning:"警告: 「{{name}}」は現在印刷中です!電源をオフにしますか?印刷が中断され、プリンターが損傷する可能性があります。",powerOffButton:"電源オフ"},bulk:{select:"選択",selectAll:"すべて選択",selectByLocation:"場所で選択",selected:"{{count}}件選択中",actions:{stop:"停止",pause:"一時停止",resume:"再開",clearPlate:"ベッドをクリア",clearHMS:"通知をクリア"},confirm:{stopTitle:"{{count}}件の印刷を停止",stopMessage:"{{count}}台のプリンターのアクティブな印刷をキャンセルします。この操作は元に戻せません。",stopButton:"すべて停止",pauseTitle:"{{count}}件の印刷を一時停止",pauseMessage:"{{count}}台のプリンターのアクティブな印刷を一時停止します。",pauseButton:"すべて一時停止",clearPlateTitle:"{{count}}台のプリントベッドをクリア",clearPlateMessage:"{{count}}台のプリンターのプリントベッドをクリアし、キュー内のジョブが開始される場合があります。",clearPlateButton:"すべてクリア"},success:"{{count}}台のプリンターで{{action}}が完了",partial:"{{succeeded}}件成功、{{failed}}件失敗",noneApplicable:"選択したプリンターにこのアクションに適した状態のものがありません",selectByState:"ステータスで選択"},discovery:{title:"プリンター",searching:"検索中...",scanning:"スキャン中...",scanProgress:"スキャン中... {{scanned}}/{{total}}",foundPrinters:"{{count}}台のプリンターを検出",noPrintersFound:"プリンターが見つかりません",noPrintersFoundSubnet:"指定されたサブネットにプリンターが見つかりません。",noPrintersFoundNetwork:"ネットワーク上にプリンターが見つかりません。",allConfigured:"検出されたすべてのプリンターは既に設定済みです。",alreadyAdded:"追加済み",select:"選択",manualEntry:"手動入力",addFromCloud:"クラウドから追加",subnetToScan:"スキャンするサブネット",dockerNote:"Dockerを検出しました。プリンターのサブネットをCIDR表記で入力してください。docker-compose.ymlでnetwork_mode: hostが必要です。",scanSubnet:"サブネットをスキャンしてプリンターを検出",discoverNetwork:"ネットワーク上のプリンターを検出",scanningSubnet:"サブネットでBambuプリンターをスキャン中...",scanningNetwork:"ネットワークをスキャン中...",serialRequired:"シリアル番号が必要です",unknown:"不明",failedToStart:"印刷の開始に失敗しました"},drying:{start:"乾燥開始",stop:"乾燥停止",temperature:"温度",duration:"時間",hours:"時間",timeRemaining:"残り {{time}}",active:"乾燥中",notSupported:"乾燥非対応",powerRequired:"AMS電源アダプターを接続して乾燥を有効にしてください",startingDrying:"乾燥を開始しています...",stoppingDrying:"乾燥を停止しています...",rotateTray:"乾燥中にスプールを回転"},filaments:"フィラメント",openCameraOverlay:"カメラオーバーレイを開く",openCameraWindow:"カメラを新しいウィンドウで開く",firmwareUpdateAvailable:"ファームウェアアップデートあり: {{current}} → {{latest}}",firmwareUpToDate:"ファームウェア {{version}} — 最新",firmwareUpdateButton:"アップデート",plateDetection:{noPermission:"このページにアクセスする権限がありません。",enabledClick:"プレートチェック有効 - クリックして無効化",disabledClick:"プレートチェック無効 - クリックして有効化",manageCalibration:"プレート検出キャリブレーションを管理",calibrationRequired:"キャリブレーションが必要です",calibrationInstructions:"ビルドプレートが<strong>完全に空</strong>であることを確認してから、キャリブレーションをクリックしてください。",calibrationDescription:"キャリブレーションは空のプレートのリファレンス画像を撮影します。以降のチェックではこのリファレンスと比較してオブジェクトを検出します。",calibrationTip:"<strong>ヒント:</strong> 異なるプレート用に最大5つのキャリブレーションを保存できます。チェック時に最適なものが自動的に使用されます。",plateEmpty:"プレートは空のようです",objectsDetected:"オブジェクトを検出しました",confidence:"信頼度",difference:"差分",analysisPreview:"分析プレビュー:",analysisLegend:"緑の枠 = 検出エリア、赤のオーバーレイ = キャリブレーションとの差分",savedReferences:"保存済みリファレンス ({{count}}/{{max}})",deleteReference:"リファレンスを削除",labelPlaceholder:"ラベル...",clickToEdit:"{{label}} - クリックして編集",clickToAddLabel:"クリックしてラベルを追加"},speed:{title:"印刷速度",silent:"サイレント (50%)",standard:"スタンダード (100%)",sport:"スポーツ (124%)",ludicrous:"ルディクラス (166%)"},fans:{partCooling:"パーツ冷却ファン",auxiliary:"補助ファン",chamber:"チャンバーファン"},clickToViewHmsErrors:"クリックしてHMSエラーを表示",estimatedCompletion:"完了予定時刻",plateNumber:"プレート {{number}}",slotOptions:"スロットオプション",amsPopup:{friendlyName:"AMS名",friendlyNamePlaceholder:"例: AMS フレンドリー名",serialNumber:"シリアル番号",firmwareVersion:"ファームウェア",save:"保存",clear:"クリア",noEditPermission:"AMS ユニットの名前を変更する権限がありません"},firmwareModal:{title:"ファームウェアアップデート",titleUpToDate:"ファームウェア情報",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",releaseNotes:"リリースノート",checkingPrereqs:"前提条件を確認中...",sdCardReady:"SDカード準備完了。下をクリックしてファームウェアをアップロードしてください。",uploadedSuccess:"ファームウェアをSDカードにアップロードしました!",applyInstructions:"プリンターでアップデートを適用するには:",step1:"プリンターのタッチスクリーンで設定に移動",step2:"ファームウェアに移動",step3:"SDカードからアップデートを選択",step4:"アップデートには10〜20分かかります",done:"完了",starting:"開始中...",uploadFirmware:"ファームウェアをアップロード",uploadFailed:"アップロード開始に失敗しました: {{error}}",uploadedToast:"ファームウェアをアップロードしました!プリンター画面からアップデートを実行してください。"},accessCodePlaceholder:"プリンター設定から取得",roi:{title:"プリンター",xStart:"X開始",yStart:"Y開始",width:"幅",height:"高さ",instruction:"ビルドプレートに焦点を合わせるように検出エリアを調整してください。プレビューの緑の枠が現在のエリアを示しています。"},developerModeWarning:"開発者LANモードが有効になっていません: {{names}}。一部の機能が動作しない可能性があります。",howToEnable:"有効化方法",incompatibleFile:"このファイルは{{slicedFor}}用にスライスされていますが、このプリンターは{{printerModel}}です",dropNotPrintable:".gcodeおよび.gcode.3mfファイルのみ印刷できます",dropToPrint:"ドロップして印刷",cannotPrint:"プリンター使用中"},archives:{title:"印刷アーカイブ",searchPlaceholder:"アーカイブを検索...",filterByPrinter:"プリンターで絞り込み",filterByStatus:"ステータスで絞り込み",sortBy:"並べ替え",sortNewest:"新しい順",sortOldest:"古い順",sortName:"名前順",sortDuration:"時間順",sortLargest:"大きい順",sortSmallest:"小さい順",sortSize:"サイズ",noArchives:"アーカイブが見つかりません",noArchivesSearch:"検索条件に一致するアーカイブがありません",originalPrintNotVisible:"元の印刷が表示されていません - フィルターをクリアしてみてください",noArchivesYet:"アーカイブはまだありません",prints:"件",pagination:{showing:"表示中",to:"〜",of:"/",show:"表示",page:"ページ",all:"すべて"},loadingArchives:"アーカイブを読み込み中...",releaseToUpload:"ドロップしてアップロード",showAll:"すべて表示",showFavoritesOnly:"お気に入りのみ表示",gridView:"グリッド表示",listView:"リスト表示",calendarView:"カレンダー表示",logView:"印刷ログ",manageTags:"タグを管理",showFailedPrints:"失敗した印刷を表示",hideFailedPrints:"失敗した印刷を非表示",hideDuplicates:"重複を非表示",viewOriginalPrint:"クリックして元の印刷を表示 (#{{id}})",printTime:"印刷時間",filamentUsed:"フィラメント使用量",cost:"コスト",reprint:"再印刷",preview:"プレビュー",deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",favorite:"お気に入り",unfavorite:"お気に入りから削除",viewDetails:"詳細を表示",status:{completed:"完了",failed:"失敗",stopped:"中止"},toast:{source3mfAttached:"ソース3MFを添付しました: {{filename}}",failedUploadSource3mf:"ソース3MFのアップロードに失敗しました",source3mfRemoved:"ソース3MFを削除しました",failedRemoveSource3mf:"ソース3MFの削除に失敗しました",f3dAttached:"F3Dを添付しました: {{filename}}",failedUploadF3d:"F3Dのアップロードに失敗しました",f3dRemoved:"F3Dを削除しました",failedRemoveF3d:"F3Dの削除に失敗しました",timelapseAttached:"タイムラプスを添付しました: {{filename}}",timelapseAlreadyAttached:"タイムラプスは既に添付されています",noMatchingTimelapse:"一致するタイムラプスが見つかりません",failedScanTimelapse:"タイムラプスのスキャンに失敗しました",failedAttachTimelapse:"タイムラプスの添付に失敗しました",timelapseRemoved:"タイムラプスを削除しました",failedRemoveTimelapse:"タイムラプスの削除に失敗しました",timelapseUploaded:"タイムラプスをアップロードしました: {{filename}}",failedUploadTimelapse:"タイムラプスのアップロードに失敗しました",archiveDeleted:"アーカイブを削除しました",failedDeleteArchive:"アーカイブの削除に失敗しました",addedToFavorites:"お気に入りに追加しました",removedFromFavorites:"お気に入りから削除しました",projectUpdated:"プロジェクトを更新しました",failedUpdateProject:"プロジェクトの更新に失敗しました",linkCopied:"リンクをクリップボードにコピーしました",failedCopyLink:"リンクのコピーに失敗しました",photoDeleted:"写真を削除しました",failedDeletePhoto:"写真の削除に失敗しました",failedDeleteArchives:"アーカイブの削除に失敗しました",failedUpdateFavorites:"お気に入りの更新に失敗しました",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました"},menu:{print:"印刷",schedule:"スケジュール",openInBambuStudio:"スライサーで開く",slice:"スライス",externalLink:"外部リンク",viewOnMakerWorld:"MakerWorldで表示",preview3d:"3Dプレビュー",viewTimelapse:"タイムラプスを表示",scanForTimelapse:"タイムラプスをスキャン",uploadTimelapse:"タイムラプスをアップロード",removeTimelapse:"タイムラプスを削除",downloadSource3mf:"ソース3MFをダウンロード",uploadSource3mf:"ソース3MFをアップロード",replaceSource3mf:"ソース3MFを置換",removeSource3mf:"ソース3MFを削除",uploadF3d:"F3Dをアップロード",replaceF3d:"F3Dを置換",downloadF3d:"Fusion 360デザインファイルをダウンロード",removeF3d:"F3Dを削除",download:"ダウンロード",copyDownloadLink:"ダウンロードリンクをコピー",qrCode:"QRコード",viewPhotos:"{{count}}枚の写真を表示",viewPhotosCount:"写真を表示 ({{count}})",projectPage:"プロジェクトページ",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",edit:"編集",goToProject:"プロジェクトへ: {{name}}",addToProject:"プロジェクトに追加",removeFromProject:"プロジェクトから削除",loading:"アーカイブを読み込み中...",noProjectsAvailable:"利用可能なプロジェクトがありません",select:"選択",deselect:"選択解除",delete:"削除"},permission:{noReprint:"このアーカイブを再印刷する権限がありません",noAddToQueue:"キューに追加する権限がありません",noUpdateArchives:"アーカイブを更新する権限がありません",noUploadFiles:"ファイルをアップロードする権限がありません",noDownload:"アーカイブをダウンロードする権限がありません",noCopyLink:"ダウンロードリンクをコピーする権限がありません",noDelete:"このアーカイブを削除する権限がありません",noCreate:"アーカイブを作成する権限がありません"},card:{previousPlate:"前のプレート",nextPlate:"次のプレート",plateNumber:"プレート {{number}}",moreOptions:"その他のオプション",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",cancelled:"キャンセル",failed:"失敗",duplicate:"重複",duplicateTitle:"このモデルは以前印刷されています",openSource3mf:"ソース3MFをBambu Studioで開く(右クリックでオプション表示)",downloadF3d:"Fusion 360デザインファイルをダウンロード",viewTimelapse:"タイムラプスを表示",viewPhoto:"写真を表示",viewPhotos:"{{count}}枚の写真を表示",openFolder:"フォルダーを開く: {{name}}",slicedFile:"スライス済みファイル - 印刷可能",sourceFile:"ソースファイルのみ - AMSマッピング不可",gcode:"GCODE",source:"ソース",project:"プロジェクト",estimated:"推定: {{time}}",actual:"実際: {{time}}",accuracy:"精度: {{percent}}%",filament:"{{weight}}g",layer:"レイヤー",layers:"レイヤー",object:"{{count}}オブジェクト",objects:"{{count}}オブジェクト",slicedFor:"{{model}}用にスライス",uploadedBy:"アップロード者",noPermissionReprint:"再印刷する権限がありません",noFileForReprint:"3MFファイルがありません — 印刷記録時にプリンターからファイルをダウンロードできませんでした",noPermissionEdit:"プロファイルを編集する権限がありません",noPermissionDelete:"アーカイブを削除する権限がありません",reprint:"再印刷",schedulePrint:"印刷をスケジュール",schedule:"スケジュール",openInBambuStudio:"スライサーで開く",openInBambuStudioToSlice:"スライサーでスライス",slice:"スライス",externalLink:"外部リンク",makerWorld:"MakerWorld: {{designer}}",viewProject:"プロジェクトを表示",noExternalLink:"外部リンクなし",preview3d:"3Dプレビュー",download:"ダウンロード",edit:"編集",delete:"削除"},modal:{deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",deleteButton:"削除",removeSource3mf:"ソース3MFを削除",removeSource3mfConfirm:'"{{name}}"からソース3MFファイルを削除してもよろしいですか?元のスライサープロジェクトファイルが削除されます。',removeButton:"削除",removeF3d:"F3Dを削除",removeF3dConfirm:'"{{name}}"からFusion 360デザインファイルを削除してもよろしいですか?',removeTimelapse:"タイムラプスを削除",removeTimelapseConfirm:'"{{name}}"からタイムラプス動画を削除してもよろしいですか?',timelapse:"{{name}} - タイムラプス",selectTimelapse:"タイムラプスを選択",selectTimelapseDesc:"自動一致が見つかりませんでした。この印刷のタイムラプスを選択してください:",deleteArchives:"印刷アーカイブを削除",deleteArchivesConfirm:"{{count}}件のアーカイブを削除しますか?この操作は元に戻せません。",deleteCount:"{{count}}件を削除"},page:{title:"印刷アーカイブ",printsCount:"{{count}}回印刷",dropFilesHere:".3mfファイルをここにドロップ",releaseToUpload:"ドロップしてアップロード",only3mfSupported:".3mfファイルのみ対応しています",close:"閉じる",selected:"{{count}}件選択中",selectAll:"すべて選択",tags:"タグ",project:"プロジェクト",favorite:"お気に入り",delete:"削除",toggledFavorites:"{{count}}件のアーカイブのお気に入りを切替えました",failedUpdateFavorites:"お気に入りの更新に失敗しました",archivesDeleted:"{{count}}件のアーカイブを削除しました",failedDeleteArchives:"アーカイブの削除に失敗しました",photoDeleted:"写真を削除しました",failedDeletePhoto:"写真の削除に失敗しました"},list:{name:"名前",printer:"プリンター",date:"日付",size:"サイズ",actions:"操作",hasTimelapse:"タイムラプスあり"},log:{date:"日時",printName:"印刷名",printer:"プリンター",user:"ユーザー",status:"ステータス",duration:"所要時間",filament:"フィラメント",allPrinters:"全プリンター",allUsers:"全ユーザー",allStatuses:"全ステータス",cancelled:"キャンセル",skipped:"スキップ",dateFrom:"開始日",dateTo:"終了日",noEntries:"印刷ログが見つかりません",showing:"{{total}}件中{{count}}件を表示",rowsPerPage:"行数",page:"ページ",prev:"前へ",next:"次へ",clearLog:"ログをクリア",clearLogTitle:"印刷ログをクリア",clearLogConfirm:"すべての印刷ログエントリが完全に削除されます。アーカイブとキューアイテムには影響しません。この操作は元に戻せません。よろしいですか?",clearLogButton:"すべてクリア",cleared:"{{count}}件のログエントリを削除しました",clearFailed:"印刷ログの削除に失敗しました"}},queue:{title:"印刷キュー",subtitle:"印刷ジョブのスケジュールと管理",addToQueue:"キューに追加",print:"印刷",reprint:"再印刷",schedulePrint:"印刷をスケジュール",editQueueItem:"キューアイテムを編集",printToPrinters:"{{count}}台のプリンターで印刷",queueToPrinters:"{{count}}台のプリンターでキュー追加",queueSelectedPlates:"{{count}}プレートをキューに追加",selectAllPlates:"全{{count}}プレートを選択",deselectAll:"全て解除",printQueued:"キューに追加しました",itemsQueued:"{{count}}件をキューに追加しました",sending:"送信中...",sendingProgress:"送信中 {{current}}/{{total}}...",adding:"追加中...",addingProgress:"追加中 {{current}}/{{total}}...",savingProgress:"保存中 {{current}}/{{total}}...",clearQueue:"キューをクリア",clearHistory:"履歴をクリア",emptyQueue:"キューは空です",position:"順番",scheduledTime:"予定時刻",moveUp:"上に移動",moveDown:"下に移動",startNow:"今すぐ開始",printingInProgress:"印刷中...",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",itemCount:"{{count}}件",itemCount_plural:"{{count}}件のアイテム",dragToReorder:"ドラッグして並べ替え(ASAPのみ)",reorderHint:"順番はASAPアイテムのみに影響します。スケジュール済みアイテムは設定時刻に実行されます。",sjf:{label:"SJF",tooltip:"短いジョブ優先 — スケジューラーが短い印刷を優先します"},addedBy:"{{username}}が追加",nextInQueue:"次のキュー",clearPlate:"プレートをクリアして次を開始",clearPlateSuccess:"プレートをクリアしました — 次の印刷の準備完了",plateReady:"プレートをクリアしました — 次の印刷の準備完了",plateNumber:"プレート {{index}}",quantity:"数量",quantityHint:"{{count}}件のキューアイテムを作成",activeBatches:"アクティブなバッチ",batchProgress:"{{total}}件中{{completed}}件完了",cancelBatch:"残りをキャンセル",batchCancelled:"残りのバッチアイテムをキャンセルしました",cancelBatchConfirmTitle:"バッチをキャンセル",cancelBatchConfirmMessage:"このバッチの残りの保留中アイテムをすべてキャンセルしますか?",batch:"バッチ",sections:{currentlyPrinting:"印刷中",queued:"キュー中",history:"履歴"},status:{pending:"待機中",waiting:"待機中",printing:"印刷中",paused:"一時停止",completed:"完了",failed:"失敗",skipped:"スキップ",cancelled:"キャンセル済み"},summary:{printing:"印刷中",queued:"キュー中",totalTime:"キュー合計時間",totalWeight:"キュー合計重量",history:"履歴"},filter:{allPrinters:"すべてのプリンター",unassigned:"未割当",allStatus:"すべてのステータス",allLocations:"すべてのロケーション",any:"すべて"},sort:{byPosition:"順番で並べ替え",byName:"名前で並べ替え",byPrinter:"プリンターで並べ替え",bySchedule:"スケジュールで並べ替え",byDate:"日付で並べ替え",ascendingOldest:"昇順(古い順)",descendingNewest:"降順(新しい順)"},badges:{staged:"ステージ済み",requiresPrevious:"前の成功が必要",autoPowerOff:"自動電源オフ",gcodeInjection:"G-code"},empty:{title:"スケジュールされた印刷はありません",description:"アーカイブページのコンテキストメニューから「スケジュール」オプションを使用するか、ファイルをドラッグ&ドロップして始めましょう。"},time:{asap:"即時",overdue:"期限超過",now:"今すぐ",lessThanMinute:"1分以内",inMinutes:"{{count}}分後",inHours:"{{count}}時間後"},actions:{stopPrint:"印刷を停止",startPrint:"印刷を開始",requeue:"再キュー"},bulkEdit:{title:"{{count}}件のアイテムを編集",title_plural:"{{count}}件のアイテムを編集",description:"変更した設定のみが選択されたアイテムに適用されます。",printer:"プリンター",noChange:"— 変更なし —",queueOptions:"キューオプション",staged:"ステージ済み",autoPowerOff:"印刷後に自動電源オフ",requirePrevious:"前の成功を必要とする",printOptions:"印刷オプション",bedLevelling:"ベッドレベリング",flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",layerInspection:"第一層検査",timelapse:"タイムラプス",useAms:"AMS使用",applyChanges:"変更を適用",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",editSelected:"選択を編集",cancelSelected:"選択をキャンセル"},confirm:{cancelTitle:"スケジュール済み印刷をキャンセル",cancelMessage:"「{{name}}」をキャンセルしますか?",stopTitle:"印刷を停止",stopMessage:"現在の印刷「{{name}}」を停止しますか?プリンター上の印刷ジョブがキャンセルされます。",removeTitle:"履歴から削除",removeMessage:"「{{name}}」をキュー履歴から削除しますか?",clearHistoryTitle:"履歴をクリア",clearHistoryMessage:"{{count}}件の履歴をすべて削除しますか?",cancelButton:"印刷をキャンセル",stopButton:"印刷を停止",thisPrint:"この印刷",thisItem:"このアイテム"},toast:{cancelled:"キャンセル済み",cancelFailed:"アイテムのキャンセルに失敗しました",removed:"キューアイテムを削除しました",removeFailed:"プロジェクトからのアーカイブ削除に失敗しました",stopped:"印刷を停止しました",stopFailed:"印刷の停止に失敗しました",released:"印刷をキューにリリースしました",startFailed:"印刷の開始に失敗しました",reorderFailed:"キューの並べ替えに失敗しました",historyCleared:"{{count}}件の履歴をクリアしました",clearHistoryFailed:"履歴のクリアに失敗しました",updateFailed:"アイテムの更新に失敗しました",bulkCancelled:"{{count}}件のアイテムをキャンセルしました",bulkCancelFailed:"アイテムのキャンセルに失敗しました"},timeline:{listView:"リスト",timelineView:"タイムライン",unassigned:"未割当",noData:"この日の予定された印刷はありません",allDoneBy:"すべての印刷は {{time}} までに完了予定",staged:"ステージング",filterAll:"すべて表示",filterPrinting:"印刷中",filterQueued:"待機中",time:{anyMoment:"まもなく",minutesLeft:"残り{{minutes}}分",hoursLeft:"残り{{hours}}時間",hoursMinutesLeft:"残り{{hours}}時間{{minutes}}分"},day:{previous:"前日",next:"翌日",today:"今日"}},permissions:{noStopPrint:"印刷を停止する権限がありません",noStartPrint:"印刷を開始する権限がありません",noEdit:"このキューアイテムを編集する権限がありません",noCancel:"このキューアイテムをキャンセルする権限がありません",noRequeue:"アイテムを再キューする権限がありません",noRemove:"このキューアイテムを削除する権限がありません",noClearHistory:"すべての履歴をクリアする権限がありません",noEditItems:"キューアイテムを編集する権限がありません",noCancelItems:"キューアイテムをキャンセルする権限がありません"}},backgroundDispatch:{unknownFile:"不明なファイル",unknownPrinter:"不明なプリンター",startingPrints:"印刷開始中",progressSummary:"{{complete}}/{{total}} 完了 • 配信済み: {{dispatched}} • 処理中: {{processing}}",expandDetails:"配信詳細を展開",collapseDetails:"配信詳細を折りたたむ",dismissToast:"配信トーストを閉じる",cancelDispatchJob:"配信ジョブをキャンセル",cancel:"キャンセル",cancelling:"キャンセル中…",status:{dispatched:"配信済み",processing:"処理中",completed:"完了",failed:"失敗",cancelled:"キャンセル済み"},toast:{cancellingUpload:"アップロードをキャンセル中...",cancelled:"配信をキャンセルしました",cancelFailed:"配信のキャンセルに失敗しました",completeWithFailures:"バックグラウンド配信完了: {{completed}} 件成功、{{failed}} 件失敗",completeSuccess:"バックグラウンド配信完了: {{completed}} 件成功",printStartedRemaining:"{{completed}} 件の印刷を開始、残り {{remaining}} 件送信中..."}},stats:{title:"統計",subtitle:"ウィジェットをドラッグして並べ替え。目のアイコンをクリックして非表示。",overview:"概要",totalPrints:"総印刷数",successRate:"成功率",totalPrintTime:"総印刷時間",printTime:"印刷時間",totalFilament:"総フィラメント使用量",filamentUsed:"フィラメント使用量",filamentCost:"フィラメントコスト",totalCost:"総コスト",energyUsed:"エネルギー使用量",energyCost:"エネルギーコスト",averagePrintTime:"平均印刷時間",printsPerDay:"1日あたりの印刷数",byPrinter:"プリンター別",printsByPrinter:"プリンター別印刷数",byMaterial:"素材別",byMonth:"月別",last7Days:"過去7日間",last30Days:"過去30日間",last90Days:"過去90日間",allTime:"全期間",quickStats:"クイック統計",printActivity:"印刷アクティビティ",filamentTypes:"フィラメントタイプ",filamentTrends:"フィラメントトレンド",failureAnalysis:"失敗分析",timeAccuracy:"時間精度",successful:"成功",failed:"失敗",perfectEstimate:"100% = 完全な推定",noTimeAccuracyData:"時間精度データがありません",noFilamentData:"フィラメントデータがありません",noPrinterData:"プリンターデータがありません",noPrintData:"印刷データがありません",noPrintDataLast30Days:"過去30日間の印刷データがありません",failureReasons:"失敗理由",topFailureReasons:"主な失敗理由",failedPrintsCount:"{{failed}} / {{total}} 件の印刷が失敗",lastWeekRate:"先週: {{rate}}%",resetLayout:"レイアウトをリセット",recalculateCosts:"コストを再計算",recalculateCostsHint:"現在のフィラメント価格ですべてのアーカイブコストを再計算",exportStats:"統計をエクスポート",exportAsCsv:"CSVでエクスポート",exportAsExcel:"Excelでエクスポート",hiddenCount:"{{count}}件非表示",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました",layoutReset:"レイアウトをリセットしました",recalculatedCosts:"{{count}}件のアーカイブのコストを再計算しました",recalculateFailed:"コストの再計算に失敗しました",loadingStats:"統計を読み込み中...",noPermissionResetLayout:"レイアウトをリセットする権限がありません",noPermissionRecalculate:"コストを再計算する権限がありません",noPrintDataInRange:"選択した期間にデータがありません",periodFilament:"フィラメント使用量",periodCost:"コスト",avgPerPrint:"1印刷あたりの平均",usageOverTime:"時間推移",filamentByWeight:"重量",printDuration:"印刷時間分布",printerUtilization:"プリンター稼働率",filamentSuccess:"素材別成功率",printHabits:"印刷習慣",printTimeOfDay:"時間帯別プリント",colorDistribution:"カラー分布",noColorData:"カラーデータがありません",records:"記録",longestPrint:"最長プリント",heaviestPrint:"最重プリント",mostExpensivePrint:"最高額",busiestDay:"最多プリント日",successStreak:"連続成功",streakPrint:"連続プリント",streakPrints:"{{count}}連続プリント",printerStats:"プリンター統計",hours:"時間",avgPrints:"平均印刷数",noArchiveData:"印刷データがありません",filamentByTime:"推移",avgWeight:"平均重量",avgTime:"平均時間",filamentByPrints:"印刷数",timeframe:{today:"今日","this-week":"今週","this-month":"今月","last-7":"過去7日間","last-30":"過去30日間","last-90":"過去90日間","this-year":"今年","all-time":"全期間",custom:"カスタム",from:"開始",to:"終了"},allUsers:"全ユーザー",noUser:"ユーザーなし(システム)",filterByUser:"ユーザーでフィルター"},maintenance:{title:"メンテナンス",overview:"概要",allOk:"すべてのメンテナンスは最新です",dueCount:"{{count}}件の期限到来",dueCount_plural:"{{count}}件の期限到来",warningCount:"{{count}}件の警告",warningCount_plural:"{{count}}件の警告",totalPrintTime:"総印刷時間",nextMaintenance:"次回メンテナンス",nothingDue:"予定なし",tasks:"タスク",lastPerformed:"前回実施日",interval:"間隔",hoursRemaining:"残り{{hours}}時間",hoursOverdue:"{{hours}}時間超過",markDone:"完了にする",performMaintenance:"メンテナンスを実施",history:"履歴",noHistory:"メンテナンス履歴がありません",editPrintHours:"印刷時間を編集",currentHours:"現在の時間",statusTab:"ステータス",settingsTab:"設定",overdueCount:"{{count}}件超過",dueSoonCount:"{{count}}件まもなく期限",dueSoon:"まもなく期限",allGood:"問題なし",overdueBy:"{{duration}}超過",dueIn:"あと{{duration}}",timeLeft:"残り{{duration}}",day:"1日",days:"日",week:"1週間",weeks:"{{count}}週間",month:"1ヶ月",months:"{{count}}ヶ月",year:"1年",maintenanceTypes:"メンテナンスタイプ",maintenanceTypesDescription:"システムタイプとカスタムメンテナンスタスク",addCustomType:"カスタムタイプを追加",restoreDefaults:"デフォルトタスクを復元",intervalType:"インターバルタイプ",intervalValue:"間隔 ({{type}})",icon:"アイコン",documentationLink:"ドキュメントリンク(任意)",assignToPrinters:"プリンターに割り当て",selectAtLeastOnePrinter:"プリンターを1台以上選択してください",addType:"タイプを追加",custom:"カスタム",printHours:"印刷時間",calendarDays:"カレンダー日数",exampleName:"例: HEPAフィルター交換",viewDocumentation:"ドキュメントを表示",timeBasedInterval:"時間ベースのインターバル",intervalOverrides:"インターバルのオーバーライド",intervalOverridesDescription:"特定のプリンターの間隔をカスタマイズ",assignedToPrinters:"割り当て済みプリンター:",noPrintersAssigned:"プリンター未割り当て",addPrinterShort:"追加:",printersAssignedClick:"{{count}}台のプリンターを割り当て済み - クリックして管理",removeFromPrinter:"このプリンターから削除",types:{lubricateCarbonRods:"カーボンロッドの潤滑",lubricateRails:"リニアレールの潤滑",cleanNozzle:"ノズル/ホットエンドの清掃",checkBelts:"ベルト張力の確認",cleanBuildPlate:"ビルドプレートの清掃",checkExtruder:"エクストルーダーギアの確認",checkCooling:"冷却ファンの確認",generalInspection:"総合点検",cleanCarbonRods:"カーボンロッドの清掃",lubricateSteelRods:"スチールロッドの潤滑",cleanSteelRods:"スチールロッドの清掃",cleanLinearRails:"リニアレールの清掃",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},maintenanceComplete:"メンテナンスを完了としてマークしました",typeUpdated:"メンテナンスタイプを更新しました",typeDeleted:"メンテナンスタイプを削除しました",defaultsRestored:"デフォルトタスクを{{count}}件復元しました",printHoursUpdated:"印刷時間を更新しました",printerAssigned:"プリンターを割り当てました",printerRemoved:"プリンターを削除しました",deleteTypeConfirm:"「{{name}}」を削除しますか?",deleteSystemTypeTitle:"デフォルトのメンテナンスタスクを削除しますか?",deleteSystemTypeMessage:"デフォルトのメンテナンスタスク「{{name}}」を削除してもよろしいですか?",noPermissionUpdate:"メンテナンス記録を更新する権限がありません",noPermissionPerform:"メンテナンスを実行する権限がありません",noPermissionEditTypes:"メンテナンスタイプを編集する権限がありません",noPermissionDeleteTypes:"メンテナンスタイプを削除する権限がありません",noPermissionEditHours:"メンテナンス時間を編集する権限がありません",noPermissionRemovePrinter:"プリンターの割り当てを解除する権限がありません",noPermissionAssignPrinter:"プリンターを割り当てる権限がありません",noPermissionEditIntervals:"メンテナンス間隔を編集する権限がありません",configureSettings:"メンテナンスタイプと間隔を設定"},settings:{title:"設定",general:"一般",tabs:{general:"一般",smartPlugs:"スマートプラグ",notifications:"通知",queue:"ワークフロー",filament:"フィラメント",network:"ネットワーク",apiKeys:"APIキー",virtualPrinter:"仮想プリンター",users:"認証",backup:"バックアップ",emailAuth:"メール認証",ldap:"LDAP"},ldap:{title:"LDAP認証",enabledDesc:"LDAP認証が有効です",disabledDesc:"LDAP認証が無効です",disabledHint:"以下のLDAP設定を構成して保存し、有効にしてください。",enabled:"LDAP認証を有効にしました",disabled:"LDAP認証を無効にしました",feature1:"LDAP資格情報でログインできます",feature2:"ローカル管理者アカウントはフォールバックとして残ります",feature3:"ログイン時にLDAPグループがBamBuddyグループにマッピングされます",serverConfig:"LDAPサーバー設定",serverUrl:"サーバーURL",serverUrlHint:"標準はldap://、SSL接続はldaps://を使用",security:"セキュリティ",securityHint:"StartTLSはプレーン接続をTLSにアップグレードします。LDAPSは最初からTLSを使用します。",bindDn:"バインドDN(サービスアカウント)",bindPassword:"バインドパスワード",searchBase:"検索ベースDN",userFilter:"ユーザー検索フィルター",userFilterHint:"{username}はログインユーザー名に置き換えられます。OpenLDAPの場合は(uid={username})を使用。",autoProvision:"ユーザー自動作成",autoProvisionHint:"初回LDAPログイン時にBamBuddyアカウントを自動作成",defaultGroup:"デフォルトグループ",defaultGroupNone:"— なし(フォールバックなし)—",defaultGroupHint:"LDAPユーザーが認証されたがマッピングされたLDAPグループに属していない場合に割り当てられるフォールバックグループ。空欄の場合、マッピングされていないユーザーは権限なしのままになります。",groupMapping:"グループマッピング(JSON)",groupMappingHint:"LDAPグループDNをBamBuddyグループにマッピング。利用可能なグループ: ",testConnection:"接続テスト",settingsSaved:"LDAP設定を保存しました",errors:{serverRequired:"LDAPサーバーURLは必須です",searchBaseRequired:"検索ベースDNは必須です",enableAuthFirst:"先に認証を有効にしてください",configureLdapFirst:"先にLDAP設定を保存してください"}},email:{smtpSettings:"SMTP設定",smtpHost:"SMTPサーバー",smtpPort:"SMTPポート",security:"セキュリティ",authentication:"認証",username:"ユーザー名",password:"パスワード",fromEmail:"送信元メールアドレス",fromName:"送信者名",testConnection:"SMTP接続テスト",testRecipient:"テスト受信者メール",sendTest:"テストメール送信",sending:"送信中...",save:"設定を保存",saving:"保存中...",advancedAuth:"高度な認証",advancedAuthEnabled:"高度な認証が有効です",advancedAuthEnabledDesc:"メールベースのユーザー管理機能が有効になっています。新規ユーザーには自動生成されたパスワードがメールで送信され、ユーザーはパスワード忘れ機能でパスワードをリセットできます。",advancedAuthDisabled:"高度な認証が無効です",advancedAuthDisabledDesc:"高度な認証を有効にして、ユーザー管理のメールベース機能を有効化してください。",enable:"有効にする",disable:"無効にする",feature1:"パスワードは自動生成され、新規ユーザーにメールで送信されます",feature2:"ユーザーはユーザー名またはメールでログインできます",feature3:"パスワード忘れ機能が利用可能です",feature4:"管理者はメールでユーザーパスワードをリセットできます",errors:{requiredFields:"すべての必須フィールドに入力してください",usernameRequired:"認証が有効な場合、ユーザー名は必須です",enterTestEmail:"テストメールアドレスを入力してください",smtpServerAndEmail:"テストする前にSMTPサーバーと送信元メールを入力してください",usernamePasswordRequired:"認証が有効な場合、ユーザー名とパスワードは必須です",configureSmtpFirst:"最初にSMTP設定を構成してテストしてください",enableAuthFirst:"メール関連機能をご利用いただくには、まず認証を有効にしてください。"},success:{settingsSaved:"SMTP設定を保存しました"},securityOptions:{starttls:"STARTTLS (ポート 587)",ssl:"SSL/TLS (ポート 465)",none:"なし (ポート 25)"},authOptions:{enabled:"有効",disabled:"無効"}},appearance:"外観",notifications:"通知",smartPlugs:"スマートプラグ",spoolman:"Spoolman",updates:"アップデート",language:"言語",languageDescription:"表示言語を選択してください",theme:"テーマ",themeLight:"ライト",themeDark:"ダーク",themeSystem:"システム設定に従う",defaultView:"デフォルト画面",defaultViewDescription:"アプリ起動時に表示するページ",checkForUpdates:"アップデートを確認",autoUpdate:"自動アップデート",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",upToDate:"最新です",updateAvailable:"アップデートあり",notificationLanguage:"通知の言語",notificationLanguageDescription:"プッシュ通知の言語",bedCooledThreshold:"ベッド冷却しきい値",bedCooledThresholdDescription:"印刷後にベッドが冷却されたと見なす温度",userNotificationsEnabled:"ユーザー通知",userNotificationsEnabledDescription:"ユーザー通知メニューと印刷ジョブイベントのメール通知を有効にします。高度な認証が必要です。",userNotificationsDisabledHint:"ユーザー通知を使用するには高度な認証を有効にしてください。",notificationProviders:"通知プロバイダー",addProvider:"プロバイダーを追加",editProvider:"プロバイダーを編集",providerType:"プロバイダーの種類",testNotification:"テスト通知",testSuccess:"テスト通知を送信しました",testFailed:"テスト通知の送信に失敗しました",quietHours:"おやすみ時間",quietHoursDescription:"この時間帯は通知を送信しません",quietHoursStart:"開始",quietHoursEnd:"終了",events:{title:"通知イベント",printStart:"印刷開始",printComplete:"印刷完了",printFailed:"印刷失敗",printStopped:"印刷中止",printProgress:"進捗マイルストーン",printProgressDescription:"25%, 50%, 75%で通知",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",filamentLow:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",maintenanceDueDescription:"メンテナンスが必要なときに通知"},smartPlug:{title:"スマートプラグ",add:"スマートプラグを追加",edit:"スマートプラグを編集",name:"名前",ipAddress:"IPアドレス",linkedPrinter:"連携プリンター",autoOn:"自動電源オン",autoOnDescription:"印刷開始時に電源を入れる",autoOff:"自動電源オフ",autoOffDescription:"印刷完了後に電源を切る",offDelay:"オフ遅延",offDelayMinutes:"印刷後の待機時間(分)",offDelayTemp:"ノズル温度が下回ったとき",currentState:"現在の状態",turnOn:"電源オン",turnOff:"電源オフ"},filamentTracking:"フィラメント追跡",filamentTrackingDesc:"フィラメントスプールの追跡方法を選択してください。内蔵インベントリまたは外部Spoolmanサーバーを使用できます。",filamentChecks:"フィラメントチェック",disableFilamentWarnings:"フィラメント警告を無効化",disableFilamentWarningsDesc:"印刷またはキュー追加時にフィラメント不足の警告を表示しない",preferLowestFilament:"残量が少ないフィラメントを優先",preferLowestFilamentDesc:"複数のスプールが一致する場合、残量が最も少ないものを使用します",trackingModeBuiltIn:"内蔵インベントリ",trackingModeBuiltInDesc:"RFID自動検出と使用量追跡を含む",trackingModeSpoolmanDesc:"外部フィラメント管理サーバー",builtInFeatureRfid:"AMS内のBambu Lab RFIDスプールを自動検出",builtInFeatureUsage:"プリントごとのフィラメント消費量を追跡",builtInFeatureCatalog:"スプール、カラー、K値プロファイルを管理",builtInFeatureThirdParty:"サードパーティ製スプールをインベントリスプールに割り当て可能",amsSyncButton:"AMSから重量を同期",amsSyncTitle:"AMSからスプール重量を同期",amsSyncMessage:"接続されたプリンターの現在のAMS残量値で、すべてのインベントリスプール重量を上書きします。破損した重量データの復旧に使用してください。プリンターがオンラインである必要があります。",amsSyncing:"同期中...",amsSyncSuccess:"{{synced}}個のスプールを同期、{{skipped}}個をスキップ",amsSyncError:"AMSからの重量同期に失敗しました",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"Spoolmanサーバーのurl(例:http://localhost:7912)",spoolmanConnected:"接続中",spoolmanDisconnected:"未接続",status:"ステータス",connect:"接続",disconnect:"切断",howSyncWorks:"同期の仕組み",syncInfoRfidOnly:"RFIDを搭載した公式Bambu Labスプールのみ同期されます",syncInfoAutoCreate:"新しいスプールは初回同期時にSpoolmanに自動作成されます",syncInfoThirdPartySkipped:"Bambu Lab以外のスプール(サードパーティ、リフィル)はスキップされます",linkingExistingSpools:"既存スプールのリンク",linkingExistingSpoolsDesc:"既存のSpoolmanスプールをAMSにリンクするには、AMSスロットにカーソルを合わせて「Spoolmanにリンク」をクリックしてください。",syncMode:"同期モード",syncModeAuto:"自動",syncModeManual:"手動のみ",syncModeAutoDesc:"変更が検出されるとAMSデータが自動的に同期されます",syncModeManualDesc:"手動でトリガーした場合のみ同期",syncAmsData:"AMSデータを同期",syncAmsDataDesc:"プリンターのAMSデータをSpoolmanに手動同期",allPrinters:"全プリンター",noDefaultPrinter:"デフォルトなし(毎回選択)",sidebarOrder:"サイドバーの順序",saveThumbnails:"サムネイルを保存",captureFinishPhoto:"完了写真を撮影",noPrintersConfigured:"プリンターが設定されていません",archiveMode:{always:"常にアーカイブを作成",never:"アーカイブを作成しない",ask:"毎回確認"},checkForUpdatesLabel:"アップデートを確認",checkPrinterFirmware:"プリンターファームウェアの確認",includeBetaUpdates:"ベータ版を含める",includeBetaUpdatesDesc:"アップデート確認時にベータ版およびプレリリース版を通知する",enableRetry:"リトライを有効化",homeAssistantDescription:"Home Assistantに接続してHA REST APIでスマートプラグを制御します。switch、light、input_booleanエンティティに対応しています。",environmentManagedLabel:"(環境変数で管理)",autoEnabledViaEnv:"環境変数により自動的に有効化されました",urlFromEnvReadOnly:"HA_URL環境変数で設定された値(読み取り専用)",tokenFromEnvReadOnly:"HA_TOKEN環境変数で設定された値(読み取り専用)",mqttConnectedTo:"接続先:",prometheusDescription:"プリンターデータをPrometheus形式で公開",noSmartPlugsTitle:"スマートプラグが設定されていません",noSmartPlugsDescription:"Tasmotaベースのスマートプラグを追加して、エネルギー消費を追跡し、電源制御を自動化します。",noProvidersTitle:"プロバイダーが設定されていません",noProvidersDescription:"アラートを受信するにはプロバイダーを追加してください。",noTemplatesAvailable:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを生成してください。",apiPermissionView:"プリンターステータスとキューを表示",apiPermissionEdit:"印刷キューにアイテムを追加・削除",apiKeysEmptyTitle:"APIキーがありません",apiKeysEmptyDescription:"外部サービスと連携するためのAPIキーを作成してください。",noUsersFound:"ユーザーが見つかりません",noGroupsFound:"グループが見つかりません",noGroupsAvailable:"利用可能なグループがありません",passwordsDoNotMatch:"パスワードが一致しません",systemGroupWarning:"システムグループ名は変更できません",authDisabledTitle:"認証が無効です",authDisabledFeature1:"システムへのアクセスにログインを要求",authDisabledFeature2:"グループベースの権限で複数ユーザーを作成",authDisabledFeature3:"50以上のきめ細かな権限でアクセスを制御",userHasCreated:"このユーザーは以下を作成しています:",userItemsQuestion:"これらのアイテムをどうしますか?",deleteUserConfirm:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。",actionCannotBeUndone:"この操作は元に戻せません",addFirstSmartPlug:"最初のスマートプラグを追加",providers:"プロバイダー",log:"ログ",testAll:"すべてテスト",testResults:"テスト結果",testPassedCount:"{{count}}件成功",testFailedCount:"{{count}}件失敗",messageTemplates:"メッセージテンプレート",messageTemplatesDescription:"各イベントの通知メッセージをカスタマイズ。",apiKeys:"APIキー",apiKeysDescription:"外部連携やWebhook用のAPIキーを作成します。",createKey:"キーを作成",apiKeyCreated:"APIキーを作成しました",apiKeyCopyWarning:"今すぐこのキーをコピーしてください - 再表示されません!",useInApiBrowser:"APIブラウザーで使用",createNewApiKey:"新しいAPIキーを作成",keyName:"キー名",keyNamePlaceholder:"例: Home Assistant, OctoPrint",readStatus:"ステータスの読み取り",readStatusDescription:"プリンターのステータスとキューを表示",manageQueue:"キューの管理",manageQueueDescription:"印刷キューへのアイテムの追加と削除",controlPrinter:"プリンターの制御",controlPrinterDescription:"印刷の一時停止、再開、停止",unnamedKey:"名前なしキー",lastUsed:"最終使用:",read:"読み取り",control:"制御",createFirstKey:"最初のキーを作成",webhookEndpoints:"Webhookエンドポイント",webhookApiKeyHint:"X-API-KeyヘッダーでAPIキーを使用してください。",webhook:{getAllStatus:"全プリンターステータスを取得",getSpecificStatus:"特定のプリンターステータスを取得",addToQueue:"印刷キューに追加",pausePrint:"印刷を一時停止",resumePrint:"印刷を再開",stopPrint:"印刷を停止"},apiBrowser:"APIブラウザ",apiBrowserDescription:"すべての利用可能なAPIエンドポイントを探索してテストします。",apiKeyForTesting:"テスト用APIキー",apiKeyPlaceholder:"CallMeBot APIキー",apiKeyHint:"このキーはX-API-Keyヘッダーとしてリクエストに送信されます。",deleteApiKeyTitle:"APIキーを削除",deleteApiKeyMessage:"このAPIキーを削除してもよろしいですか?このキーを使用しているすべての連携が動作しなくなります。",deleteKey:"キーを削除",amsDisplayThresholds:"AMS表示しきい値",amsThresholdsDescription:"AMS湿度と温度インジケーターの色しきい値を設定します。",humidity:"湿度",goodGreen:"良好(緑)≤",fairOrange:"普通(オレンジ)≤",aboveFairBad:"普通のしきい値以上は赤(悪い)で表示",fairAlsoDryingThreshold:"このしきい値は自動乾燥のトリガーにも使用されます",temperature:"温度",goodBlue:"良好(青)≤",aboveFairHot:"普通のしきい値以上は赤(高温)で表示",historyRetention:"履歴の保持",keepSensorHistory:"センサー履歴の保持期間",historyRetentionDescription:"古い湿度と温度データは自動的に削除されます",defaultPrintOptions:"デフォルト印刷オプション",defaultPrintOptionsDescription:"新しい印刷のデフォルト値を設定します。印刷ダイアログで個別に変更できます。",defaultBedLevelling:"ベッドレベリング",defaultBedLevellingDesc:"印刷前にベッドを自動レベリング",defaultFlowCali:"フローキャリブレーション",defaultFlowCaliDesc:"押出フローのキャリブレーション",defaultVibrationCali:"振動キャリブレーション",defaultVibrationCaliDesc:"リンギングアーティファクトを低減",defaultLayerInspect:"第1層検査",defaultLayerInspectDesc:"AIによる第1層の検査",defaultTimelapse:"タイムラプス",defaultTimelapseDesc:"タイムラプス動画を記録",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"プレートクリア確認",requirePlateClear:"プレートクリア確認を必須にする",requirePlateClearDescription:"有効にすると、スケジューラーは完了したプリンターでキューの印刷を開始する前に、プリンターごとのプレートクリア確認を待ちます。プレートを物理的に確認するファームワークフローでは無効にしてください。",gcodeInjection:"G-codeインジェクション",gcodeInjectionDescription:"Farmloop、SwapMod、AutoClear、Printflow 3Dなどの自動印刷システム用に、印刷の開始と終了時にカスタムG-codeを挿入します。スニペットはプリンターモデルごとに設定し、キューアイテム��「G-codeを挿入」を有効にすると適用されます。",gcodeInjectionNoPrinters:"プリンターが見つかりません。G-codeスニペットを設定するにはプリンターを追加してください。",gcodeStartLabel:"開始G-code",gcodeEndLabel:"終了G-code",gcodeStartPlaceholder:"印刷開始前に挿入されるG-code...",gcodeEndPlaceholder:"印刷終了後に追加されるG-code...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"自動乾燥",queueDryingDescription:"キュー印刷の合間にプリンターがアイドル状態の時、AMSフィラメントを自動的に乾燥します。上記の湿度しきい値を使用します。",queueDryingEnabled:"自動乾燥を有効にする",queueDryingEnabledDescription:"プリンターがアイドル状態で湿度がしきい値を超えた場合、AMS乾燥を自動的に開始",queueDryingBlock:"乾燥完了まで待機",queueDryingBlockDescription:"乾燥が完了するまで印刷キューをブロックします。オフの場合、印刷が優先されます。",ambientDryingEnabled:"常時乾燥",ambientDryingEnabledDescription:"キューに関係なく、アイドル状態のプリンターで湿度がしきい値を超えた場合に自動的にフィラメントを乾燥。",dryingPresets:"乾燥プリセット",dryingPresetsDescription:"フィラメントタイプごとの温度と時間。AMS 2 Proは低温、AMS-HTは高温に対応。",dryingFilament:"フィラメント",printModal:"印刷ダイアログ",expandCustomMapping:"カスタムマッピングをデフォルトで展開",expandCustomMappingDescription:"複数プリンターに印刷する際、プリンターごとのAMSマッピングを展開表示",authentication:"認証",authEnabledDescription:"ユーザー認証でインスタンスが保護されています",authDisabledDescription:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",authDisabledMessage:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",enableAuthentication:"認証を有効にする",currentUser:"現在のユーザー",changePassword:"パスワードを変更",admin:"管理者",users:"ユーザー",addUser:"ユーザーを追加",groups:"グループ",addGroup:"グループを追加",system:"システム",noDescription:"説明なし",userCount:"{{count}}人のユーザー",permissionCount:"{{count}}件の権限",createUser:"ユーザーを作成",username:"ユーザー名",enterUsername:"ユーザー名を入力",password:"パスワード",enterPassword:"パスワードを入力(6文字以上)",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",viewReleaseOnGitHub:"GitHubでリリースを表示",turnAllPlugsOn:"すべてのプラグをオン",turnAllPlugsOff:"すべてのプラグをオフ",clearNotificationLogs:"通知ログをクリア",clearLogsMessage:"30日以上前のすべての通知ログを完全に削除します。この操作は元に戻せません。",clearLogs:"通知ログを削除",resetUiPreferences:"UI設定をリセット",resetUiPreferencesMessage:"すべてのUI設定をデフォルトにリセットします:サイドバー順序、テーマ、ダッシュボードレイアウト、表示モード、ソート設定。プリンター、アーカイブ、サーバー設定は影響を受けません。クリア後にページがリロードされます。",resetPreferences:"設定をリセット",deleteGroupTitle:"グループを削除",deleteGroupMessage:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。",deleteGroup:"グループを削除",disableAuthenticationTitle:"認証を無効化",disableAuthenticationMessage:"認証を無効にしますか?Bambuddyインスタンスにログインなしでアクセスできるようになります。ユーザーはデータベースに残りますが、認証は無効になります。",disableAuthentication:"認証を無効化",configureBambuddy:"Bambuddyを設定",systemDefault:"システムデフォルト",archiveSettings:"アーカイブ設定",newWindow:"新しいウィンドウ",embeddedOverlay:"埋め込みオーバーレイ",preferredSlicer:"優先スライサー",preferredSlicerDescription:"ファイルを開くスライサーアプリケーションを選択",externalCameras:"外部カメラ",costTracking:"コスト追跡",printsOnly:"印刷のみ",totalConsumption:"総消費量",dataManagement:"データ管理",storageUsage:"ストレージ使用量",storageUsageDescription:"カテゴリ別のデータ使用量の内訳",storageUsageTotal:"合計",storageUsageErrors:"エラー",storageUsageOtherBreakdown:"その他(静的アセット、スクリプト、設定ファイルを含む)",storageUsageSystem:"システム",storageUsageData:"データ",storageUsageUnavailable:"ストレージ使用量情報は利用できません",clearNotificationLogsDescription:"30日以上前の通知ログを削除",resetUiPreferencesDescription:"サイドバー順序、テーマ、表示モード、レイアウト設定をリセット。プリンター、アーカイブ、設定は影響を受けません。",enableHomeAssistant:"Home Assistantを有効化",enableMqtt:"MQTTを有効化",useTls:"TLSを使用",enableMetricsEndpoint:"メトリクスエンドポイントを有効化",availableMetrics:"利用可能なメトリクス",editUser:"ユーザーを編集",deleteUserTitle:"ユーザーを削除",groupName:"グループ名",leaveEmptyForAnonymous:"匿名の場合は空のまま",leaveEmptyForNoAuth:"認証なしの場合は空のまま",enterNewPassword:"新しいパスワードを入力",confirmNewPassword:"新しいパスワードを確認",enterGroupName:"グループ名を入力",enterDescriptionOptional:"説明を入力(任意)",enterCurrentPassword:"現在のパスワードを入力",enterNewPasswordMin6:"新しいパスワードを入力(6文字以上)",toast:{keyCopied:"キーをクリップボードにコピーしました",copyFailed:"キーのコピーに失敗しました",keyAddedToBrowser:"キーをAPIブラウザに追加しました",clearLogsFailed:"ログの削除に失敗しました",uiPreferencesReset:"UI設定をリセットしました。更新中...",authDisabled:"認証を無効にしました",authDisableFailed:"認証の無効化に失敗しました",apiKeyCreated:"APIキーを作成しました",apiKeyDeleted:"APIキーを削除しました",userCreated:"ユーザーが正常に作成されました",userUpdated:"ユーザーが正常に更新されました",userDeleted:"ユーザーが正常に削除されました",groupCreated:"グループを作成しました",groupUpdated:"グループを更新しました",groupDeleted:"グループを削除しました",fillRequiredFields:"必須項目をすべて入力してください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です",enterGroupName:"グループ名を入力",settingsSaved:"設定を保存しました",cameraSettingsSaved:"カメラ設定を保存しました",enterCameraUrl:"カメラURLを入力してください",passwordChanged:"パスワードが正常に変更されました",connectionFailed:"接続失敗",testFailed:"テスト通知の送信に失敗しました",cameraConnected:"カメラ接続{{resolution}}"},testConnection:"接続テスト",catalog:{spoolCatalog:"スプールカタログ",spoolCatalogDescription:"ブランド/タイプ別の空スプール重量。スプール追加時の自動重量検索に使用されます。",searchCatalog:"カタログを検索...",addNewEntry:"新しいエントリを追加",namePlaceholder:"名前(例:Bambu Lab - プラスチック)",weight:"重量",type:"タイプ",default:"デフォルト",custom:"カスタム",noMatch:"検索に一致するエントリがありません",empty:"カタログにエントリがありません",deleteEntry:"エントリを削除",deleteConfirm:"「{{name}}」を削除してもよろしいですか?",resetCatalog:"カタログをリセット",resetConfirm:"カタログをデフォルトにリセットしますか?カスタムエントリはすべて削除されます。",loadFailed:"スプールカタログの読み込みに失敗しました",nameWeightRequired:"名前と重量は必須です",entryAdded:"エントリを追加しました",addFailed:"エントリの追加に失敗しました",entryUpdated:"エントリを更新しました",updateFailed:"エントリの更新に失敗しました",entryDeleted:"エントリを削除しました",deleteFailed:"エントリの削除に失敗しました",resetSuccess:"カタログをデフォルトにリセットしました",resetFailed:"カタログのリセットに失敗しました",exported:"{{count}}件のエントリをエクスポートしました",imported:"{{added}}件のエントリをインポートしました({{skipped}}件スキップ)",importFailed:"インポートに失敗しました:無効なJSON形式",exportTooltip:"カタログをJSONにエクスポート",importTooltip:"JSONからカタログをインポート",resetTooltip:"デフォルトにリセット",selectedCount:"{{count}}件選択中",deleteSelected:"選択を削除",bulkDeleteConfirm:"{{count}}件のエントリーを削除してもよろしいですか?",bulkDeleted:"{{count}}件のエントリーを削除しました",bulkDeleteFailed:"エントリーの削除に失敗しました"},colorCatalog:{title:"カラーカタログ",description:"メーカー/素材別のフィラメントカラー。スプール追加時の自動カラー検索に使用されます。",searchColors:"カラーを検索...",allManufacturers:"すべてのメーカー",addNewColor:"新しいカラーを追加",manufacturer:"メーカー",colorName:"カラー名",hex:"Hex",materialOptional:"素材(任意)",showing:"{{total}}件中{{filtered}}件を表示",noMatch:"検索に一致するカラーがありません",empty:"カタログにカラーがありません",deleteColor:"カラーを削除",deleteConfirm:"「{{name}}」を削除してもよろしいですか?",resetCatalog:"カラーカタログをリセット",resetConfirm:"カタログをデフォルトにリセットしますか?カスタムカラーはすべて削除されます。",sync:"同期",starting:"開始中...",syncTooltip:"FilamentColors.xyzから同期(2000+カラー)",loadFailed:"カラーカタログの読み込みに失敗しました",fieldsRequired:"メーカー、カラー名、Hexカラーは必須です",colorAdded:"カラーを追加しました",addFailed:"カラーの追加に失敗しました",colorUpdated:"カラーを更新しました",updateFailed:"カラーの更新に失敗しました",colorDeleted:"カラーを削除しました",deleteFailed:"カラーの削除に失敗しました",resetSuccess:"カラーカタログをデフォルトにリセットしました",resetFailed:"カタログのリセットに失敗しました",syncUpToDate:"最新の状態です({{count}}件のカラーを確認)",syncComplete:"{{added}}件の新しいカラーを追加しました({{skipped}}件は既に存在)",syncError:"同期エラー",syncFailed:"FilamentColors.xyzからの同期に失敗しました",exported:"{{count}}件のカラーをエクスポートしました",imported:"{{added}}件のカラーをインポートしました({{skipped}}件スキップ)",importFailed:"インポートに失敗しました:無効なJSON形式",selectedCount:"{{count}}件選択中",deleteSelected:"選択を削除",bulkDeleteConfirm:"{{count}}件のカラーを削除してもよろしいですか?",bulkDeleted:"{{count}}件のカラーを削除しました",bulkDeleteFailed:"カラーの削除に失敗しました"},dateFormat:"日付形式",dateFormatUs:"US (MM/DD/YYYY)",dateFormatEu:"EU (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"時刻形式",timeFormat12:"12時間制 (3:30 PM)",timeFormat24:"24時間制 (15:30)",defaultPrinter:"デフォルトプリンター",defaultPrinterDescription:"アップロード、再印刷、その他の操作でこのプリンターを事前選択します。",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"サイドバーの項目をドラッグして並べ替え。ここでデフォルトの順序にリセット。",setDefault:"デフォルト設定",sidebarOrderSetDefaultHint:"デフォルト設定は、まだカスタマイズしていないユーザーに現在のメニュー順序を適用します。",sidebarDefaultSet:"デフォルトメニュー順序を設定しました。",sidebarDefaultCleared:"デフォルトメニュー順序をクリアしました。",sidebarDefaultFailed:"デフォルトメニュー順序の設定に失敗しました。",reset:"リセット",darkMode:"ダークモード",lightMode:"ライトモード",active:"(アクティブ)",background:"背景",accent:"アクセント",style:"スタイル",bgNeutral:"ニュートラル",bgWarm:"ウォーム",bgCool:"クール",bgOled:"OLEDブラック",bgSlate:"スレートブルー",bgForest:"フォレストグリーン",accentGreen:"グリーン",accentTeal:"ティール",accentBlue:"ブルー",accentOrange:"オレンジ",accentPurple:"パープル",accentRed:"レッド",styleClassic:"クラシック",styleGlow:"グロー",styleVibrant:"ビビッド",themeToggleHint:"サイドバーの太陽/月アイコンでダークモードとライトモードを切り替えます。",autoArchivePrints:"印刷を自動アーカイブ",autoArchiveDescription:"印刷完了時に3MFファイルを自動保存",saveThumbnailsDescription:"3MFファイルからプレビュー画像を抽出して保存",captureFinishPhotoDescription:"印刷完了時にプリンターカメラから写真を撮影",ffmpegNotInstalled:"ffmpegがインストールされていません",ffmpegRequired:"カメラ撮影にはffmpegが必要です。<brew>brew install ffmpeg</brew>(macOS)または<apt>apt install ffmpeg</apt>(Linux)でインストールしてください。",camera:"カメラ",cameraViewMode:"カメラ表示モード",cameraOverlayDescription:"メイン画面上にリサイズ可能なオーバーレイでカメラを表示",cameraWindowDescription:"別のブラウザウィンドウでカメラを表示",externalCamerasDescription:"内蔵プリンターカメラの代わりに外部カメラを設定。MJPEGストリーム、RTSP、HTTPスナップショット、USBカメラ(V4L2)をサポート。有効にすると、ライブビューと完了写真に外部カメラが使用されます。",cameraPlaceholderUsb:"デバイスパス (/dev/video0)",cameraPlaceholderUrl:"カメラURL (rtsp://... または http://...)",cameraTypeMjpeg:"MJPEGストリーム",cameraTypeRtsp:"RTSPストリーム",cameraTypeSnapshot:"HTTPスナップショット",cameraTypeUsb:"USBカメラ (V4L2)",cameraRotation:"回転",test:"テスト",connected:"接続済み",disconnected:"未接続",currency:"通貨",defaultFilamentCost:"デフォルトフィラメントコスト(kg単価)",electricityCost:"電気料金(kWh単価)",energyDisplayMode:"エネルギー表示モード",energyModePrintDescription:"ダッシュボードに印刷中の消費エネルギーの合計を表示",energyModeTotalDescription:"ダッシュボードにスマートプラグの累計エネルギーを表示",fileManager:"ファイルマネージャー",createArchiveEntry:"印刷時にアーカイブエントリを作成",createArchiveEntryDescription:"ファイルマネージャーから印刷時に、オプションでアーカイブエントリを作成",lowDiskSpaceWarning:"ディスク容量不足の警告",lowDiskSpaceDescription:"空きディスク容量がこのしきい値を下回った場合に警告を表示",printerFirmware:"プリンターファームウェア",checkFirmwareDescription:"Bambu Labのプリンターファームウェア更新を確認",bambuddySoftware:"Bambuddyソフトウェア",autoCheckDescription:"起動時に自動的に新しいバージョンを確認",checkNow:"今すぐ確認",updateAvailableVersion:"アップデート利用可能: v{{version}}",releaseNotes:"リリースノート",updateViaDocker:"Docker Composeでアップデート:",installUpdate:"アップデートをインストール",latestVersionRunning:"最新バージョンを使用しています",failedToCheckUpdates:"アップデートの確認に失敗しました: {{error}}",backupRestore:"バックアップと復元",backupRestoreDescription:"設定のエクスポート/インポートとGitHubバックアップの設定",goToBackup:"バックアップへ",externalUrl:"外部URL",externalUrlDescription:"Bambuddyがアクセス可能な外部URL。通知画像や外部連携に使用されます。",bambuddyUrl:"Bambuddy URL",externalUrlHint:"プロトコルとポートを含めてください(例: http://192.168.1.100:8000)",ftpRetry:"FTPリトライ",ftpRetryDescription:"プリンターのWi-Fiが不安定な場合にFTP操作をリトライ。3MFダウンロード、印刷アップロード、タイムラプスダウンロード、ファームウェア更新に適用。",autoRetryDescription:"失敗したFTP操作を自動的にリトライ",retryAttempts:"リトライ回数",retryDelay:"リトライ遅延",connectionTimeout:"接続タイムアウト",time_one:"{{count}}回",time_other:"{{count}}回",second_one:"{{count}}秒",second_other:"{{count}}秒",nSeconds:"{{count}}秒",increaseForWeakWifi:"Wi-Fiが弱いプリンター用に増やしてください",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Home Assistantに接続してHA REST API経由でスマートプラグを制御。switch、light、input_boolean、scriptエンティティをサポート。",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"長期アクセストークン",haTokenHint:"HAでトークンを作成: プロフィール → 長期アクセストークン → トークンを作成",connectionSuccessful:"接続成功",connectionFailed:"接続失敗",haConnectionSuccess:"Home Assistantへの接続に成功しました。",haConnectionFailed:"Home Assistantへの接続に失敗しました。",mqttPublishing:"MQTTパブリッシュ",mqttDescription:"Node-RED、Home Assistant、その他の自動化システムとの統合のため、外部MQTTブローカーにBamBuddyイベントをパブリッシュ。",mqttEnableDescription:"外部MQTTブローカーにイベントをパブリッシュ",brokerHostname:"ブローカーホスト名",port:"ポート",usernameOptional:"ユーザー名(オプション)",passwordOptional:"パスワード(オプション)",topicPrefix:"トピックプレフィックス",topicPrefixHint:"トピック形式: {{prefix}}/printers/<serial>/status 等",prometheusMetrics:"Prometheusメトリクス",prometheusEndpointDescription:"Prometheus/Grafanaモニタリング用に<code>/api/v1/metrics</code>でプリンターメトリクスを公開。",bearerTokenOptional:"Bearerトークン(オプション)",bearerTokenHint:"設定時、リクエストに<code>Authorization: Bearer <token></code>が必要",metricsConnectionStatus:"接続状態",metricsPrinterState:"プリンター状態(idle/printing等)",metricsPrintProgress:"印刷進捗 0-100%",metricsBedTemp:"ベッド温度",metricsNozzleTemp:"ノズル温度",metricsPrintsTotal:"結果別の総印刷数",metricsMore:"...その他(レイヤー、ファン、キュー、フィラメント使用量)",smartPlugsDescription:"スマートプラグ(TasmotaまたはHome Assistant)を接続して、電源制御の自動化とプリンターのエネルギー使用量を追跡。",allOn:"すべてオン",allOff:"すべてオフ",addSmartPlug:"スマートプラグを追加",energySummary:"エネルギー概要",currentPower:"現在の消費電力",plugsOnline:"{{reachable}}/{{total}}プラグオンライン",today:"今日",yesterday:"昨日",total:"合計",enablePlugsForSummary:"プラグを有効にしてエネルギー概要を表示",addNotificationProvider:"追加",systemBadge:"(システム)",creating:"作成中...",changing:"変更中...",deleteUserAndItems:"ユーザーとそのアイテムを削除",deleteUserKeepItems:"ユーザーを削除、アイテムは保持(オーナーなしになります)",ok:"OK"},notification:{printStarted:{title:"印刷開始",body:"{{printer}}: {{filename}} の印刷を開始しました"},printCompleted:{title:"印刷完了",body:"{{printer}}: {{filename}} が正常に完了しました"},printFailed:{title:"印刷失敗",body:"{{printer}}: {{filename}} が失敗しました"},printStopped:{title:"印刷中止",body:"{{printer}}: {{filename}} が中止されました"},printProgress:{title:"印刷進捗",body:"{{printer}}: {{filename}} は {{percent}}% 完了"},printerOffline:{title:"プリンターオフライン",body:"{{printer}} がオフラインです"},printerError:{title:"プリンターエラー",body:"{{printer}}: {{error}}"},filamentLow:{title:"フィラメント残量低下",body:"{{printer}}: フィラメントが残りわずかです"},maintenanceDue:{title:"メンテナンス期限",body:"{{printer}}: {{items}} の対応が必要です"}},errors:{generic:"問題が発生しました",networkError:"ネットワークエラーです。接続を確認してください。",notFound:"見つかりません",unauthorized:"認証エラー",serverError:"サーバーエラー",validationError:"入力内容を確認してください",printerConnectionFailed:"プリンターへの接続に失敗しました",saveFailed:"保存に失敗しました",deleteFailed:"削除に失敗しました",loadFailed:"データの読み込みに失敗しました"},hmsErrors:{title:"エラー - {{name}}",noErrors:"エラーなし",viewOnWiki:"Bambu Lab Wikiで表示",clearInstructions:"プリンターでエラーをクリアするとここからも消えます。",clearErrors:"エラーをクリア",clearSuccess:"HMSエラーをクリアしました",clearFailed:"HMSエラーのクリアに失敗しました"},mqttDebug:{title:"MQTTデバッグログ",searchPlaceholder:"トピックまたはペイロードで検索...",noMessages:"まだメッセージが記録されていません",startLoggingHint:"「ログ開始」をクリックしてMQTTメッセージのキャプチャを開始",noMessagesMatch:"フィルターに一致するメッセージがありません",adjustFilterHint:"検索条件やフィルター条件を調整してみてください",incoming:"受信",outgoing:"送信",loggingStopped:"ログ記録停止",loggingActive:"ログ記録中 - メッセージは自動更新されます",startLogging:"ログ記録を開始",stopLogging:"ログ停止",clearLog:"ログをクリア",topic:"トピック",timestamp:"タイムスタンプ",direction:"方向",all:"すべて"},printerFiles:{title:"ファイル管理",storageUsed:"使用中:",storageFree:"空き:",filterPlaceholder:"ファイルを検索...",deleteButton:"削除",deleteFiles:"{{count}}件のファイルを削除",deleteFileConfirm:"このファイルを削除しますか?",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?元に戻せません。",noFiles:"このディレクトリにファイルがありません",loadingFiles:"ファイルを読み込み中...",failedToLoad:"ファイルの読み込みに失敗しました",toast:{filesDeleted:"{{count}}件のファイルを削除しました",deleteFailed:"削除に失敗: {{error}}"}},confirm:{delete:"削除しますか?",unsavedChanges:"保存されていない変更があります。このページを離れますか?",clearQueue:"キューをクリアしますか?"},login:{title:"Bambuddy ログイン",subtitle:"アカウントにサインイン",username:"ユーザー名",usernamePlaceholder:"ユーザー名を入力",usernameOrEmail:"ユーザー名またはメール",usernameOrEmailPlaceholder:"ユーザー名または @ メール",password:"パスワード",passwordPlaceholder:"パスワードを入力",signIn:"サインイン",signingIn:"ログイン中...",forgotPassword:"パスワードをお忘れですか?",loginSuccess:"ログインしました",loginFailed:"ログインに失敗しました",enterCredentials:"ユーザー名とパスワードを入力してください",forgotPasswordTitle:"パスワードを忘れた場合",forgotPasswordMessage:"パスワードを忘れた場合は、システム管理者に連絡してリセットしてもらってください。",forgotPasswordEmailMessage:"メールアドレスを入力すると、新しいパスワードを送信します。",emailAddress:"メールアドレス",emailPlaceholder:"your.email@example.com",cancel:"キャンセル",sending:"送信中...",sendResetEmail:"リセットメールを送信",howToReset:"パスワードのリセット方法:",resetStep1:"Bambuddy管理者に連絡",resetStep2:"ユーザー管理でパスワードリセットを依頼",resetStep3:"管理者が新しい仮パスワードを設定",resetStep4:"新しいパスワードでログインし、設定で変更",gotIt:"了解"},setup:{title:"Bambuddy セットアップ",subtitle:"Bambuddyインスタンスの認証を設定",enableAuth:"認証を有効化",adminAccount:"管理者アカウント",adminAccountDesc:"既に管理者ユーザーが存在する場合、既存の管理者アカウントを使用して認証が有効化されます。既存の管理者を使用する場合は下のフィールドを空のままにするか、新しい認証情報を入力して新しい管理者ユーザーを作成してください。",adminUsername:"管理者ユーザー名",adminPassword:"管理者パスワード",optionalIfAdminExists:"(管理者ユーザーが存在する場合は任意)",adminUsernamePlaceholder:"管理者ユーザー名を入力(任意)",adminPasswordPlaceholder:"管理者パスワードを入力(任意)",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",settingUp:"セットアップ中...",completeSetup:"セットアップを完了",toast:{authEnabledAdminCreated:"認証が有効になり、管理者ユーザーが作成されました",authEnabledExistingAdmins:"既存の管理者ユーザーを使用して認証が有効になりました",setupCompleted:"セットアップが完了しました",enterBothCredentials:"管理者のユーザー名とパスワードの両方を入力するか、既存の管理者を使用する場合は両方を空にしてください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です"}},changePassword:{title:"パスワードを変更",currentPassword:"現在のパスワード",currentPasswordPlaceholder:"現在のパスワードを入力",newPassword:"新しいパスワード",newPasswordPlaceholder:"新しいパスワードを入力(6文字以上)",confirmPassword:"新しいパスワード確認",confirmPasswordPlaceholder:"パスワードを確認",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です",changing:"変更中...",success:"パスワードを変更しました",failed:"パスワードの変更に失敗しました"},plateAlert:{title:"印刷が一時停止されました!",message:"ビルドプレート上にオブジェクトが検出されました。印刷が自動的に一時停止されました。プレートをクリアして印刷を再開してください。",understand:"了解"},camera:{title:"カメラビュー",invalidPrinterId:"無効なプリンターID",live:"ライブ",snapshot:"スナップショット",restartStream:"ストリームを再開",refreshSnapshot:"スナップショットを更新",fullscreen:"フルスクリーン",exitFullscreen:"フルスクリーンを終了",connectingToCamera:"カメラに接続中...",capturingSnapshot:"スナップショットを撮影中...",connectionLost:"接続が切断されました",connectionFailed:"カメラ接続に失敗しました",reconnecting:"{{countdown}}秒後に再接続... (試行 {{attempt}}/{{max}})",reconnectNow:"今すぐ再接続",cameraUnavailable:"カメラが利用できません",cameraUnavailableDesc:"プリンターの電源がオンで接続されていることを確認してください。",noCamera:"カメラがありません",retry:"再試行",cameraStream:"カメラストリーム",zoomOut:"ズームアウト",zoomIn:"ズームイン",resetZoom:"ズームをリセット",recording:"録画中",startRecording:"録画開始",stopRecording:"録画停止",chamberLight:"チャンバーライト切替"},groups:{title:"グループ管理",subtitle:"アクセス制御の権限グループを管理",backToSettings:"設定に戻る",createGroup:"グループを作成",noPermission:"このページにアクセスする権限がありません。",system:"システム",noDescription:"説明なし",usersCount:"{{count}}人のユーザー",permissionsCount:"{{count}}個の権限",edit:"編集",delete:"削除",toast:{created:"グループを作成しました",updated:"グループを更新しました",deleted:"アーカイブを削除しました",enterGroupName:"グループ名を入力"},modal:{editGroup:"グループを編集",createGroup:"グループを作成",cancel:"キャンセル",saving:"保存中...",creating:"作成中...",saveChanges:"変更を保存"},form:{groupName:"グループ名",groupNamePlaceholder:"グループ名を入力",systemGroupWarning:"システムグループ名は変更できません",description:"説明",descriptionPlaceholder:"説明を入力(任意)",permissions:"権限"},deleteModal:{title:"グループを削除",message:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。",confirm:"確認"},editor:{title:"グループを編集",createTitle:"グループを作成",search:"権限を検索...",selectAll:"すべて選択",clearAll:"すべて解除",permissionsSelected:"{{count}}件選択",noResults:"検索に一致する権限がありません"}},users:{title:"ユーザー管理",subtitle:"ユーザーとBambuddyインスタンスへのアクセスを管理",backToSettings:"設定に戻る",createUser:"ユーザーを作成",noPermission:"このページにアクセスする権限がありません。",admin:"管理者",noGroups:"グループなし",active:"アクティブ",inactive:"非アクティブ",edit:"編集",delete:"削除",system:"システム",noGroupsAvailable:"利用可能なグループがありません",table:{username:"ユーザー名",groups:"グループ",status:"ステータス",actions:"アクション"},toast:{created:"ユーザーを作成しました",updated:"ユーザーを更新しました",deleted:"アーカイブを削除しました",fillRequired:"必須項目をすべて入力してください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です"},modal:{createUser:"ユーザーを作成",editUser:"ユーザーを編集",cancel:"キャンセル",creating:"作成中...",saving:"保存中...",saveChanges:"変更を保存",advancedAuthSubtitle:"高度な認証を使用"},form:{username:"ユーザー名",usernamePlaceholder:"ユーザー名を入力",email:"メール",emailPlaceholder:"user@example.com",password:"パスワード",passwordPlaceholder:"パスワードを入力",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",newPasswordPlaceholder:"新しいパスワードを入力",confirmNewPasswordPlaceholder:"新しいパスワードを確認",leaveBlankToKeep:"(現在のパスワードを維持する場合は空白)",groups:"グループ",optional:"オプション",autoGeneratedPassword:"安全なパスワードが自動的に生成され、ユーザーにメールで送信されます。",passwordManagedByAdvancedAuth:"パスワードは高度な認証によって管理されています。「パスワードのリセット」を使用して、メールで新しいパスワードをユーザーに送信してください。",resetPassword:"パスワードのリセット",resettingPassword:"パスワードをリセット中..."},deleteModal:{title:"ユーザーを削除",message:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。",confirm:"ユーザーを削除"}},streamOverlay:{title:"ストリームオーバーレイ",invalidPrinterId:"無効なプリンターID",cameraStream:"カメラストリーム",progress:"進捗",eta:"予想時間 {{minutes}} 分",printerIdle:"プリンター待機中",printerOffline:"プリンターオフライン",status:{printing:"印刷中",paused:"一時停止",finished:"完了",failed:"失敗",idle:"待機中",unknown:"不明"}},profiles:{title:"フィラメントプロファイル",subtitle:"スライサープリセットと圧力キャリブレーションの管理",tabs:{cloud:"クラウドプロファイル",local:"ローカルプロファイル",kprofiles:"Kプロファイル"},localProfiles:{title:"ローカルプロファイル",subtitle:"OrcaSlicerからスライサープリセットをインポート・管理",import:"プロファイルをインポート",importDesc:".bbscfg、.bbsflmt、.orca_filament、.zip、.jsonファイルをここにドロップ",importing:"インポート中...",search:"ローカルプリセットを検索...",noPresets:"ローカルプリセットがまだありません",badge:"ローカル",edit:"編集",delete:"削除",cancel:"キャンセル",deleteConfirmTitle:"プリセットを削除",deleteConfirm:"このプリセットを削除してもよろしいですか?元に戻せません。",source:"ソース",inheritsFrom:"継承元",filamentType:"タイプ",vendor:"メーカー",compatiblePrinters:"プリンター",nozzleTemp:"ノズル温度",cost:"コスト",density:"密度",pressureAdvance:"プレッシャーアドバンス",filament:"フィラメント",process:"プロセス",printer:"プリンター",toast:{importSuccess:"{{count}}件のプリセットをインポートしました",importSkipped:"{{count}}件のプリセットをスキップしました(重複)",importError:"インポート中に{{count}}件のエラーが発生しました",deleted:"プリセットを削除しました",updated:"プリセットを更新しました"}},connectedAs:"接続中:",logout:"ログアウト",noLogoutPermission:"ログアウトする権限がありません",failedToLoad:"ファイルの読み込みに失敗しました",retry:"リトライ",time:{justNow:"たった今",minsAgo:"{{count}}分前",hoursAgo:"{{count}}時間前",daysAgo:"{{count}}日前"},toast:{loggedOut:"ログアウトしました"},login:{title:"Bambuddy ログイン",subtitle:"アカウントにサインイン",email:"メールアドレス",password:"パスワード",region:"リージョン",regionGlobal:"グローバル",regionChina:"中国",verificationCode:"認証コード",totpCode:"認証アプリコード",checkEmail:"メール ({{email}}) に届いた6桁のコードを入力してください",enterTotpHint:"認証アプリの6桁のコードを入力してください",accessToken:"アクセストークン",accessTokenHint:"Bambu Labのアクセストークンを貼り付け(Bambu Studioから取得)",back:"戻る",loginButton:"ログイン",verifyButton:"認証",setTokenButton:"トークンを設定",useToken:"アクセストークンを使用",useEmail:"メールでログイン",toast:{loggedIn:"ログインしました",codeSent:"メールに認証コードを送信しました",enterTotp:"認証アプリのコードを入力してください",tokenSet:"トークンを設定しました"}},presets:{myPreset:"マイプリセット(編集可能)",duplicate:"複製",editable:"編集可能",failedToLoadDetails:"プリセットの詳細を読み込めませんでした",deleteConfirm:"このプロファイルを削除しますか?",deleteWarning:"「{{name}}」をBambu Cloudから完全に削除します。元に戻せません。",noDuplicatePermission:"プリセットを複製する権限がありません",noEditPermission:"プリセットを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",types:{filament:"フィラメント",printer:"プリンター",process:"プロセス"},toast:{deleted:"アーカイブを削除しました",created:"プリセットを作成しました",updated:"プリセットを更新しました",duplicated:"プリセットを複製しました",fieldAdded:'フィールド "{{key}}" を追加しました',exported:"プリセットをエクスポートしました"},baseLabel:"ベース: {{name}}",currentLabel:"現在: {{name}}",newPreset:"新規プリセット",editPreset:"プリセットを編集",duplicatePreset:"プリセットを複製",createNewPreset:"新しいプリセットを作成",customizeSettings:"新しいプリセットの設定をカスタマイズ",compareWithBase:"ベースプリセットと比較",compare:"比較",basePreset:"ベースプリセット",selectBasePreset:"ベースプリセットを選択...",presetName:"プリセット名",myCustomPreset:"カスタムプリセット",inheritsFrom:"継承元:",dropJsonToImport:"JSONファイルをドロップしてインポート",tabs:{common:"一般",allFields:"すべてのフィールド"},availableFields:"利用可能なフィールド",searchFieldsPlaceholder:"フィールドを検索...",noMatchingFields:"一致するフィールドがありません",allFieldsAdded:"すべてのフィールドが追加済みです",addCustomField:"カスタムフィールドを追加",yourOverrides:"オーバーライド一覧",noOverridesYet:"オーバーライドはまだありません",clickFieldsToAdd:"左のフィールドをクリックして追加",saveAsTemplate:"テンプレートとして保存",jsonTip:"ヒント: .jsonファイルをこのモーダルにドラッグ&ドロップして設定をインポート"},cloudView:{searchPlaceholder:"プリセットを検索...",templates:"テンプレート",refresh:"更新",newPreset:"新規プリセット",clearFilters:"フィルターをクリア",compareMode:"比較モード",selectAnotherPreset:"同じタイプ({{type}})の別のプリセットを選択",clickTwoPresets:"同じタイプのプリセットを2つクリックして比較",selectFirst:"1. 最初を選択",selectSecond:"2. 2番目を選択",compareNow:"比較を実行",lastSynced:"最終同期:",showingCount:"{{total}}件中{{shown}}件を表示",noPresetsFound:"プリセットが見つかりません",columns:{filament:"フィラメント",process:"プロセス",printer:"プリンター"},noFilamentPresets:"フィラメントプリセットなし",noProcessPresets:"プロセスプリセットなし",noPrinterPresets:"プリンタープリセットなし",filters:{type:"種類",owner:"所有者",printer:"プリンター",nozzle:"ノズル",filament:"フィラメント",layer:"レイヤー",all:"すべて",myPresets:"マイプリセット",builtIn:"ビルトイン",process:"プロセス"},noTemplatesPermission:"テンプレートを管理する権限がありません",noRefreshPermission:"プロファイルを更新する権限がありません",noCreatePermission:"プロジェクトを作成する権限がありません"},templates:{title:"フィラメントプロファイル",noTemplates:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを作成してください。",createFirst:"プリセットエディタからテンプレートを作成",typeFilter:"タイプ:",deleteTitle:"テンプレートを削除",deleteWarning:"この操作は元に戻せません",deleteConfirm:"このプロファイルを削除しますか?",namePlaceholder:"テンプレート名",descriptionPlaceholder:"説明",settingsJson:"設定 (JSON)",fieldsCount:"{{count}}フィールド",shownInModals:"モーダルに表示",hiddenInModals:"モーダルで非表示",apply:"適用",toast:{deleted:"アーカイブを削除しました",updated:"テンプレートを更新しました",created:"テンプレートを作成しました",applied:"テンプレートを適用しました"}}},support:{debugLoggingActive:"デバッグログが有効です",manageLogs:"管理",collectItem7:"プリンター接続状態とファームウェアバージョン",collectItem8:"連携状態(Spoolman、MQTT、HA)",collectItem9:"ネットワークインターフェース(サブネットのみ)",collectItem10:"Pythonパッケージバージョン",collectItem11:"データベース健全性チェック",collectItem12:"Docker環境の詳細"},fileManager:{title:"ファイル管理",subtitle:"印刷ファイルの整理と管理",uploadFiles:"ファイルをアップロード",newFolder:"新しいフォルダ",folderName:"フォルダ名",folderNamePlaceholder:"例: 機能パーツ",renameFile:"ファイル名を変更",renameFolder:"フォルダ名を変更",moveFiles:"{{count}}件のファイルを移動",rootNoFolder:"ルート(フォルダなし)",current:"(現在)",linkFolder:"フォルダをリンク",linkFolderDescription:"「{{name}}」をプロジェクトまたはアーカイブにリンクしてすばやくアクセス。",project:"プロジェクト",archive:"アーカイブ",noProjectsFound:"プロジェクトが見つかりません",noArchivesFound:"アーカイブが見つかりません",unlink:"リンク解除",link:"リンク",dragDropFiles:"ファイルをここにドラッグ&ドロップ",dropFilesHere:"ここにファイルをドロップ",orClickToBrowse:"またはクリックして選択",allFileTypesSupported:"すべてのファイルタイプに対応。ZIPファイルは展開されます。",zipFilesDetected:"ZIPファイルを検出",zipExtractOptions:"ZIPファイルは展開されます。フォルダー構造の処理方法を選択:",preserveZipStructure:"ZIPのフォルダ構造を保持",createFolderFromZip:"ZIPファイル名からフォルダーを作成",stlThumbnailGeneration:"STLサムネイル生成",zipMayContainStl:"ZIPファイルにSTLファイルが含まれている場合があります。展開時にサムネイルを生成できます。",thumbnailsCanBeGenerated:"STLファイルのサムネイルを生成できます。大きなモデルは処理に時間がかかる場合があります。",generateThumbnailsForStl:"STLファイルのサムネイルを生成",threemfDetected:"3MFファイルを検出",threemfExtractionInfo:"プリンターモデル、素材、色、印刷設定は3MFファイルから自動的に抽出されます。",willBeExtracted:"• 展開予定",filesExtracted:"• {{count}}個のファイルを展開済み",uploadComplete:"アップロード完了: {{count}}個成功",uploadFailed:"アップロード失敗",zipFilesFailed:"{{count}}個のファイルが失敗",uploading:"アップロード中...",changeLink:"リンクを変更...",linkTo:"リンク先...",linkToProjectOrArchive:"プロジェクトまたはアーカイブにリンク",addToQueue:"キューに追加",schedulePrint:"印刷をスケジュール",generateThumbnail:"サムネイルを生成",generateThumbnails:"サムネイルを生成",generateThumbnailsForMissing:"サムネイルのないSTLファイルのサムネイルを生成",gridView:"グリッド表示",listView:"リスト表示",lowDiskSpaceWarning:"ディスク容量不足の警告",lowDiskSpaceDetails:"{{total}}中{{free}}の空き容量のみ。しきい値は設定で{{threshold}}GBに設定されています。",files:"ファイル",folders:"フォルダ",size:"サイズ",free:"空き:",allFiles:"すべてのファイル",wrap:"折り返し",enableTextWrapping:"テキスト折り返しを有効化",disableTextWrapping:"テキスト折り返しを無効化",dragToResizeTooltip:"ドラッグしてリサイズ、ダブルクリックでリセット",searchFiles:"ファイルを検索...",allTypes:"すべての種類",prints:"印刷回数",ascending:"昇順",descending:"降順",resultsCount:"{{total}}件中{{showing}}件",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",adding:"追加中...",loadingFiles:"ファイルを読み込み中...",folderIsEmpty:"フォルダーは空です",noFilesYet:"ファイルはまだありません",folderEmptyDescription:"ファイルをアップロードするか、このフォルダーにファイルを移動して開始しましょう。",noFilesDescription:"印刷関連ファイルの整理を始めるにはファイルをアップロードしてください。",noMatchingFiles:"一致するファイルがありません",noMatchingFilesDescription:"現在の検索またはフィルター条件に一致するファイルがありません。",clearFilters:"フィルターをクリア",printedCount:"{{count}}回印刷済み",uploadedBy:"アップロード者",deleteFolder:"フォルダを削除",deleteFile:"ファイルを削除",deleteFilesCount:"{{count}}件のファイルを削除",deleteFolderConfirm:"このフォルダを削除しますか?中のファイルもすべて削除されます。",deleteFileConfirm:"このファイルを削除しますか?",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?この操作は元に戻せません。",deleting:"削除中...",noPermissionRenameFolder:"フォルダー名を変更する権限がありません",noPermissionLinkFolder:"フォルダーをリンクする権限がありません",noPermissionDeleteFolder:"フォルダーを削除する権限がありません",noPermissionPrint:"印刷する権限がありません",noPermissionAddToQueue:"キューに追加する権限がありません",noPermissionDownload:"ファイルをダウンロードする権限がありません",noPermissionRenameFile:"このファイル名を変更する権限がありません",noPermissionGenerateThumbnail:"サムネイルを生成する権限がありません",noPermissionDeleteFile:"このファイルを削除する権限がありません",noPermissionCreateFolder:"フォルダーを作成する権限がありません",noPermissionUpload:"ファイルをアップロードする権限がありません",noPermissionMoveFiles:"ファイルを移動する権限がありません",noPermissionDeleteFiles:"ファイルを削除する権限がありません",linkExternal:"外部リンク",linkExternalFolder:"外部フォルダをリンク",linkExternalFolderDescription:"ホストディレクトリ(NAS、USB、ネットワーク共有)をファイルマネージャにマウントします。ファイルはコピーされず、元のパスから直接アクセスされます。",externalFolderNamePlaceholder:"例:NASプリント",externalPath:"ホストパス",externalPathHelp:"Dockerホスト上のディレクトリの絶対パス。コンテナにバインドマウントされている必要があります。",readOnly:"読み取り専用",readOnlyHelp:"アップロードと削除を防止",showHiddenFiles:"隠しファイルを表示(ドットファイル)",externalFolder:"外部フォルダ",scanFolder:"スキャン",toast:{folderCreated:"フォルダを作成しました",folderDeleted:"フォルダを削除しました",fileDeleted:"ファイルを削除しました",filesDeleted:"{{count}}件のファイルを削除しました",filesMoved:"ファイルを移動しました",folderLinked:"フォルダをリンクしました",folderUnlinked:"フォルダのリンクを解除しました",externalFolderLinked:"外部フォルダがリンクされスキャンされました",folderScanned:"スキャン完了:{{added}}件追加、{{removed}}件削除",addedToQueue:"{{count}}個のファイルをキューに追加しました",addedToQueuePartial:"{{added}}件追加、{{failed}}件失敗",failedToAddToQueue:"ファイルの追加に失敗: {{error}}",fileRenamed:"ファイル名を変更しました",folderRenamed:"フォルダ名を変更しました",thumbnailsGenerated:"{{count}}件のサムネイルを生成しました",thumbnailsGeneratedPartial:"{{succeeded}}件生成、{{failed}}件失敗",noStlMissingThumbnails:"サムネイルのないSTLファイルはありません",failedToGenerateThumbnails:"サムネイルの生成に失敗: {{error}}",thumbnailGenerated:"サムネイルを生成しました",failedToGenerateThumbnail:"サムネイルの生成に失敗: {{error}}"}},projects:{title:"プロジェクト",subtitle:"印刷プロジェクトを管理",newProject:"新規プロジェクト",editProject:"プロジェクトを編集",deleteProject:"プロジェクトを削除",projectName:"プロジェクト: {{name}}",description:"説明",noProjects:"プロジェクトはまだありません",noProjectsFiltered:"{{status}}のプロジェクトはありません",noProjectsFilteredHelp:"{{status}}のプロジェクトがありません。ステータスが変更されるとここに表示されます。",createFirst:"最初のプロジェクトを作成して、関連する印刷の整理、進捗管理、ビルドの管理を始めましょう。",createFirstButton:"最初のプロジェクトを作成",create:"作成",files:"ファイル",prints:"印刷",plates:"プレート",parts:"パーツ",lastModified:"最終更新日",deleteConfirm:"このプロジェクトを削除しますか?アーカイブとキューアイテムはリンク解除されますが、削除されません。",addFiles:"ファイルを追加",removeFile:"ファイルを削除",viewDetails:"詳細を表示",namePlaceholder:"プロジェクト名",descriptionPlaceholder:"プロジェクトの説明(任意)",color:"色",targetPlates:"目標プレート数",targetPlatesPlaceholder:"例: 10",targetPlatesHelp:"印刷ジョブの数",targetParts:"目標パーツ数",targetPartsPlaceholder:"例: 50",targetPartsHelp:"必要なオブジェクトの総数",tagsLabel:"タグ(カンマ区切り)",tagsPlaceholder:"カンマ区切りのタグ",dueDate:"期限",priority:"優先度",priorityLow:"低",priorityNormal:"通常",priorityHigh:"高",priorityUrgent:"緊急",statusActive:"進行中",statusCompleted:"完了",statusArchived:"アーカイブ済み",done:"完了",completed:"完了",failed:"失敗",inQueue:"キュー内",noPrintsYet:"印刷履歴なし",printJobs:"印刷ジョブ",partsPrinted:"印刷済みパーツ",failedParts:"失敗パーツ",import:"インポート",export:"エクスポート",importProject:"プロジェクトをインポート",exportAll:"すべてのプロジェクトをエクスポート",loading:"プロジェクトを読み込み中...",noEditPermission:"プロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",noCreatePermission:"プロジェクトを作成する権限がありません",noImportPermission:"プロジェクトをインポートする権限がありません",noExportPermission:"プロジェクトをエクスポートする権限がありません",toast:{created:"プロジェクトを作成しました",updated:"プロジェクトを更新しました",deleted:"アーカイブを削除しました",imported:"プロジェクトをインポートしました",multipleImported:"{{count}}件のプロジェクトをインポートしました",importFailed:"インポートに失敗しました",exported:"プロジェクトをエクスポートしました(メタデータのみ)"}},projectDetail:{notFound:"見つかりません",backToProjects:"プロジェクト一覧に戻る",export:"エクスポート",exportProject:"プロジェクトをエクスポート",noExportPermission:"プロジェクトをエクスポートする権限がありません",noEditPermission:"このプロジェクトを編集する権限がありません",partOf:"所属先",priorityLabel:"優先度",noPrints:"このプロジェクトにはまだ印刷がありません",status:{active:"進行中",completed:"完了",archived:"アーカイブ済み"},priority:{low:"低",normal:"通常",high:"高",urgent:"緊急"},dueDate:{overdue:"期限超過",today:"今日が期限",daysLeft:"残り{{count}}日"},progress:{platesProgress:"プレート進捗",partsProgress:"パーツ進捗",printJobs:"印刷ジョブ",parts:"パーツ",percentComplete:"% 完了",remaining:"残り"},stats:{printJobs:"印刷ジョブ",total:"合計",failed:"失敗",partsPrinted:"印刷済みパーツ",printTime:"印刷時間",filamentUsed:"フィラメント使用量"},cost:{title:"コスト追跡",filamentCost:"フィラメント",energy:"エネルギー",totalCost:"合計コスト",total:"合計",includesBom:"BOM含む",budget:"予算",remaining:"残り"},subProjects:{title:"サブプロジェクト ({{count}})"},notes:{title:"メモ",noEditPermission:"このプロジェクトを編集する権限がありません",placeholder:"このプロジェクトについてメモを追加...",empty:"<空>"},files:{title:"ファイル",linkFolders:"ファイルマネージャーからフォルダーをリンク",forQuickAccess:"してクイックアクセスできるようにします。",fileCount:"{{count}}ファイル",empty:"<空>"},bom:{title:"部品表",acquired:"{{completed}}/{{total}} 取得済み",showAll:"すべて表示",hideDone:"完了を非表示",addPart:"パーツを追加",noAddPermission:"パーツを追加する権限がありません",partNamePlaceholder:"パーツ名",partName:"パーツ名",qty:"数量",price:"価格 ({{currency}})",sourcingUrlPlaceholder:"URL(任意)",remarksPlaceholder:"備考",deletePart:"パーツを削除",deleteConfirm:"「{{name}}」を削除しますか?",noUpdatePermission:"パーツを更新する権限がありません",noEditPermission:"このプロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",totalCost:"合計コスト",empty:"<空>"},timeline:{title:"アクティビティタイムライン",empty:"<空>"},template:{saveAsTemplate:"テンプレートとして保存",noCreatePermission:"プロジェクトを作成する権限がありません"},queue:{title:"印刷キュー",viewAll:"すべて表示",printing:"印刷中",queued:"キューに追加"},prints:{title:"印刷 ({{count}})"},toast:{projectUpdated:"プロジェクトを更新しました",partAdded:"パーツを追加しました",partRemoved:"パーツを削除しました",exportFailed:"エクスポートに失敗しました",projectExported:"プロジェクトがエクスポートされました",templateCreated:"プロジェクトからテンプレートを作成しました"}},system:{title:"システム情報",version:"バージョン",uptime:"稼働時間",cpuUsage:"CPU使用率",memoryUsage:"メモリ使用量",diskUsage:"ディスク使用量",networkInfo:"ネットワーク情報",logs:"ログ",debugMode:"デバッグモード",enableDebug:"デバッグログを有効化",disableDebug:"デバッグログを無効化",downloadLogs:"ログをダウンロード",clearLogs:"通知ログを削除",dockerInfo:"Docker情報",containerName:"コンテナ名",imageName:"イメージ名",platform:"プラットフォーム",architecture:"アーキテクチャ"},library:{title:"フィラメントライブラリ",addFilament:"フィラメントを追加",editFilament:"フィラメントを編集",deleteFilament:"フィラメントを削除",vendor:"メーカー",material:"素材",color:"色",kFactor:"K値",temperature:"温度",noFilaments:"ライブラリにフィラメントがありません",deleteConfirm:"このフィラメントを削除しますか?",importFromPrinter:"プリンターからインポート",exportToFile:"ファイルにエクスポート"},spoolman:{title:"Spoolman連携",enabled:"Spoolman有効",url:"Spoolman URL",connected:"接続中",disconnected:"未接続",testConnection:"接続テスト",sync:"同期",syncing:"同期中...",lastSync:"最終同期",linkToSpoolman:"Spoolmanに連携",openInSpoolman:"Spoolmanで開く",unlinkSpool:"スプールのリンクを解除",unlinkConfirmTitle:"スプールのリンクを解除しますか?",unlinkConfirmMessage:"これにより、スプールがSpoolmanから切断されます。Spoolman内のスプールデータは変更されません。",selectSpool:"スプールを選択",noUnlinkedSpools:"Spoolmanに未連携のスプールが見つかりません。",linkSuccess:"スプールをSpoolmanにリンクしました",linkFailed:"スプールのリンクに失敗しました",unlinkSuccess:"スプールをSpoolmanから解除しました",unlinkFailed:"スプールのリンク解除に失敗しました",spoolId:"スプールID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"残り",disableWeightSync:"AMS推定重量同期を無効化",disableWeightSyncDesc:"AMS推定値から残量を更新しません。AMSの割合ベースの推定よりもSpoolmanの使用量追跡を優先する場合に使用してください。新しいスプールは引き続きAMS推定値を初期重量として使用します。",reportPartialUsage:"失敗した印刷の部分使用量を報告",reportPartialUsageDesc:"印刷が失敗またはキャンセルされた場合、レイヤー進捗に基づいてその時点までの推定フィラメント使用量を報告します。"},inventory:{title:"スプール在庫管理",addSpool:"スプールを追加",editSpool:"スプールを編集",material:"素材",selectMaterial:"素材を選択...",subtype:"サブタイプ",brand:"ブランド",searchBrand:"ブランドを検索...",useCustomBrand:"「{{brand}}」を使用",useCustomMaterial:"カスタム素材を使用: {{material}}",colorName:"色名",colorNamePlaceholder:"Jade White, Fire Red...",color:"色",hexColor:"HEXカラー",pickColor:"カスタムカラーを選択",labelWeight:"表示重量",coreWeight:"空スプール重量",searchSpoolWeight:"スプール重量を検索...",weightUsed:"使用量",currentWeight:"残量",measuredWeight:"計測重量",spoolName:"スプール",costPerKg:"kgあたりのコスト",measuredWeightError:"計測重量は{{min}}gから{{max}}gの間で入力してください。",slicerFilament:"スライサーフィラメント",slicerFilamentName:"スライサープリセット名",slicerPreset:"スライサープリセット",searchPresets:"フィラメントプリセットを検索...",selectedPreset:"選択済み",noPresetsFound:"プリセットが見つかりません",tempOverrides:"温度オーバーライド",note:"メモ",notePlaceholder:"このスプールに関する追加メモ...",archive:"アーカイブ",restore:"復元",noSpools:"スプールがありません。最初のスプールを追加してください。",noManualSpools:"手動で追加されたスプールがありません。先にインベントリにスプールを追加してください。",kProfiles:"Kプロファイル",addKProfile:"Kプロファイルを追加",assignSpool:"スプールを割り当て",unassignSpool:"割り当て解除",assignSuccess:"スプールを割り当て、AMSスロットを設定しました",assignFailed:"スプールの割り当てに失敗しました",selectSpool:"このスロットに割り当てるスプールを選択",assigned:"割り当て済み",assigning:"割り当て中...",searchSpools:"スプールを検索...",showAllSpools:"すべてのスプールを表示",allMaterials:"すべての素材",filterByBrand:"ブランドで絞り込み...",showArchived:"アーカイブ済みを表示",quickAdd:"クイック追加(在庫)",quantity:"数量",stock:"在庫",configured:"設定済み",spoolsCreated:"{{count}}本のスプールを作成しました",spoolCreated:"スプールを作成しました",spoolUpdated:"スプールを更新しました",spoolDeleted:"スプールを削除しました",spoolArchived:"スプールをアーカイブしました",spoolRestored:"スプールを復元しました",deleteConfirm:"このスプールを削除しますか?この操作は元に戻せません。",archiveConfirm:"このスプールをアーカイブしますか?",advancedSettings:"詳細設定",filamentInfoTab:"フィラメント情報",paProfileTab:"PAプロファイル",filamentInfo:"フィラメント",additional:"追加情報",loadingPresets:"クラウドプリセットを読み込み中...",cloudConnected:"クラウド接続済み",cloudNotConnected:"クラウド未接続(デフォルト使用)",recentColors:"最近",searchColors:"色を検索...",searchResults:"検索結果",allColors:"すべての色",commonColors:"一般的な色",showLess:"少なく表示",showAll:"すべて表示",noColorsFound:"一致する色がありません",noResults:"結果なし",selectMaterialFirst:"フィラメント情報タブで素材を選択してください。",noPrintersConfigured:"プリンターが設定されていません。プリンターを追加してください。",matchingFilter:"フィルター",anyBrand:"すべてのブランド",anyVariant:"すべてのバリアント",autoSelect:"自動選択",matches:"件一致",match:"件一致",noMatches:"一致なし",connected:"接続済み",offline:"オフライン",printerOffline:"プリンターがオフラインです。接続してキャリブレーションプロファイルを表示してください。",noKProfilesMatch:"選択したフィラメントに一致するKプロファイルがありません。",leftNozzle:"左ノズル",rightNozzle:"右ノズル",profilesSelected:"キャリブレーションプロファイル選択済み",totalInventory:"在庫合計",totalConsumed:"総消費量",byMaterial:"素材別",inPrinter:"プリンター内",lowStock:"残量少",sinceTracking:"追跡開始以降",loadedInAms:"AMS/Extに装填中",remaining:"残り",weightCheck:"重量チェック",lastWeighed:"最終計量",neverWeighed:"未計量",search:"スプールを検索...",showing:"表示",to:"〜",of:"/",show:"表示",spools:"スプール",spool:"スプール",page:"ページ",noSpoolsMatch:"結果なし",noSpoolsMatchDesc:"検索やフィルターを調整してみてください。",active:"アクティブ",archived:"アーカイブ済み",all:"すべて",used:"使用済み",new:"新規",clearFilters:"フィルターをクリア",table:"テーブル",cards:"カード",net:"正味",groupSimilar:"グループ化",groupedSpools:"{{count}}本の同一スプール",groupedRows:"行",columns:"列",configureColumns:"列の設定",configureColumnsDesc:"ドラッグして並べ替えるか、矢印を使用してください。目のアイコンで表示/非表示を切り替えます。",visible:"表示中",reset:"リセット",cancel:"キャンセル",applyChanges:"変更を適用",moveUp:"上へ移動",moveDown:"下へ移動",hideColumn:"列を非表示",showColumn:"列を表示",linkToSpool:"スプールにリンク",tagLinked:"タグがスプールにリンクされました",tagLinkFailed:"タグのリンクに失敗しました",tagAlreadyLinked:"タグは既に別のスプールにリンクされています",unknownTag:"不明なRFIDタグが検出されました",usageHistory:"使用履歴",noUsageHistory:"まだ使用記録がありません",printName:"プリント名",weightConsumed:"消費重量",clearHistory:"クリア",historyCleared:"使用履歴がクリアされました",fillSourceLabel:"(Inv)",lowStockThresholdError:"しきい値は0.1から99.9の間でなければなりません",assignMismatchTitle:"材料の不一致",assignMismatchMessage:"選択したスプールの材料「{{spoolMaterial}}」は、{{location}} のトレイ材料「{{trayMaterial}}」と一致しません。割り当てますか?",assignMismatchConfirm:"強制的に割り当て",assignPartialMismatchMessage:"スプールの材料「{{spoolMaterial}}」は「{{trayMaterial}}」に似ていますが、{{location}} と完全には一致しません。続行しますか?",assignProfileMismatchMessage:"スプールのプロファイル「{{spoolProfile}}」は {{location}} のトレイプロファイル「{{trayProfile}}」と一致しません。続行しますか?"},timelapse:{title:"タイムラプス",create:"タイムラプスを作成",download:"ダウンロード",delete:"削除",preview:"プレビュー",frameRate:"フレームレート",quality:"品質",processing:"バックアップファイルを処理中...",noTimelapses:"利用可能なタイムラプスがありません"},ams:{title:"AMS",slot:"スロット",empty:"<空>",emptySlot:"空のスロット",unknown:"不明",humidity:"湿度",temperature:"温度",filamentType:"フィラメントタイプ",filamentColor:"色",remaining:"残り",history:"AMS履歴",noHistory:"メンテナンス履歴がありません",configureSlot:"フィラメントプロファイルとK値でスロットを設定",externalSpool:"外部スプール",profile:"プロファイル",kFactor:"K値",fill:"充填率",configure:"設定",used:"使用済み",remainingUnit:"残り"},printModal:{title:"印刷を開始",selectPrinter:"プリンターを選択",selectPlate:"プレートを選択",filamentMapping:"フィラメントマッピング",totalCost:"合計コスト:",slotRemainingShort:" - 残{{grams}}g",printSettings:"印刷設定",bedLeveling:"ベッドレベリング",flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",layerInspection:"第一層検査",timelapse:"タイムラプス",startPrint:"印刷を開始",addToQueue:"キューに追加",cancel:"キャンセル",noPrintersAvailable:"利用可能なプリンターがありません",printerBusy:"プリンターは使用中です",printerOffline:"プリンターはオフラインです",sameTypeDifferentColor:"同じ種類、異なる色",filamentTypeNotLoaded:"フィラメントタイプが未読み込み",openCalendar:"カレンダーを開く",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"左ノズル",rightNozzleTooltip:"右ノズル",filamentOverride:"フィラメントオーバーライド",filamentOverrideHint:"モデルベースの割り当てに使用するフィラメントをオプションで上書きします。スケジューラは元の3MF値ではなく、選択したフィラメントに基づいてマッチングします。",originalFilament:"オリジナル",overrideWith:"変更先",resetToOriginal:"オリジナルに戻す",insufficientFilamentTitle:"フィラメントが不足しています",insufficientFilamentMessage:"割り当てられたスプールの一部は、この印刷に必要な量より残量が少ないです:",insufficientFilamentLine:"{{printer}} - {{slot}}: 必要 {{required}}g、残り {{remaining}}g",printAnyway:"それでも印刷",forceColorMatch:"カラーマッチを強制",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"{{count}}台のプリンターに段階的に送信",gcodeInjection:"自動印刷G-codeを挿入"},backup:{title:"バックアップと復元",createBackup:"バックアップを作成",restoreBackup:"バックアップの復元",restoreDescription:"バックアップファイルからすべてのデータを置き換える",downloadBackup:"バックアップをダウンロード",uploadBackup:"バックアップをアップロード",lastBackup:"最終バックアップ",autoBackup:"自動バックアップ",backupNow:"今すぐバックアップ",restoreWarning:"警告: バックアップの復元は現在のすべてのデータを上書きします。",includeArchives:"アーカイブを含む",includeSettings:"設定を含む",includeProfiles:"プロファイルを含む",backupSuccess:"バックアップを作成しました",restoreSuccess:"バックアップを復元しました",backupFailed:"バックアップに失敗しました: {{error}}",restoreFailed:"復元に失敗しました",restoreNote:"復元中、仮想プリンターは停止されます",githubBackup:"GitHubバックアップ",enabled:"有効",cloudLoginRequired:"Bambu Cloudログインが必要です。GitHubバックアップを有効にするには、プロファイル → クラウドプロファイルからサインインしてください。",cloudLoginRequiredShort:"Cloudログインが必要",githubDescription:"プロファイルをプライベートGitHubリポジトリに自動的に同期し、バックアップとバージョン履歴を保持します。",repositoryUrl:"リポジトリURL",personalAccessToken:"個人アクセストークン",tokenSaved:"(保存済み)",enterNewToken:"新しいトークンを入力して更新",tokenHint:"Contents読み書き権限を持つきめ細かいトークン",branch:"ブランチ",manualOnly:"手動のみ",hourly:"毎時",daily:"毎日",weekly:"毎週",includeInBackup:"バックアップに含める",kProfiles:"Kプロファイル",kProfilesDescription:"接続されたプリンターからの圧力キャリブレーション",noPrintersConnected:"プリンターが接続されていません",printersConnected:"{{connected}}/{{total}} 接続済み",cloudProfiles:"クラウドプロファイル",cloudProfilesDescription:"Bambu Cloudからのフィラメント、プリンター、プロセスプリセット",appSettings:"アプリ設定",appSettingsDescription:"Bambuddy設定(データベース全体)",spoolInventory:"スプール在庫",spoolInventoryDescription:"フィラメントスプール、使用履歴、コスト追跡",printArchives:"印刷アーカイブ",printArchivesDescription:"印刷履歴メタデータ(gcode/3MFファイルなし)",lastBackupAt:"最終バックアップ:",noBackupsYet:"バックアップはまだありません",next:"次回:",startingBackup:"バックアップを開始しています...",test:"テスト",enableBackup:"バックアップを有効化",testConnection:"接続テスト",enterRepoUrl:"リポジトリURLを入力してください",enterRepoAndToken:"リポジトリURLとアクセストークンを入力してください",repoRequired:"リポジトリURLは必須です",tokenRequired:"アクセストークンは必須です",githubBackupEnabled:"GitHubバックアップが有効になりました",tokenUpdated:"トークンが更新されました",settingsSaved:"設定が保存されました",failedToSave:"保存に失敗しました: {{message}}",backupCompleteFiles:"バックアップ完了 - {{count}}ファイルが更新されました",backupSkippedNoChanges:"バックアップをスキップ - 変更なし",backupFailed2:"バックアップに失敗しました: {{message}}",clearedLogs:"{{count}}件のログを削除しました",failedToClearLogs:"ログの削除に失敗しました: {{message}}",history:"履歴",clear:"クリア",date:"日付",status:"ステータス",commit:"コミット",localBackup:"ローカルバックアップ",localBackupDescription:"データベース、アーカイブ、アップロード、すべてのファイルを含むBambuddyデータの完全なバックアップを作成します。",downloadBackupLabel:"バックアップをダウンロード",completeBackupZip:"完全バックアップ: データベース + 全ファイル (ZIP)",download:"ダウンロード",preparingBackup:"バックアップを準備しています...",creatingArchive:"バックアップアーカイブを作成しています...大きなアーカイブの場合、時間がかかることがあります。",downloadingFile:"バックアップファイルをダウンロードしています...",backupDownloaded:"バックアップのダウンロードが成功しました",failedToCreateBackup:"バックアップの作成に失敗しました: {{message}}",restore:"復元",restoreReplacesAll:"復元はすべてのデータを置き換えます。",restoreReplacesAllDetail:"現在のデータベースとファイルは完全に置き換えられます。復元後に再起動が必要です。",restoreConfirmTitle:"バックアップを復元",restoreConfirmMessage:'"{{filename}}"から復元してもよろしいですか?現在のデータベースとすべてのファイルが完全に置き換えられます。復元後にアプリケーションの再起動が必要です。',restoreConfirmButton:"バックアップを復元",uploadingFile:"バックアップファイルをアップロードしています...",backupRestoredRestart:"バックアップが復元されました。Bambuddyを再起動してください。",failedToRestore:"バックアップの復元に失敗しました。ファイル形式を確認してください。",reloadNow:"今すぐリロード",creatingBackup:"バックアップを作成中",restoringBackup:"バックアップを復元中",preparing:"準備中...",processing:"処理中...",doNotClosePage:"このページを閉じたり、移動しないでください。大きなバックアップの場合、この操作には数分かかることがあります。",restoring:"復元中...",restoreComplete:"復元完了",restoreFailed2:"復元失敗",importSettings:"バックアップファイルから設定をインポート",pleaseWaitRestoring:"データの復元中です。お待ちください",selectBackupFile:"クリックしてバックアップファイルを選択 (.jsonまたは.zip)",duplicateHandling:"重複処理の仕組み:",matchPrinters:"プリンター",matchPrintersBy:"シリアル番号で照合",matchSmartPlugs:"スマートプラグ",matchSmartPlugsBy:"IPアドレスで照合",matchNotificationProviders:"通知プロバイダー",matchNotificationProvidersBy:"名前で照合",matchFilaments:"フィラメント",matchFilamentsBy:"名前 + タイプ + ブランドで照合",matchArchives:"アーカイブ",matchArchivesBy:"コンテンツハッシュで照合(常にスキップ)",matchPendingUploads:"保留中のアップロード",matchPendingUploadsBy:"ファイル名で照合",matchSettingsTemplates:"設定とテンプレート",matchSettingsTemplatesBy:"常に上書き",replaceExisting:"既存のデータを置き換え",keepExisting:"既存のデータを保持",overwriteDescription:"既に存在する項目をバックアップデータで上書き",keepDescription:"まだ存在しない項目のみ復元",overwriteCaution:"注意:",overwriteWarning:"上書きすると、現在の設定がバックアップのデータで置き換えられます。プリンターのアクセスコードはセキュリティのため上書きされません。",cancel:"キャンセル",processingBackup:"バックアップファイルを処理しています...",itemsRestored:"復元済み",itemsSkipped:"スキップ済み",restored:"復元済み",skippedAlreadyExist:"スキップ(既に存在)",filesCategory:"ファイル(3MF、サムネイルなど)",andMore:"...他{{count}}件",newApiKeysGenerated:"新しいAPIキーが生成されました",keysShownOnce:"これらのキーは一度だけ表示されます。今すぐコピーしてください!",copy:"コピー",noDataFound:"バックアップファイルに復元するデータが見つかりませんでした。",close:"閉じる",categories:{settings:"設定",notification_providers:"通知プロバイダー",notification_templates:"通知テンプレート",smart_plugs:"スマートプラグ",printers:"プリンター",filaments:"フィラメント",maintenance_types:"メンテナンスタイプ",archives:"アーカイブ",projects:"プロジェクト",pending_uploads:"保留中のアップロード",external_links:"外部リンク",api_keys:"APIキー"}},tags:{title:"タグ",addTag:"タグを追加",editTag:"タグを編集",deleteTag:"タグを削除",tagName:"タグ名",tagColor:"タグの色",noTags:"タグがありません",deleteConfirm:"このタグを削除しますか?",manageTags:"タグを管理"},uploadModal:{title:"3MFファイルのアップロード",dragDrop:".3mfファイルをここにドラッグ&ドロップ",or:"または",browseFiles:"ファイルを参照",extractionInfo:"プリンターモデルは3MFファイルのメタデータから自動的に抽出されます。",uploaded:"アップロード済み",failed:"アップロードに失敗しました",uploading:"アップロード中...",upload:"アップロード",uploadFailed:"アップロード失敗"},editArchive:{title:"アーカイブを編集",name:"名前",namePlaceholder:"印刷名",printer:"プリンター",noPrinter:"プリンターなし",project:"プロジェクト",noProject:"プロジェクトなし",itemsPrinted:"印刷数",itemsPrintedHelp:"この印刷ジョブで製造したアイテム数",notes:"メモ",notesPlaceholder:"この印刷についてメモを追加...",externalLink:"外部リンク",externalLinkPlaceholder:"https://...",externalLinkHelp:"Printables、Thingiverse、その他のソースへのリンク",tags:"タグ",tagsPlaceholder:"タグを追加...",addMoreTags:"タグをさらに追加...",matchingTags:'"{{query}}" に一致',existingTags:"既存のタグ",clickToAdd:"(クリックして追加)",status:"ステータス",failureReason:"失敗理由",selectReason:"理由を選択...",photos:"印刷結果の写真",photosHelp:"+ をクリックして印刷結果の写真を追加",printResult:"印刷結果",saving:"保存中...",failureReasons:{adhesionFailure:"定着不良",spaghettiDetached:"スパゲッティ / 剥離",layerShift:"レイヤーシフト",cloggedNozzle:"ノズル詰まり",filamentRunout:"フィラメント切れ",warping:"反り",stringing:"糸引き",underExtrusion:"押出不足",powerFailure:"電源障害",userCancelled:"ユーザーによるキャンセル",other:"その他"},statuses:{completed:"完了",failed:"失敗",aborted:"キャンセル",printing:"印刷中"}},kProfiles:{title:"Kプロファイル",noPrintersConfigured:"プリンターが設定されていません",addPrinterInSettings:"Kプロファイルを管理するには設定でプリンターを追加してください",noActivePrinters:"アクティブなプリンターがありません",enablePrinterConnection:"Kプロファイルを表示するにはプリンター接続を有効にしてください",loadingProfiles:"Kプロファイルを読み込み中...",printerOffline:"プリンターオフライン",printerOfflineDesc:"選択したプリンターは接続されていません。電源を入れてKプロファイルを表示してください。",noMatchingProfiles:"一致するプロファイルなし",noMatchingProfilesDesc:"検索条件に一致するプロファイルがありません",noKProfiles:"Kプロファイルなし",noKProfilesDesc:"{{diameter}}mmノズル用の圧力キャリブレーションプロファイルが見つかりません",createFirstProfile:"最初のプロファイルを作成",printer:"プリンター",nozzle:"ノズル",refresh:"更新",addProfile:"K-プロファイルを追加",export:"エクスポート",import:"インポート",select:"選択",selectAll:"すべて選択",delete:"削除",searchPlaceholder:"名前またはフィラメントで検索...",allExtruders:"すべてのエクストルーダー",leftOnly:"左のみ",rightOnly:"右のみ",allFlow:"すべてのフロー",hfOnly:"HFのみ",sOnly:"Sのみ",sortName:"ソート: 名前",sortKValue:"ソート: K値",sortFilament:"ソート: フィラメント",leftExtruder:"左エクストルーダー",rightExtruder:"右エクストルーダー",modal:{addTitle:"Kプロファイルを追加",editTitle:"Kプロファイルを編集",profileName:"プロファイル名",profileNamePlaceholder:"マイPLAプロファイル",kValue:"K値",kValuePlaceholder:"0.020",kValueHelp:"一般的な範囲: PLA 0.01〜0.06、PETG 0.02〜0.10",filament:"フィラメント",selectFilament:"フィラメントを選択...",noFilamentsHelp:"フィラメントが見つかりません。Bambu Studioでまずプロファイルを作成してください。",flowType:"フロータイプ",highFlow:"ハイフロー",standard:"スタンダード",nozzleSize:"ノズルサイズ",extruder:"エクストルーダー",extruders:"エクストルーダー",left:"左",right:"右",notes:"メモ(ローカル保存)",notesPlaceholder:"このプロファイルのメモを追加...",notesHelp:"メモはBambuddyに保存され、プリンターには保存されません",syncing:"プリンターと同期中...",savingExtruder:"エクストルーダーに保存中 {{current}}/{{total}}...",pleaseWait:"お待ちください"},deleteConfirm:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"「{{name}}」をプリンターから削除しますか?"},bulkDelete:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"選択した{{count}}件のプロファイルをプリンターから削除しますか?"},toast:{profileSaved:"Kプロファイルを保存しました",profilesSaved:"Kプロファイルを{{count}}台のエクストルーダーに保存しました",selectAtLeastOneExtruder:"エクストルーダーを1つ以上選択してください",profileDeleted:"Kプロファイルを削除しました",profilesDeleted:"{{count}}件のプロファイルを削除しました",exportedProfiles:"{{count}}件のプロファイルをエクスポートしました",importedProfiles:"{{total}}件中{{imported}}件のプロファイルをインポートしました",noProfilesToExport:"エクスポートするプロファイルがありません",invalidFileFormat:"無効なファイル形式",failedToParseImport:"インポートファイルの解析に失敗しました",failedToSaveBatch:"Kプロファイルの保存に失敗しました",noteSaved:"メモを保存しました",failedToSaveNote:"メモの保存に失敗しました"},permission:{noRead:"プロファイルを更新する権限がありません",noCreate:"プロファイルを追加する権限がありません",noUpdate:"Kプロファイルを更新する権限がありません",noDelete:"Kプロファイルを削除する権限がありません",noExport:"プロファイルをエクスポートする権限がありません",noImport:"プロファイルをインポートする権限がありません"}},virtualPrinter:{title:"仮想プリンター",running:"稼働中",stopped:"停止",description:{default:"Bambu StudioとOrcaSlicerに表示される仮想プリンターを有効化。このプリンターに送信されたファイルは印刷せずに直接アーカイブされます。",proxy:"スライサーのトラフィックを実際のプリンターに転送するプロキシを有効化。任意のネットワーク経由でリモート印刷が可能です。"},enable:{title:"仮想プリンターを有効化",visibleInSlicer:"スライサーの検出リストに「Bambuddy」として表示",proxyingTo:"{{name}}にプロキシ中",notActive:"非アクティブ"},model:{title:"プリンターモデル",description:"エミュレートするプリンターモデルを選択。",restartWarning:"モデルを変更すると仮想プリンターが再起動されます"},accessCode:{title:"アクセスコード",isSet:"アクセスコードが設定されています",notSet:"アクセスコード未設定 - 有効化に必要です",placeholder:"8文字のコードを入力",placeholderChange:"新しいコードを入力して変更",hint:"正確に8文字必要です。スライサーの認証に使用されます。",charCount:"({{count}}/8)"},targetPrinter:{title:"ターゲットプリンター",configured:"プロキシターゲット設定済み",notConfigured:"ターゲットプリンター未選択 - プロキシモードに必要です",placeholder:"プリンターを選択...",hint:"スライサートラフィックの転送先プリンターを選択。プリンターはLANモードである必要があります。",noPrinters:"プリンターが設定されていません。プロキシモードを使用するにはまずプリンターを追加してください。"},remoteInterface:{title:"ネットワークインターフェース上書き",configured:"インターフェース上書き有効",optional:"オプション — 自動検出IPが間違っている場合に使用(複数NIC、Docker、VPNなど)",placeholder:"自動検出(デフォルト)...",hint:"SSDPで広告され、TLS証明書に使用されるIPアドレスを上書きします。Bambuddyに複数のネットワークインターフェースがある場合に便利です。"},mode:{title:"モード",archive:"アーカイブ",archiveDesc:"ファイルを即座にアーカイブ",review:"レビュー",reviewDesc:"アーカイブ前にレビュー",queue:"キュー",queueDesc:"アーカイブしてキューに追加",proxy:"プロキシ",proxyDesc:"実際のプリンターに転送"},autoDispatch:{title:"自動ディスパッチ",description:"キューに追加されたときに自動的に印刷を開始します。オフの場合、手動ディスパッチを待ちます。"},setupRequired:{title:"セットアップが必要です",description:"仮想プリンター機能を使用するには追加のシステム設定が必要です。ポートフォワーディング、ファイアウォールルール、プラットフォーム固有の設定が含まれます。",readGuide:"有効にする前にセットアップガイドをお読みください"},howItWorks:{title:"仕組み",step1:"同じLAN上では、仮想プリンターはスライサー(Bambu Studio / OrcaSlicer)に自動的に表示されます。他のネットワークからは、IPアドレスとアクセスコードで手動で追加してください。",step2:"アーカイブ、レビュー、キューモードでは、スライサーの「送信」ボタンを使用して3MFファイルをBambuddyにアップロードします。スライサーは「印刷成功」と表示しますが、ファイルは保存され、印刷はされません。",step3:"プロキシモードでは、仮想プリンターはすべてのトラフィックを実際のプリンターに転送します。直接接続されているかのように印刷がすぐに開始されます。"},status:{title:"ステータス詳細",printerName:"プリンター名",model:"モデル",serialNumber:"シリアル番号",mode:"モード",pendingFiles:"保留中のファイル",targetPrinter:"ターゲットプリンター",ftpPort:"FTPポート",mqttPort:"MQTTポート",ftpConnections:"FTP接続数",mqttConnections:"MQTT接続数"},toast:{updated:"仮想プリンター設定を更新しました",failedToUpdate:"設定の更新に失敗しました",accessCodeRequired:"先にアクセスコードを設定してください",targetPrinterRequired:"先にターゲットプリンターを選択してください",bindIpRequired:"先にバインドIPを設定してください",accessCodeEmpty:"アクセスコードは空にできません",accessCodeLength:"アクセスコードは8文字である必要があります",created:"仮想プリンターを作成しました",failedToCreate:"仮想プリンターの作成に失敗しました",deleted:"仮想プリンターを削除しました",failedToDelete:"仮想プリンターの削除に失敗しました"},list:{title:"仮想プリンター",add:"追加",addFirst:"仮想プリンターを追加",empty:"仮想プリンターが設定されていません。追加して始めましょう。"},bindIp:{title:"バインドインターフェース",placeholder:"インターフェースを選択...",hint:"この仮想プリンターがバインドするネットワークインターフェース。プリンターごとに一意である必要があります。"},proxy:{accessCodeHint:"プロキシモードでは、スライサーにターゲットプリンターのアクセスコードを使用してください。接続は実際のプリンターに透過的に転送されます。"},addDialog:{title:"仮想プリンターを追加",name:"名前",hint:"アクセスコード、ターゲットプリンター、その他の設定は作成後に設定できます。",create:"作成"},deleteConfirm:{title:"仮想プリンターを削除",message:"「{{name}}」を削除してもよろしいですか?このプリンターのすべてのサービスが停止されます。"}},modelViewer:{openInSlicer:"スライサーで開く",tabs:{model:"3Dモデル",gcode:"G-codeプレビュー"},notAvailable:"利用不可",notSliced:"未スライス",plates:"プレート",allPlates:"全プレート",plateNumber:"プレート {{number}}",plateCount:"{{count}} プレート",plateCount_other:"{{count}} プレート",objectCount:"{{count}} オブジェクト",objectCount_other:"{{count}} オブジェクト",filamentCount:"{{count}} フィラメント",filamentCount_other:"{{count}} フィラメント",eta:"予想時間 {{minutes}} 分",noPreview:"このファイルのプレビューは利用できません",pagination:{pageOf:"ページ {{current}} / {{total}}",prev:"前へ",next:"次へ"},errors:{failedToLoad:"ファイルの読み込みに失敗しました",noMeshes:"3MFファイルにメッシュが見つかりません",unsupportedFormat:"サポートされていないファイル形式です"}},maintenanceDescriptions:{lubricateCarbonRods:"カーボンロッドに潤滑剤を塗布してスムーズな動きを確保",lubricateRails:"リニアレールの潤滑",cleanNozzle:"ノズル/ホットエンドの清掃",checkBelts:"ベルト張力の確認",cleanBuildPlate:"ビルドプレートの清掃",checkExtruder:"エクストルーダーギアの確認",checkCooling:"冷却ファンの確認",generalInspection:"総合点検",cleanCarbonRods:"カーボンロッドの清掃",lubricateSteelRods:"スチールロッドに潤滑剤を塗布してスムーズな動きを確保",cleanSteelRods:"スチールロッドの清掃",cleanLinearRails:"リニアレールを拭いてほこりや汚れを除去",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},smartPlugs:{offline:"オフライン",admin:"管理",openPlugAdminPage:"プラグ管理ページを開く",deleteSmartPlug:"スマートプラグを削除",turnOnSmartPlug:"スマートプラグをオンにする",turnOffSmartPlug:"スマートプラグをオフにする",turnOn:"オンにする",turnOff:"オフにする",addSmartPlug:{scanningNetwork:"ネットワークをスキャン中...",chooseEntity:"エンティティを選択...",connectionFailed:"接続失敗",searchEntities:"エンティティを検索...",searchPowerSensors:"電力センサーを検索...",searchEnergySensors:"エネルギーセンサーを検索...",placeholders:{plugName:"リビングルームプラグ",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"電力トピックと同じ、または異なる"}},linkedTo:"リンク先:",monitorOnly:"監視のみ",alerts:"アラート",scheduleOn:"オン {{time}}",scheduleOff:"オフ {{time}}",on:"オン",off:"オフ",power:"電力",kwhToday:"本日のkWh",settings:"設定",automationSettings:"自動化設定",showInSwitchbar:"スイッチバーに表示",quickAccessSidebar:"サイドバーからクイックアクセス",enabled:"有効",enableAutomation:"このプラグの自動化を有効にする",autoOn:"自動オン",autoOnDescription:"印刷開始時にオンにする",autoOff:"自動オフ",autoOffDescription:"印刷完了時にオフにする(ワンショット)",autoOffPersistent:"有効のまま維持",autoOffPersistentDescription:"ワンショットではなく印刷間で有効のまま維持",turnOffDelayMode:"オフ遅延モード",time:"時間",temp:"温度",delayMinutes:"遅延(分)",tempThreshold:"温度しきい値(°C)",tempThresholdDescription:"ノズルがこの温度以下に冷却されるとオフになります",edit:"編集",deleteConfirm:'"{{name}}"を削除してもよろしいですか?この操作は取り消せません。',turnOnConfirm:'"{{name}}"をオンにしてもよろしいですか?',turnOffConfirm:'"{{name}}"をオフにしてもよろしいですか?接続されたデバイスの電源が切れます。',failedToTurn:'"{{name}}"を{{action}}できませんでした',unknown:"不明",addTitle:"スマートプラグを追加",editTitle:"スマートプラグを編集",stopScanning:"スキャン停止",discoverTasmota:"Tasmotaデバイスを検出",foundDevices:"{{count}}台のデバイスが見つかりました - クリックして選択:",noDevicesFound:"ネットワーク上にTasmotaデバイスが見つかりません",haNotConfigured:"Home Assistantが設定されていません。設定場所:",haSettingsPath:"設定 → ネットワーク → Home Assistant",selectEntity:"エンティティを選択 *",ipAddress:"IPアドレス *",nameLabel:"名前 *",username:"ユーザー名",password:"パスワード",authHint:"Tasmotaデバイスが認証を必要としない場合は空のままにしてください",linkToPrinter:"プリンターにリンク",noPrinter:"プリンターなし(手動制御のみ)",linkingDescription:"リンクすると印刷開始/完了時に自動でオン/オフできます",powerAlerts:"電力アラート",alertAbove:"上限アラート(W)",alertBelow:"下限アラート(W)",alertDescription:"電力消費がこれらのしきい値を超えた場合に通知します。無効にするには空のままにしてください。",dailySchedule:"デイリースケジュール",turnOnAt:"オンにする時刻",turnOffAt:"オフにする時刻",scheduleDescription:"毎日これらの時刻にプラグを自動的にオン/オフします。スキップするには空のままにしてください。",showOnPrinterCard:"プリンターカードに表示",displayOnPrinterCard:"プリンターカードにボタンを表示",connectedResult:"接続成功!",deviceLabel:"デバイス: {{name}} - ",stateLabel:"状態: {{state}}",test:"テスト",delete:"削除",save:"保存",add:"追加",cancel:"キャンセル",failedToStartScan:"スキャンを開始できませんでした",nameRequired:"名前は必須です",entityRequired:"Home AssistantプラグにはエンティティIDが必要です",mqttTopicRequired:"電力、エネルギー、または状態監視用に少なくとも1つのMQTTトピックを設定する必要があります",loadingEntities:"エンティティを読み込み中...",loading:"読み込み中...",failedToLoadEntities:"エンティティの読み込みに失敗しました: {{error}}",noEntitiesMatching:'"{{search}}"に一致するエンティティが見つかりません',noEntitiesAvailable:"利用可能なエンティティがありません",searchingEntities:"すべてのエンティティを検索中({{count}}件見つかりました)",showingEntities:"switch、light、input_booleanを表示({{count}}件利用可能)",energyMonitoringOptional:"エネルギー監視(オプション)",energyMonitoringHint:"電力/エネルギーデータを提供するセンサーを検索して選択します。",powerSensorW:"電力センサー(W)",energyTodayKwh:"本日のエネルギー(kWh)",totalEnergyKwh:"総エネルギー(kWh)",noMatchingSensors:"一致するセンサーがありません",none:"なし",mqttNotConfigured:"MQTTブローカーが設定されていません。ブローカーアドレスを設定してください:",mqttSettingsPath:"設定 → ネットワーク → MQTT配信",mqttNotConfiguredSuffix:"(配信を有効にする必要はありません。ブローカーの詳細を入力するだけです)。",mqttMonitorOnlyDescription:"MQTTプラグはMQTTサブスクリプション経由で電力/エネルギーデータを受信します。オン/オフ制御は利用できません - MQTTブローカーまたはホームオートメーションシステムを使用してください。",powerMonitoring:"電力監視",energyMonitoring:"エネルギー監視",stateMonitoring:"状態監視",optional:"オプション",topic:"トピック",jsonPath:"JSONパス",multiplier:"乗数",onValue:"ON値",mqttPowerHint:`JSONパスはJSONペイロードから値を抽出します(例: "power_l1")。トピックが生の数値を送信する場合は空のままにしてください。
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"電力URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"電力乗数",restEnergyUrl:"エネルギーURL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"エネルギー乗数",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"電力データ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyUrlHint:"エネルギーデータ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyHint:"各値は個別のURLを使用するか、ステータスURLにフォールバックできます。乗数で単位変換が可能です(例:WhからkWhへの変換は0.001)。",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"スイッチバーにスイッチがありません",enableSwitchbarHint:"設定 > スマートプラグで「スイッチバーに表示」を有効にしてください"},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"メール",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTPメール通知",telegram:"Telegramボット経由の通知",discord:"Webhook経由でDiscordチャンネルに送信",ntfy:"無料のセルフホスト可能なプッシュ通知",pushover:"シンプルで信頼性の高いプッシュ通知",callmebot:"CallMeBot経由の無料WhatsApp通知",webhook:"任意のURLへの汎用HTTP POST",homeassistant:"Home Assistantダッシュボードの永続通知"},lastSuccess:"最終: {{date}}",error:"エラー",printer:"プリンター:",allPrinters:"すべてのプリンター",sendTestNotification:"テスト通知を送信",eventSettings:"イベント設定",enabled:"有効",sendFromProvider:"このプロバイダーから通知を送信",printEvents:"印刷イベント",printerStatus:"プリンターステータス",amsAlarms:"AMSアラーム",amsHtAlarms:"AMS-HTアラーム",printQueue:"印刷キュー",start:"開始",plateCheck:"プレートチェック",complete:"完了",failed:"失敗",stopped:"停止",progress:"進捗",offline:"オフライン",lowFilament:"フィラメント残量低下",maintenance:"メンテナンス",amsHumidity:"AMS湿度",amsTemp:"AMS温度",amsHtHumidity:"AMS-HT湿度",amsHtTemp:"AMS-HT温度",bedCooled:"ベッド冷却済み",firstLayer:"第1層完了",quiet:"静音",digest:"ダイジェスト {{time}}",printStarted:"印刷開始",plateNotEmpty:"プレートが空でない",plateNotEmptyDescription:"印刷前にオブジェクトが検出されました",printCompleted:"印刷完了",bedCooledLabel:"ベッド冷却済み",bedCooledDescription:"印刷後にベッドがしきい値以下に冷却",firstLayerCompleteLabel:"第1層完了",firstLayerCompleteDescription:"第1層完了時にスナップショット付きで通知",missingSpoolAssignmentLabel:"スプール割り当て不足",missingSpoolAssignmentDescription:"印刷開始時に必要トレイへスプールが未割り当ての場合に通知",printFailed:"印刷失敗",printStopped:"印刷停止",progressMilestones:"進捗マイルストーン",progressMilestonesDescription:"25%、50%、75%で通知",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",lowFilamentLabel:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",maintenanceDueDescription:"メンテナンスが必要な場合に通知",amsHumidityHigh:"AMS湿度高",amsHumidityHighDescription:"通常AMSの湿度がしきい値を超過",amsTemperatureHigh:"AMS温度高",amsTemperatureHighDescription:"通常AMSの温度がしきい値を超過",amsHtHumidityHigh:"AMS-HT湿度高",amsHtHumidityHighDescription:"AMS-HTの湿度がしきい値を超過",amsHtTemperatureHigh:"AMS-HT温度高",amsHtTemperatureHighDescription:"AMS-HTの温度がしきい値を超過",jobAdded:"ジョブ追加",jobAddedDescription:"キューにジョブが追加されました",jobAssigned:"ジョブ割り当て",jobAssignedDescription:"モデルベースのジョブがプリンターに割り当てられました",jobStarted:"ジョブ開始",jobStartedDescription:"キュージョブの印刷が開始されました",jobWaiting:"ジョブ待機中",jobWaitingDescription:"フィラメントまたはプリンター待ちのジョブ",jobSkipped:"ジョブスキップ",jobSkippedDescription:"ジョブがスキップされました(前のジョブが失敗)",jobFailed:"ジョブ失敗",jobFailedDescription:"ジョブの開始に失敗しました",queueComplete:"キュー完了",queueCompleteDescription:"すべてのキュージョブが完了しました",quietHours:"静音時間",noNotificationsDuring:"この時間帯は通知を送信しません",editProviderToChangeQuietHours:"プロバイダーを編集して静音時間を変更",dailyDigest:"デイリーダイジェスト",batchNotifications:"通知をまとめて1日のサマリーとして送信",sendAt:"{{time}}に送信",editProviderToChangeDigestTime:"プロバイダーを編集してダイジェスト時刻を変更",edit:"編集",deleteProvider:"通知プロバイダーを削除",deleteConfirm:'"{{name}}"を削除してもよろしいですか?この操作は取り消せません。',delete:"削除",addTitle:"通知プロバイダーを追加",editTitle:"通知プロバイダーを編集",nameLabel:"名前 *",namePlaceholder:"マイ通知",providerTypeLabel:"プロバイダータイプ *",configuration:"設定",testConfiguration:"設定をテスト",printerFilter:"プリンターフィルター",onlyFromPrinter:"このプリンターからのイベントのみ通知を送信",quietHoursDnd:"静音時間(おやすみモード)",quietStart:"開始",quietEnd:"終了",dailyDigestLabel:"デイリーダイジェスト",sendDigestAt:"ダイジェスト送信時刻",digestCollected:"イベントが収集され、この時刻にまとめて送信されます",notificationEvents:"通知イベント",progressPercent:"(25%、50%、75%)",bedCooledAfterPrint:"(印刷完了後)",cancel:"キャンセル",save:"保存",add:"追加",nameRequired:"名前は必須です",fieldRequired:"{{field}}は必須です",phoneNumber:"電話番号",apiKey:"APIキー",serverUrl:"サーバーURL",topic:"トピック",authToken:"認証トークン",userKey:"ユーザーキー",appToken:"アプリトークン",priority:"優先度",botToken:"ボットトークン",chatId:"チャットID",smtpServer:"SMTPサーバー",smtpPort:"SMTPポート",security:"セキュリティ",authentication:"認証",username:"ユーザー名",password:"パスワード",fromEmail:"送信元メール",toEmail:"宛先メール",webhookUrl:"Webhook URL",payloadFormat:"ペイロード形式",authorization:"認可",titleFieldName:"タイトルフィールド名",messageFieldName:"メッセージフィールド名",editTemplate:"テンプレートを編集: {{name}}",titleLabel:"タイトル",bodyLabel:"本文",titlePlaceholder:"通知タイトル...",bodyPlaceholder:"通知本文...",availableVariables:"利用可能な変数",clickToInsert:"クリックして本文のカーソル位置に挿入",livePreview:"ライブプレビュー",hide:"非表示",show:"表示",loadingPreview:"プレビューを読み込み中...",enterTemplateContent:"テンプレートの内容を入力するとプレビューが表示されます",titlePreview:"タイトル:",bodyPreview:"本文:",resetToDefault:"デフォルトにリセット",titleRequired:"タイトルは必須です",bodyRequired:"本文は必須です",notificationLog:"通知ログ",showFailedOnly:"失敗のみ",last24Hours:"過去24時間",last7Days:"過去7日間",last30Days:"過去30日間",last90Days:"過去90日間",justNow:"たった今",noFailedNotifications:"失敗した通知はありません",noNotificationsLogged:"記録された通知はありません",unknownProvider:"不明なプロバイダー",logTitle:"タイトル",logMessage:"メッセージ",logError:"エラー",logProvider:"プロバイダー: {{type}}",logTime:"時刻: {{time}}",refresh:"更新",clearOld:"古いものを削除",statsSummary:"過去{{days}}日間:",statsNotifications:"通知",statsSent:"{{count}}件送信",statsFailed:"{{count}}件失敗",eventTypes:{print_start:"印刷開始",print_complete:"印刷完了",print_failed:"印刷失敗",print_stopped:"印刷停止",print_progress:"進捗",printer_offline:"プリンターオフライン",printer_error:"プリンターエラー",filament_low:"フィラメント残量低下",maintenance_due:"メンテナンス期限",test:"テスト"},userEmail:{title:"通知",emailNotifications:"メール通知",emailNotificationsDesc:"自分の印刷ジョブに対してメール通知を受け取ります。メールは高度な認証で設定されたSMTP設定を使用して送信されます。",sendingTo:"通知の送信先",noEmailWarning:"アカウントにメールアドレスが設定されていません。管理者に連絡して追加してもらってください。",printJobNotifications:"印刷ジョブ通知",printJobNotificationsDesc:"送信した印刷ジョブのどのイベントでメール通知を送るかを選択します。",printJobStarts:"印刷ジョブ開始",printJobStartsDesc:"印刷ジョブが開始されたときに通知を受け取る。",printJobFinishes:"印刷ジョブ完了",printJobFinishesDesc:"印刷ジョブが正常に完了したときに通知を受け取る。",printErrors:"印刷エラー",printErrorsDesc:"印刷ジョブが失敗またはエラーが発生したときに通知を受け取る。",printJobStops:"印刷ジョブ停止",printJobStopsDesc:"印刷ジョブがキャンセルまたは停止されたときに通知を受け取る。",saveSuccess:"通知設定を保存しました。",saveError:"通知設定の保存に失敗しました。"}},richTextEditor:{bold:"太字",italic:"斜体",underline:"下線",bulletList:"箇条書きリスト",numberedList:"番号付きリスト",alignLeft:"左揃え",alignCenter:"中央揃え",alignRight:"右揃え",addLink:"リンクを追加",removeLink:"リンクを削除"},externalLinks:{noLinksConfigured:"外部リンクが設定されていません",deleteLink:"リンクを削除",removeCustomIcon:"カスタムアイコンを削除",openInNewTab:"新しいタブで開く",placeholders:{linkName:"マイリンク"}},keyboardShortcuts:{title:"キーボードショートカット",navigation:"ナビゲーション",archivesSection:"アーカイブ",kProfilesSection:"Kプロファイル",generalSection:"全般",shortcuts:{goToPrinters:"プリンターへ移動",goToArchives:"アーカイブへ移動",goToQueue:"キューへ移動",goToStats:"統計へ移動",goToProfiles:"クラウドプロファイルへ移動",goToSettings:"設定へ移動",focusSearch:"検索にフォーカス",openUploadModal:"アップロードモーダルを開く",clearSelection:"選択をクリア / 入力をぼかす",contextMenu:"カードのコンテキストメニュー",refreshProfiles:"プロファイルを更新",newProfile:"新しいプロファイル",exitSelectionMode:"選択モードを終了",showHelp:"このヘルプを表示"},footer:"Escキーを押すか外側をクリックして閉じます"},notificationLog:{title:"通知ログ",events:{printStarted:"印刷開始",printComplete:"印刷完了",printFailed:"印刷失敗",printStopped:"印刷停止",progress:"進捗",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",lowFilament:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",test:"テスト"},timeAgo:{justNow:"たった今",minutesAgo:"{{minutes}}分前",hoursAgo:"{{hours}}時間前"}},restoreBackup:{title:"バックアップを復元",restoring:"復元中...",restoreComplete:"復元完了",restoreFailed:"復元失敗",importSettings:"バックアップファイルから設定をインポート",pleaseWait:"データの復元中です。しばらくお待ちください",clickToSelect:"クリックしてバックアップファイルを選択(.jsonまたは.zip)",howDuplicateHandling:"重複の処理方法:",categories:{printers:"プリンター",smartPlugs:"スマートプラグ",notificationProviders:"通知プロバイダー",filaments:"フィラメント",archives:"アーカイブ",pendingUploads:"保留中のアップロード",settingsTemplates:"設定とテンプレート"},matchingInfo:{printers:"シリアル番号で照合",smartPlugs:"IPアドレスで照合",notificationProviders:"名前で照合",filaments:"名前+タイプ+ブランドで照合",archives:"コンテンツハッシュで照合",pendingUploads:"ファイル名で照合",settingsTemplates:"常に上書き"},replaceExisting:"既存データを置き換え",keepExisting:"既存データを保持",replaceDescription:"既に存在するアイテムをバックアップデータで上書き",keepDescription:"まだ存在しないアイテムのみを復元",caution:"注意:",cautionText:"上書きすると現在の構成がバックアップデータに置き換えられます。セキュリティ上の理由から、プリンターのアクセスコードは上書きされません。",itemsRestored:"復元されたアイテム",itemsSkipped:"スキップされたアイテム",restored:"復元済み",skipped:"スキップ(既に存在)",filesLabel:"ファイル(3MF、サムネイルなど)",newApiKeysGenerated:"新しいAPIキーが生成されました",newApiKeysWarning:"これらのキーは一度だけ表示されます。今すぐコピーしてください!",processingBackup:"バックアップファイルを処理中...",noDataFound:"バックアップファイルに復元するデータが見つかりませんでした。",failedToRestore:"バックアップの復元に失敗しました。ファイル形式を確認してください。"},backupExport:{title:"バックアップをエクスポート",selectData:"含めるデータを選択",selectAll:"すべて選択",selectNone:"なし",categoryDescriptions:{settings:"言語、テーマ、更新設定",notifications:"ntfy、Pushover、Discordなど",templates:"カスタムメッセージテンプレート",smartPlugs:"Tasmotaプラグ設定",externalLinks:"サイドバーの外部サービスへのリンク",printers:"プリンター情報(アクセスコード除外)",plateDetection:"空プレート参照画像",filaments:"フィラメントの種類とコスト",maintenance:"カスタムメンテナンススケジュール",archives:"すべての印刷データ+ファイル(3MF、サムネイル、写真)",projects:"プロジェクト、BOMアイテム、添付ファイル",pendingUploads:"仮想プリンターアップロード待機中",apiKeys:"Webhook APIキー(インポート時に新しいキーが生成されます)"},requiresPrinters:"プリンターを選択する必要があります",zipFileWarning:"ZIPファイルが作成されます。",zipFileDescription:"すべての3MFファイル、サムネイル、タイムラプス、写真が含まれます。これには時間がかかり、大きなファイルになる可能性があります。",includeAccessCodes:"アクセスコードを含める",includeAccessCodesDescription:"別のマシンへの転送用",includeAccessCodesWarning:"アクセスコードはプレーンテキストで含まれます。このバックアップファイルを安全に保管してください!",categoriesSelected:"{{selectedCount}}カテゴリー選択済み"},pendingUploads:{placeholders:{notes:"この印刷に関するメモを追加..."},discardUpload:"アップロードを破棄",archiveAllUploads:"すべてのアップロードをアーカイブ",discardAllUploads:"すべてのアップロードを破棄",archive:"アーカイブ",timeAgo:{justNow:"たった今",minutesAgo:"{{minutes}}分前",hoursAgo:"{{hours}}時間前",daysAgo:"{{days}}日前"}},apiBrowser:{placeholders:{requestBody:"JSONリクエストボディ...",searchEndpoints:"エンドポイントを検索..."}},configureAmsSlot:{title:"AMSスロットの設定",slotConfigured:"スロットを設定しました!",configuringSlot:"スロットを設定中:",slotLabel:"{{ams}} スロット {{slot}}",searchPresets:"プリセットを検索...",colorPlaceholder:"色名またはHex(例: 茶色、FF8800)",clearCustomColor:"カスタム色をクリア",noCloudPresets:"クラウドプリセットがありません。Bambu Cloudにログインして同期してください。",noPresetsAvailable:"プリセットがありません。Bambu Cloudにログインするか、ローカルプロファイルをインポートしてください。",noMatchingPresets:"一致するプリセットが見つかりません。",custom:"カスタム",builtin:"内蔵",settingsSentToPrinter:"設定をプリンターに送信しました",filamentProfile:"フィラメントプロファイル",kProfileLabel:"Kプロファイル(Pressure Advance)",filteringFor:"フィルター中: {{material}}",noKProfile:"Kプロファイルなし(デフォルト0.020を使用)",noMatchingKProfiles:"一致するKプロファイルが見つかりません。デフォルトK=0.020が使用されます。",selectFilamentFirst:"まずフィラメントプロファイルを選択してください",kFromCalibration:"K={{value}}(プリンターキャリブレーションから)",customColorLabel:"カスタム色(オプション)",presetColors:"{{name}}の色:",showLessColors:"色を減らす",showMoreColors:"色をもっと表示",clear:"クリア",hexLabel:"Hex: #{{hex}}",resetting:"リセット中...",resetSlot:"スロットをリセット",cancel:"キャンセル",configuring:"設定中...",configureSlot:"スロットを設定"},githubBackup:{title:"GitHubバックアップ",history:"履歴",downloadBackup:"バックアップをダウンロード",restoreBackup:"バックアップを復元",noBackupsYet:"バックアップはまだありません"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"タグを検索...",renameTag:"タグ名を変更",deleteTag:"タグを削除"},notificationTemplates:{placeholders:{title:"通知タイトル...",body:"通知本文..."}},batchTag:{placeholders:{newTag:"新しいタグを入力..."}},photoGallery:{deletePhoto:"写真を削除"},filamentHoverCard:{copySpoolUuid:"スプールUUIDをコピー"},kProfilesView:{hasNote:"メモあり",copyProfile:"プロファイルをコピー"},layout:{openMenu:"メニューを開く",noPermissionSystemInfo:"システム情報を表示する権限がありません"},dashboard:{dragToReorder:"ドラッグして並べ替え",hideWidget:"ウィジェットを非表示"},notificationProviderCard:{deleteNotificationProvider:"通知プロバイダーを削除"},fileManagerModal:{closeFileManager:"ファイルマネージャーを閉じる",sortFiles:"ファイルを並べ替え",goToParentFolder:"親フォルダーへ移動",threeView:"3Dビュー"},embeddedCameraViewer:{refreshStream:"ストリームを更新",close:"閉じる",zoomOut:"ズームアウト",resetZoom:"ズームをリセット",zoomIn:"ズームイン",dragToResize:"ドラッグしてサイズ変更"},timelapseViewer:{skipBack5s:"5秒戻る",skipForward5s:"5秒進む"},notificationProviders:{descriptions:{email:"SMTP電子メール通知",telegram:"Telegramボット経由の通知",discord:"Webhookを介してDiscordチャンネルに送信",ntfy:"無料でセルフホスト可能なプッシュ通知",pushover:"シンプルで信頼性の高いプッシュ通知",callmebot:"CallMeBot経由の無料WhatsApp通知",webhook:"任意のURLへのジェネリックHTTP POST"}},logViewer:{searchPlaceholder:"メッセージまたはロガー名を検索...",noLogEntries:"ログエントリが見つかりません"},switchbarPopover:{noSwitchesInSwitchbar:"スイッチバーにスイッチがありません"},projectPageModal:{placeholders:{title:"タイトル",designer:"デザイナー",license:"ライセンス",description:"説明を入力...",profileTitle:"プロファイルタイトル",profileDescription:"プロファイルの説明..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"待機中",justNow:"たった今",now:"今すぐ",minsAgo:"{{count}}分前",inMins:"あと{{count}}分",hoursAgo:"{{count}}時間前",inHours:"あと{{count}}時間",daysAgo:"{{count}}日前",inDays:"あと{{count}}日"},spoolbuddy:{nav:{dashboard:"ダッシュボード",ams:"AMS",inventory:"インベントリ",writeTag:"書込み",settings:"設定"},status:{nfcReady:"NFC準備完了",nfcOff:"NFCオフ",offline:"オフライン",online:"オンライン",noPrinters:"プリンターなし",deviceOffline:"デバイスオフライン",waitingConnection:"デバイス接続を待っています...",systemReady:"システム準備完了",status:"ステータス"},dashboard:{readyToScan:"スキャン準備完了",idleMessage:"スプールを計量台に置いて識別します",nfcHint:"NFCタグは自動的に読み取られます",device:"デバイス",syncWeight:"重量同期",weightSynced:"同期完了!",unknownTag:"不明なタグ",newTag:"新しいタグを検出",onScale:"計量中",linkSpool:"スプールにリンク",linkTagTitle:"タグをスプールにリンク",linkTag:"タグをリンク",selectSpool:"このタグにリンクするスプールを選択:",noUntagged:"タグなしのスプールが見つかりません",tagDetected:"タグ検出",noTag:"タグなし",tagId:"タグ",grossWeight:"総重量",spoolSize:"スプールサイズ",close:"閉じる",currentSpool:"現在のスプール"},modal:{spoolDetected:"スプール検出",assignToAms:"AMSに割り当て",syncWeight:"重量同期",weightSynced:"同期完了!",syncing:"同期中...",newTagDetected:"新しいタグを検出",addToInventory:"インベントリに追加",assignToAmsTitle:"AMSに割り当て",selectSlot:"スロットを選択",assign:"割り当て",assigning:"割り当て中...",assignSuccess:"割り当て完了!",assignError:"スプールの割り当てに失敗しました。再試行してください。",noPrinterSelected:"プリンターを選択...",noAmsDetected:"このプリンターにAMSが検出されません",slot:"スロット"},weight:{noReading:"読み取りなし",stable:"安定",measuring:"計測中...",tare:"風袋引き",calibrate:"キャリブレーション"},spool:{remaining:"残量",material:"素材",brand:"ブランド",color:"色",coreWeight:"コア",labelWeight:"ラベル",scaleWeight:"計量",netWeight:"正味",lastUsed:"最終使用"},ams:{noData:"AMSが検出されません",connectAms:"AMSを接続してスロットを表示",noPrinter:"プリンター未選択",selectPrinter:"上部バーからプリンターを選択",printerDisconnected:"プリンター切断",humidity:"湿度",level:"レベル",active:"アクティブ",slot:"スロット",empty:"空"},inventory:{search:"スプールを検索...",empty:"インベントリにスプールがありません",noResults:"一致するスプールがありません",spools:"スプール",addSpool:"スプール追加"},settings:{tabDevice:"デバイス",tabDisplay:"ディスプレイ",tabScale:"計量",tabUpdates:"アップデート",nfcReader:"NFCリーダー",type:"タイプ",connection:"接続",notConnected:"N/A",deviceInfo:"デバイス情報",hostname:"ホスト",uptime:"稼働時間",brightness:"明るさ",saved:"保存済み",noBacklight:"DSIバックライトが検出されませんでした。明るさ制御にはDSIディスプレイが必要です。",screenBlank:"画面オフタイムアウト",screenBlankDesc:"操作がないと画面がオフになります。タッチで復帰。",displayNote:"明るさはソフトウェアフィルターとして適用されます。",scaleCalibration:"計量キャリブレーション",currentWeight:"現在の重量",tareOffset:"風袋",calFactor:"係数",knownWeight:"既知の重量",calStep1:"計量台からすべてのアイテムを取り除き、ゼロ設定を押してください。",calStep2:"既知の重量を計量台に置いてください。",setZero:"ゼロ設定",calibrateNow:"キャリブレーション",calibrated:"キャリブレーション済み",tareSet:"風袋コマンドを送信しました。デバイスを待っています...",tareFailed:"風袋コマンドの送信に失敗しました",zeroSet:"ゼロ点を設定しました。既知の重量を計量台に置いてください。",calibrationDone:"キャリブレーション完了!",calibrationFailed:"キャリブレーションに失敗しました",lastCalibrated:"最終キャリブレーション",stable:"安定",settling:"安定化中...",firmware:"ファームウェア",scale:"計量",noDevice:"SpoolBuddyデバイスが見つかりません",daemonVersion:"デーモンバージョン",currentVersion:"現在",versionPending:"デーモンを待っています...",checking:"確認中...",checkUpdates:"アップデートを確認",updateAvailable:"アップデートあり",updateInstructions:"SSH経由で更新:SpoolBuddyインストールスクリプトを実行してください。",upToDate:"最新です",includeBeta:"ベータ版を含む"},writeTag:{tabExisting:"既存のスプール",tabNew:"新規スプール",tabReplace:"タグ交換",searchPlaceholder:"素材、色、ブランドで検索...",noUntaggedSpools:"タグなしのスプールがありません",noTaggedSpools:"タグ付きのスプールがありません",selectSpool:"スプールを選択し、NTAGをリーダーに置いてください",placeTag:"NTAGをリーダーに置いてください",tagReady:"タグ検出 — 書込み準備完了",writeTag:"タグ書込み",replaceTag:"タグ交換",writing:"タグ書込み中...",waiting:"SpoolBuddyを待機中...",writeSuccess:"タグの書込みが完了しました!",writeFailed:"書込み失敗",queueFailed:"書込みコマンドのキューに失敗しました",tryAgain:"再試行",cancel:"キャンセル",replaceWarning:"古いタグのリンクが解除され、新しいタグに置き換わります。",deviceOffline:"SpoolBuddyはオフラインです",material:"素材",colorName:"色名",color:"色",brand:"ブランド",weight:"重量 (g)",createSpool:"スプール作成",creating:"作成中...",spoolCreated:"スプール作成完了!書込み準備ができました。",createFailed:"スプールの作成に失敗しました"},quickMenu:{printerPower:"プリンター電源",systemControls:"システム",restartDaemon:"デーモン再起動",restartBrowser:"ブラウザ再起動",reboot:"再起動",shutdown:"シャットダウン",swipeToClose:"下にスワイプして閉じる",confirmTitle:"確認",confirmShutdown:"SpoolBuddyをシャットダウンしますか?再起動するには物理的なアクセスが必要です。",confirmReboot:"SpoolBuddyを再起動しますか?",confirmRestartDaemon:"SpoolBuddyデーモンを再起動しますか?NFCとスケールが一時的に使用できなくなります。",confirmRestartBrowser:"キオスクブラウザを再起動しますか?画面が一時的に暗くなります。",confirm:"確認",confirmPlugOn:"{{name}}をオンにしますか?",confirmPlugOff:"{{name}}をオフにしますか?",turnOn:"オン",turnOff:"オフ"}},bugReport:{title:"バグを報告",description:"説明",descriptionPlaceholder:"何が問題でしたか?問題を説明してください...",email:"メールアドレス(任意)",emailPlaceholder:"your@email.com",emailPrivacy:"入力された場合、メールアドレスはGitHub Issueの折りたたみセクションに含まれ、メンテナーがフォローアップできるようになります。",screenshot:"スクリーンショット",uploadOrPaste:"画像をアップロード、貼り付け、またはドラッグ",dataCollectedSummary:"レポートに含まれるデータは?",dataIncluded:"含まれるもの:",dataIncludedList:"アプリバージョン、OS、アーキテクチャ、Pythonバージョン、データベース統計(件数のみ)、プリンターモデル、ノズル数、ファームウェアバージョン、接続状態、統合状態(Spoolman、MQTT、HA)、非機密設定、ネットワークインターフェース数、Docker詳細、依存関係バージョン。",dataNeverIncluded:"含まれないもの:",dataNeverIncludedList:"プリンター名、シリアル番号、アクセスコード、パスワード、IPアドレス、メールアドレス、APIキー、トークン、Webhook URL、ホスト名、ユーザー名。",submit:"送信",startLogging:"デバッグログ開始",stepEnableLogging:"デバッグログ有効",stepReproduce:"問題を再現してください",stepStopLogging:"停止してレポート送信",stopAndSubmit:"停止して送信",maxDuration:"{{minutes}}分後に自動停止",stoppingLogs:"ログ収集・送信中...",submitting:"バグレポートを送信中...",submitSuccess:"バグレポートが正常に送信されました!",submitFailed:"バグレポートの送信に失敗しました",thankYou:"ありがとうございます!",submitted:"バグレポートが送信されました。",viewIssue:"Issueを表示",unexpectedError:"予期しないエラーが発生しました"}},Cue={nav:{printers:"Stampanti",archives:"Archivi",queue:"Coda",stats:"Statistiche",profiles:"Profili",maintenance:"Manutenzione",projects:"Progetti",inventory:"Filamento",files:"File",notifications:"Notifiche",settings:"Impostazioni",system:"Sistema",collapseSidebar:"Comprimi barra laterale",expandSidebar:"Espandi barra laterale",update:"Aggiorna",updateAvailable:"Aggiornamento disponibile: v{{version}}",updateAvailableBanner:"Versione {{version}} disponibile!",viewUpdate:"Vedi aggiornamento",viewOnGithub:"Vedi su GitHub",keyboardShortcuts:"Scorciatoie da tastiera (?)",switchToLight:"Passa a tema chiaro",switchToDark:"Passa a tema scuro",smartSwitches:"Interruttori Smart",logout:"Esci"},common:{save:"Salva",saving:"Salvataggio...",cancel:"Annulla",delete:"Elimina",edit:"Modifica",add:"Aggiungi",close:"Chiudi",confirm:"Conferma",loading:"Caricamento...",error:"Errore",success:"Successo",warning:"Avviso",enabled:"Abilitato",disabled:"Disabilitato",yes:"Si",no:"No",on:"On",off:"Off",all:"Tutti",none:"Nessuno",search:"Cerca",filter:"Filtro",sort:"Ordina",refresh:"Aggiorna",download:"Scarica",upload:"Carica",uploading:"Caricamento...",uploadFailed:"Caricamento fallito",actions:"Azioni",status:"Stato",name:"Nome",description:"Descrizione",date:"Data",time:"Ora",hours:"ore",minutes:"minuti",seconds:"secondi",days:"giorni",enable:"Abilita",disable:"Disabilita",permissions:"Permessi",noPrinters:"Nessuna stampante configurata",noData:"Nessun dato disponibile",linkNotFound:"Link non trovato",required:"Obbligatorio",optional:"Opzionale",dismiss:"Chiudi",apply:"Applica",reset:"Reimposta",export:"Esporta",import:"Importa",clear:"Pulisci",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",noChange:"— Nessun cambio —",unchanged:"Invariato",unassigned:"Non assegnato",unknown:"Sconosciuto",unknownError:"Errore sconosciuto",today:"Oggi",tomorrow:"Domani",asap:"ASAP",overdue:"Scaduto",now:"Ora",collapse:"Comprimi",expand:"Espandi",viewArchive:"Vedi archivio",viewInFileManager:"Vedi nel Gestore file",addedBy:"Aggiunto da {{username}}",prints:"stampe",more:"+{{count}} altre",ascending:"Crescente",descending:"Decrescente",printer:"Stampante",remove:"Rimuovi",type:"Tipo",print:"Stampa",rename:"Rinomina",move:"Sposta",create:"Crea",duplicate:"Duplica",left:"Sinistra",right:"Destra"},printers:{title:"Stampanti",addPrinter:"Aggiungi Stampante",editPrinter:"Modifica Stampante",deletePrinter:"Elimina Stampante",printerName:"Nome Stampante",serialNumber:"Numero Seriale",ipAddress:"Indirizzo IP",accessCode:"Codice di Accesso",model:"Modello",nozzleCount:"Numero Ugelli",autoArchive:"Auto Archiviazione",status:{available:"Disponibile",idle:"Inattiva",printing:"In stampa",paused:"In pausa",offline:"Offline",problem:"Problema",error:"Errore",finished:"Finita",unknown:"Sconosciuto"},temperatures:{nozzle:"Ugello",bed:"Piatto",chamber:"Camera"},progress:"{{percent}}% completato",timeRemaining:"{{time}} rimanente",deleteConfirm:'Sei sicuro di eliminare "{{name}}"?',maintenanceOk:"Manutenzione OK",maintenanceWarning:"{{count}} avviso",maintenanceWarning_plural:"{{count}} avvisi",maintenanceDue:"{{count}} in scadenza",maintenanceDue_plural:"{{count}} in scadenza",sort:{name:"Nome",status:"Stato",model:"Modello",location:"Posizione",ascending:"Ordina crescente",descending:"Ordina decrescente"},cardSize:{small:"Schede piccole",medium:"Schede medie",large:"Schede grandi",extraLarge:"Schede extra grandi"},hideOffline:"Nascondi offline",nextAvailable:"Prossima disponibile",powerOn:"Accendi",offlinePrintersWithPlugs:"Stampanti offline con smart plug",noPrintersConfigured:"Nessuna stampante configurata",search:"Cerca stampanti...",noSearchResults:"Nessuna stampante corrisponde alla tua ricerca o ai tuoi filtri",filter:{allStatuses:"Tutti gli stati",allLocations:"Tutti i luoghi"},readyToPrint:"Pronta a stampare",external:"Esterna",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Elimina archivi stampa",noLabel:"Nessuna etichetta",printPreview:"Anteprima stampa",width:"Larghezza",height:"Altezza",noObjectsFound:"Nessun oggetto trovato",objectsLoadedOnPrintStart:"Gli oggetti sono caricati quando inizia una stampa",willBeSkipped:"Verra saltato",name:"Nome",serialCannotBeChanged:"Il numero seriale non può essere cambiato",locationHelp:"Usato per raggruppare stampanti e filtrare i lavori in coda",wifiSignal:{veryWeak:"Molto debole",weak:"Debole",fair:"Discreto",good:"Buono",excellent:"Eccellente"},maintenanceUpToDate:"Tutta la manutenzione aggiornata - Clicca per vedere",chamberLightOn:"Accendi luce camera",chamberLightOff:"Spegni luce camera",files:"File",browseFiles:"Sfoglia file stampante",autoOffAfterPrint:"Spegnimento automatico dopo stampa",autoOffExecuted:"Spegnimento automatico eseguito - accendi la stampante per reimpostare",hmsErrors:"Errori HMS",viewHmsErrors:"Vedi {{count}} errore(i) HMS",resume:"Riprendi",pause:"Pausa",stop:"Ferma",camera:"Camera",skipObject:"Salta Oggetto",reconnect:"Riconnetti",mqttDebug:"Debug MQTT",printerInformation:"Informazioni stampante",copyToClipboard:"Copia",copied:"Copiato!",state:"Stato",wifiSignalLabel:"Segnale WiFi",developerMode:"Modalità sviluppatore",enabled:"Attivato",disabled:"Disattivato",addedOn:"Aggiunta il",sdCard:"Scheda SD",inserted:"Inserita",notInserted:"Non inserita",totalPrintHours:"Ore di stampa",activeNozzle:"Attivo: ugello {{nozzle}}",nozzleRack:"Rack Ugelli",nozzleDocked:"Agganciato",nozzleMounted:"Montato",nozzleActive:"Attivo",nozzleIdle:"Inattivo",nozzleDiameter:"Diametro",nozzleType:"Tipo",nozzleStatus:"Stato",nozzleFilament:"Filamento",nozzleWear:"Usura",nozzleMaxTemp:"Temp Max",nozzleSerial:"Seriale",nozzleHardenedSteel:"Acciaio Temprato",nozzleStainlessSteel:"Acciaio Inox",nozzleTungstenCarbide:"Carburo di Tungsteno",nozzleFlow:"Flusso",nozzleHighFlow:"Alto Flusso",nozzleStandardFlow:"Standard",firmwareUpdate:"Aggiornamento Firmware",firmwareInstructions:"Sul touchscreen della stampante, vai a",firmwareNav:"Vai a",settings:"Impostazioni",firmware:"Firmware",discoverPrinters:"Trova Stampanti",searching:"Ricerca...",manualEntry:"Inserimento manuale",addFromCloud:"Aggiungi da Cloud",toast:{printerDeleted:"Stampante eliminata",missingSpoolAssignment:"Stampa avviata su {{printer}}. Mancano assegnazioni bobina per: {{slots}}",printerAdded:"Stampante aggiunta",printerUpdated:"Stampante aggiornata",failedToDelete:"Impossibile eliminare stampante",failedToAdd:"Impossibile aggiungere stampante",failedToUpdate:"Impossibile aggiornare stampante",commandSent:"Comando inviato",failedToSendCommand:"Impossibile inviare comando",turnedOn:"{{name}} accesa",failedToPowerOn:"Impossibile accendere {{name}}",scriptTriggered:"Script avviato",printStopped:"Stampa fermata",printPaused:"Stampa in pausa",printResumed:"Stampa ripresa",referenceDeleted:"Riferimento eliminato",detectionAreaSaved:"Area rilevamento salvata",failedToRunScript:"Impossibile eseguire script",failedToStopPrint:"Impossibile fermare stampa",failedToPausePrint:"Impossibile mettere in pausa stampa",failedToResumePrint:"Impossibile riprendere stampa",failedToControlChamberLight:"Impossibile controllare luce camera",failedToSetSpeed:"Impossibile impostare la velocità di stampa",failedToUpdateSetting:"Impossibile aggiornare impostazione",failedToSkipObjects:"Impossibile saltare oggetti",failedToRereadRfid:"Impossibile rileggere RFID",failedToCheckPlate:"Impossibile controllare piatto",failedToUpdateLabel:"Impossibile aggiornare etichetta",failedToDeleteReference:"Impossibile eliminare riferimento",failedToSaveDetectionArea:"Impossibile salvare area rilevamento",plateCheckEnabled:"Controllo piatto abilitato",plateCheckDisabled:"Controllo piatto disabilitato",calibrationSaved:"Calibrazione salvata!",calibrationFailed:"Calibrazione non riuscita",rfidRereadInitiated:"Rilettura RFID avviata"},connection:{connected:"Connesso",offline:"Offline"},queue:{inQueue:"{{count}} stampa in coda",inQueue_plural:"{{count}} stampe in coda"},controls:"Controlli",rfid:{reread:"Rileggi RFID"},permission:{noAdd:"Non hai il permesso di aggiungere stampanti",noEdit:"Non hai il permesso di modificare stampanti",noDelete:"Non hai il permesso di eliminare stampanti",noControl:"Non hai il permesso di controllare stampanti",noFiles:"Non hai il permesso di accedere ai file stampante",noAmsRfid:"Non hai il permesso di rileggere AMS RFID",noSmartPlugControl:"Non hai il permesso di controllare smart plug",noCamera:"Non hai il permesso di visualizzare le telecamere"},modal:{addTitle:"Aggiungi Stampante",editTitle:"Modifica Stampante",myPrinter:"La mia Stampante",selectModel:"Seleziona modello...",locationGroup:"Posizione / Gruppo (opzionale)",locationPlaceholder:"es. Officina, Ufficio, Cantina",autoArchiveLabel:"Archivia automaticamente stampe completate",fromPrinterSettings:"Dalle impostazioni della stampante",modelOptional:"Modello (opzionale)",saveChanges:"Salva modifiche"},skipObjects:{tooltip:"Salta oggetti",onlyWhilePrinting:"Salta oggetti (solo durante la stampa)",requiresMultiple:"Salta oggetti (richiede 2+ oggetti)",title:"Salta Oggetti",matchIdsInfo:"Abbina gli ID con il display della stampante",printerShowsIds:"Lo schermo mostra gli ID oggetto sul piatto",skipSelected:"Salta selezionati",skipping:"Saltando...",noObjectsSelected:"Nessun oggetto selezionato",selectObjectsToSkip:"Seleziona gli oggetti da saltare nella stampa corrente",skipped:"saltato",objectsSkipped:"Oggetti saltati",activeCount:"{{count}} attivi",waitForLayer:"Attendi il layer 2+ per saltare oggetti (attualmente layer {{layer}})",skip:"Salta",confirmTitle:"Saltare oggetto?",confirmMessage:'Sei sicuro di voler saltare "{{name}}"? Questa azione non può essere annullata.'},confirm:{deleteTitle:"Elimina Stampante",deleteMessage:'Sei sicuro di eliminare "{{name}}"? Questo rimuoverà tutte le impostazioni di connessione.',deleteArchivesNote:"Tutta la cronologia di stampa sarà eliminata definitivamente.",keepArchivesNote:"La cronologia sarà mantenuta ma non più associata a questa stampante.",stopTitle:"Ferma Stampa",stopMessage:'Sei sicuro di fermare la stampa corrente su "{{name}}"? Questo annullerà il lavoro di stampa.',stopButton:"Ferma Stampa",pauseTitle:"Pausa Stampa",pauseMessage:'Sei sicuro di mettere in pausa la stampa corrente su "{{name}}"?',pauseButton:"Pausa Stampa",resumeTitle:"Riprendi Stampa",resumeMessage:'Sei sicuro di riprendere la stampa su "{{name}}"?',resumeButton:"Riprendi Stampa",powerOnTitle:"Accendi Stampante",powerOnMessage:'Sei sicuro di accendere "{{name}}"?',powerOnButton:"Accendi",powerOffTitle:"Spegni Stampante",powerOffMessage:'Sei sicuro di spegnere "{{name}}"?',powerOffWarning:'AVVISO: "{{name}}" sta stampando! Sei sicuro di spegnere? Questo interromperà la stampa e potrebbe danneggiare la stampante.',powerOffButton:"Spegni"},bulk:{select:"Seleziona",selectAll:"Seleziona tutto",selectByLocation:"Seleziona per posizione",selected:"{{count}} selezionato/i",actions:{stop:"Ferma",pause:"Pausa",resume:"Riprendi",clearPlate:"Svuota piano",clearHMS:"Cancella notifiche"},confirm:{stopTitle:"Ferma {{count}} stampe",stopMessage:"Questo annullerà le stampe attive su {{count}} stampante/i. Questa azione non può essere annullata.",stopButton:"Ferma tutte",pauseTitle:"Pausa {{count}} stampe",pauseMessage:"Questo metterà in pausa le stampe attive su {{count}} stampante/i.",pauseButton:"Pausa tutte",clearPlateTitle:"Svuota {{count}} piani di stampa",clearPlateMessage:"Questo svuoterà il piano di stampa su {{count}} stampante/i e potrebbe avviare i lavori in coda.",clearPlateButton:"Svuota tutti"},success:"{{action}} completato su {{count}} stampante/i",partial:"{{succeeded}} riuscito/i, {{failed}} fallito/i",noneApplicable:"Nessuna stampante selezionata è nello stato corretto per questa azione",selectByState:"Seleziona per stato"},discovery:{title:"Trova Stampanti",searching:"Ricerca...",scanning:"Scansione...",scanProgress:"Scansione... {{scanned}}/{{total}}",foundPrinters:"Trovate {{count}} stampante(i)",noPrintersFound:"Nessuna stampante trovata",noPrintersFoundSubnet:"Nessuna stampante trovata nella sottorete specificata.",noPrintersFoundNetwork:"Nessuna stampante trovata sulla rete.",allConfigured:"Tutte le stampanti trovate sono già configurate.",alreadyAdded:"Già aggiunta",select:"Seleziona",manualEntry:"Inserimento manuale",addFromCloud:"Aggiungi da Cloud",subnetToScan:"Sottorete da scansionare",dockerNote:"Docker rilevato. Inserisci la sottorete della stampante in notazione CIDR. Richiede network_mode: host in docker-compose.yml.",scanSubnet:"Scansiona sottorete per stampanti",discoverNetwork:"Trova stampanti in rete",scanningSubnet:"Scansione sottorete per stampanti Bambu...",scanningNetwork:"Scansione rete...",serialRequired:"Seriale richiesto",unknown:"Sconosciuto",failedToStart:"Avvio ricerca non riuscito"},drying:{start:"Avvia essiccazione",stop:"Ferma essiccazione",temperature:"Temperatura",duration:"Durata",hours:"ore",timeRemaining:"{{time}} rimanente",active:"Essiccazione",notSupported:"Essiccazione non supportata",powerRequired:"Collegare l'alimentatore AMS per abilitare l'asciugatura",startingDrying:"Avvio essiccazione...",stoppingDrying:"Arresto essiccazione...",rotateTray:"Ruota la bobina durante l'essiccazione"},filaments:"Filamenti",openCameraOverlay:"Apri overlay camera",openCameraWindow:"Apri camera in nuova finestra",firmwareUpdateAvailable:"Aggiornamento firmware disponibile: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Aggiornato",firmwareUpdateButton:"Aggiorna",plateDetection:{noPermission:"Non hai il permesso di aggiornare le stampanti",enabledClick:"Controllo piatto abilitato - Clicca per disabilitare",disabledClick:"Controllo piatto disabilitato - Clicca per abilitare",manageCalibration:"Gestisci calibrazione rilevamento piatto",calibrationRequired:"Calibrazione richiesta",calibrationInstructions:"Assicurati che il piatto sia <strong>completamente vuoto</strong>, poi clicca Calibra.",calibrationDescription:"La calibrazione salva un'immagine di riferimento del piatto vuoto. I controlli futuri confronteranno con questo riferimento per rilevare oggetti.",calibrationTip:"<strong>Suggerimento:</strong> Puoi salvare fino a 5 calibrazioni per piatti diversi. Il sistema usa automaticamente la migliore corrispondenza durante il controllo.",plateEmpty:"Il piatto sembra vuoto",objectsDetected:"Oggetti rilevati sul piatto",confidence:"Confidenza",difference:"Differenza",analysisPreview:"Anteprima analisi:",analysisLegend:"Riquadro verde = area rilevamento, overlay rosso = differenze dalla calibrazione",savedReferences:"Riferimenti salvati ({{count}}/{{max}})",deleteReference:"Elimina riferimento",labelPlaceholder:"Etichetta...",clickToEdit:"{{label}} - Clicca per modificare",clickToAddLabel:"Clicca per aggiungere etichetta"},speed:{title:"Velocità di stampa",silent:"Silenzioso (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},fans:{partCooling:"Ventola raffreddamento parte",auxiliary:"Ventola ausiliaria",chamber:"Ventola camera"},clickToViewHmsErrors:"Clicca per vedere errori HMS",estimatedCompletion:"Tempo completamento stimato",plateNumber:"Piastra {{number}}",slotOptions:"Opzioni slot",amsPopup:{friendlyName:"Nome AMS",friendlyNamePlaceholder:"es. Nome AMS amichevole",serialNumber:"Numero di serie",firmwareVersion:"Firmware",save:"Salva",clear:"Cancella",noEditPermission:"Non hai il permesso di rinominare le unità AMS"},firmwareModal:{title:"Aggiornamento Firmware",titleUpToDate:"Info Firmware",currentVersion:"Corrente:",latestVersion:"Ultima:",releaseNotes:"Note di rilascio",checkingPrereqs:"Controllo prerequisiti...",sdCardReady:"SD pronta. Clicca sotto per caricare firmware.",uploadedSuccess:"Firmware caricato su SD!",applyInstructions:"Per applicare l'aggiornamento sulla stampante:",step1:"Sul touchscreen della stampante, vai a <strong>Impostazioni</strong>",step2:"Vai a <strong>Firmware</strong>",step3:"Seleziona <strong>Aggiorna da SD</strong>",step4:"L'aggiornamento richiede 10-20 minuti",done:"Fatto",starting:"Avvio...",uploadFirmware:"Carica Firmware",uploadFailed:"Avvio caricamento fallito: {{error}}",uploadedToast:"Firmware caricato! Avvia aggiornamento dal display."},accessCodePlaceholder:"Lascia vuoto per mantenere quello attuale",roi:{title:"Area di rilevamento (ROI)",xStart:"X Inizio",yStart:"Y Inizio",width:"Larghezza",height:"Altezza",instruction:"Regola l'area di rilevamento per focalizzare il piatto. Il riquadro verde mostra l'area corrente."},developerModeWarning:"La modalità sviluppatore LAN non è attivata su: {{names}}. Alcune funzionalità potrebbero non funzionare.",howToEnable:"Come attivare",incompatibleFile:"Questo file è stato preparato per {{slicedFor}}, ma questa stampante è una {{printerModel}}",dropNotPrintable:"Solo i file .gcode e .gcode.3mf possono essere stampati",dropToPrint:"Rilascia per stampare",cannotPrint:"Stampante occupata"},archives:{title:"Archivi di stampa",searchPlaceholder:"Cerca archivi...",filterByPrinter:"Filtra per stampante",filterByStatus:"Filtra per stato",sortBy:"Ordina per",sortNewest:"Più recenti",sortOldest:"Meno recenti",sortName:"Nome",sortDuration:"Durata",sortLargest:"Più grandi",sortSmallest:"Più piccoli",sortSize:"Dimensione",noArchives:"Nessun archivio trovato",noArchivesSearch:"Nessun archivio corrisponde alla ricerca",originalPrintNotVisible:"Stampa originale non visibile - prova a rimuovere i filtri",noArchivesYet:"Nessun archivio ancora",prints:"stampe",pagination:{showing:"Mostrando",to:"a",of:"di",show:"Mostra",page:"Pagina",all:"Tutti"},loadingArchives:"Caricamento archivi...",releaseToUpload:"Rilascia per caricare",showAll:"Mostra tutti",showFavoritesOnly:"Solo preferiti",gridView:"Vista griglia",listView:"Vista elenco",calendarView:"Vista calendario",logView:"Registro stampe",manageTags:"Gestisci tag",showFailedPrints:"Mostra stampe fallite",hideFailedPrints:"Nascondi stampe fallite",hideDuplicates:"Nascondi duplicati",viewOriginalPrint:"Fai clic per visualizzare la stampa originale (#{{id}})",printTime:"Tempo di stampa",filamentUsed:"Filamento usato",cost:"Costo",reprint:"Ristampa",preview:"Anteprima",deleteArchive:"Elimina archivio",deleteConfirm:"Sei sicuro di eliminare questo archivio?",favorite:"Preferito",unfavorite:"Rimuovi dai preferiti",viewDetails:"Vedi dettagli",status:{completed:"Completato",failed:"Fallito",stopped:"Fermato"},toast:{source3mfAttached:"Sorgente 3MF allegata: {{filename}}",failedUploadSource3mf:"Caricamento sorgente 3MF non riuscito",source3mfRemoved:"Sorgente 3MF rimossa",failedRemoveSource3mf:"Rimozione sorgente 3MF non riuscita",f3dAttached:"F3D allegato: {{filename}}",failedUploadF3d:"Caricamento F3D non riuscito",f3dRemoved:"F3D rimosso",failedRemoveF3d:"Rimozione F3D non riuscita",timelapseAttached:"Timelapse allegato: {{filename}}",timelapseAlreadyAttached:"Timelapse già allegato",noMatchingTimelapse:"Nessun timelapse corrispondente",failedScanTimelapse:"Scansione timelapse non riuscita",failedAttachTimelapse:"Allegato timelapse non riuscito",timelapseRemoved:"Timelapse rimosso",failedRemoveTimelapse:"Impossibile rimuovere il timelapse",timelapseUploaded:"Timelapse caricato: {{filename}}",failedUploadTimelapse:"Impossibile caricare il timelapse",archiveDeleted:"Archivio eliminato",failedDeleteArchive:"Eliminazione archivio non riuscita",addedToFavorites:"Aggiunto ai preferiti",removedFromFavorites:"Rimosso dai preferiti",projectUpdated:"Progetto aggiornato",failedUpdateProject:"Aggiornamento progetto non riuscito",linkCopied:"Link copiato negli appunti",failedCopyLink:"Copia link non riuscita",photoDeleted:"Foto eliminata",failedDeletePhoto:"Eliminazione foto non riuscita",failedDeleteArchives:"Eliminazione archivi non riuscita",failedUpdateFavorites:"Aggiornamento preferiti non riuscito",exportDownloaded:"Export scaricato",exportFailed:"Export non riuscito"},menu:{print:"Stampa",schedule:"Programma",openInBambuStudio:"Apri nello slicer",slice:"Slice",externalLink:"Link esterno",viewOnMakerWorld:"Vedi su MakerWorld",preview3d:"Anteprima 3D",viewTimelapse:"Vedi Timelapse",scanForTimelapse:"Cerca Timelapse",uploadTimelapse:"Carica timelapse",removeTimelapse:"Rimuovi timelapse",downloadSource3mf:"Scarica Sorgente 3MF",uploadSource3mf:"Carica Sorgente 3MF",replaceSource3mf:"Sostituisci Sorgente 3MF",removeSource3mf:"Rimuovi Sorgente 3MF",uploadF3d:"Carica F3D",replaceF3d:"Sostituisci F3D",downloadF3d:"Scarica F3D",removeF3d:"Rimuovi F3D",download:"Scarica",copyDownloadLink:"Copia link download",qrCode:"QR Code",viewPhotos:"Vedi foto",viewPhotosCount:"Vedi foto ({{count}})",projectPage:"Pagina progetto",addToFavorites:"Aggiungi ai preferiti",removeFromFavorites:"Rimuovi dai preferiti",edit:"Modifica",goToProject:"Vai al progetto: {{name}}",addToProject:"Aggiungi al progetto",removeFromProject:"Rimuovi dal progetto",loading:"Caricamento...",noProjectsAvailable:"Nessun progetto disponibile",select:"Seleziona",deselect:"Deseleziona",delete:"Elimina"},permission:{noReprint:"Non hai il permesso di ristampare questo archivio",noAddToQueue:"Non hai il permesso di aggiungere alla coda",noUpdateArchives:"Non hai il permesso di aggiornare archivi",noUploadFiles:"Non hai il permesso di caricare file",noDownload:"Non hai il permesso di scaricare archivi",noCopyLink:"Non hai il permesso di copiare link download",noDelete:"Non hai il permesso di eliminare questo archivio",noCreate:"Non hai il permesso di creare archivi"},card:{previousPlate:"Piatto precedente",nextPlate:"Piatto successivo",plateNumber:"Piatto {{index}}",moreOptions:"Clic destro per altre opzioni",addToFavorites:"Aggiungi ai preferiti",removeFromFavorites:"Rimuovi dai preferiti",cancelled:"annullato",failed:"fallito",duplicate:"duplicato",duplicateTitle:"Questo modello è stato stampato prima",openSource3mf:"Apri sorgente 3MF in Bambu Studio (clic destro per altre opzioni)",downloadF3d:"Scarica file design Fusion 360",viewTimelapse:"Vedi timelapse",viewPhoto:"Vedi 1 foto",viewPhotos:"Vedi {{count}} foto",openFolder:"Apri cartella: {{name}}",slicedFile:"File slice - pronto a stampare",sourceFile:"Solo file sorgente - nessuna mappatura AMS disponibile",gcode:"GCODE",source:"SOURCE",project:"Progetto: {{name}}",estimated:"Stimato: {{time}}",actual:"Reale: {{time}}",accuracy:"Accuratezza: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} strato",layers:"{{count}} strati",object:"{{count}} oggetto",objects:"{{count}} oggetti",slicedFor:"Sliced per {{model}}",uploadedBy:"Caricato da",noPermissionReprint:"Non hai il permesso di ristampare",noFileForReprint:"Nessun file 3MF disponibile — il file non è stato scaricato dalla stampante durante la registrazione",noPermissionEdit:"Non hai il permesso di modificare archivi",noPermissionDelete:"Non hai il permesso di eliminare archivi",reprint:"Ristampa",schedulePrint:"Programma Stampa",schedule:"Programma",openInBambuStudio:"Apri nello slicer",openInBambuStudioToSlice:"Apri nello slicer per slicing",slice:"Slice",externalLink:"Link esterno",makerWorld:"MakerWorld: {{designer}}",viewProject:"Vedi progetto",noExternalLink:"Nessun link esterno",preview3d:"Anteprima 3D",download:"Scarica",edit:"Modifica",delete:"Elimina"},modal:{deleteArchive:"Elimina Archivio",deleteConfirm:'Sei sicuro di eliminare "{{name}}"? Questa azione non può essere annullata.',deleteButton:"Elimina",removeSource3mf:"Rimuovi Sorgente 3MF",removeSource3mfConfirm:'Sei sicuro di rimuovere il file sorgente 3MF da "{{name}}"? Questo eliminerà il progetto slicer originale.',removeButton:"Rimuovi",removeF3d:"Rimuovi F3D",removeF3dConfirm:'Sei sicuro di rimuovere il file Fusion 360 da "{{name}}"?',removeTimelapse:"Rimuovi timelapse",removeTimelapseConfirm:'Sei sicuro di voler rimuovere il video timelapse da "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Seleziona Timelapse",selectTimelapseDesc:"Nessun abbinamento automatico trovato. Seleziona il timelapse per questa stampa:",deleteArchives:"Elimina Archivi",deleteArchivesConfirm:"Sei sicuro di eliminare {{count}} archivio(i)? Questa azione non può essere annullata.",deleteCount:"Elimina {{count}}"},page:{title:"Archivi",printsCount:"{{filtered}} di {{total}} stampe",dropFilesHere:"Rilascia file .3mf qui",releaseToUpload:"Rilascia per caricare",only3mfSupported:"Solo file .3mf supportati",close:"Chiudi",selected:"{{count}} selezionati",selectAll:"Seleziona tutto",tags:"Tag",project:"Progetto",favorite:"Preferito",delete:"Elimina",toggledFavorites:"Preferiti aggiornati per {{count}} archivio(i)",failedUpdateFavorites:"Aggiornamento preferiti non riuscito",archivesDeleted:"{{count}} archivio(i) eliminati",failedDeleteArchives:"Eliminazione archivi non riuscita",photoDeleted:"Foto eliminata",failedDeletePhoto:"Eliminazione foto non riuscita"},list:{name:"Nome",printer:"Stampante",date:"Data",size:"Dimensione",actions:"Azioni",hasTimelapse:"Ha timelapse"},log:{date:"Data",printName:"Nome stampa",printer:"Stampante",user:"Utente",status:"Stato",duration:"Durata",filament:"Filamento",allPrinters:"Tutte le stampanti",allUsers:"Tutti gli utenti",allStatuses:"Tutti gli stati",cancelled:"Annullato",skipped:"Saltato",dateFrom:"Dal",dateTo:"Al",noEntries:"Nessuna voce di registro trovata",showing:"{{count}} di {{total}} voci",rowsPerPage:"Righe",page:"Pagina",prev:"Prec.",next:"Succ.",clearLog:"Cancella registro",clearLogTitle:"Cancella registro stampe",clearLogConfirm:"Tutte le voci del registro di stampa verranno eliminate permanentemente. Gli archivi e gli elementi della coda non sono interessati. Questa azione non può essere annullata. Sei sicuro?",clearLogButton:"Cancella tutto",cleared:"{{count}} voci di registro cancellate",clearFailed:"Impossibile cancellare il registro stampe"}},queue:{title:"Coda di stampa",subtitle:"Programma e gestisci i tuoi lavori di stampa",addToQueue:"Aggiungi alla coda",print:"Stampa",reprint:"Ristampa",schedulePrint:"Programma Stampa",editQueueItem:"Modifica elemento coda",printToPrinters:"Stampa su {{count}} Stampanti",queueToPrinters:"Metti in coda su {{count}} Stampanti",queueSelectedPlates:"Metti in coda {{count}} piastre",selectAllPlates:"Seleziona tutte le {{count}} piastre",deselectAll:"Deseleziona tutto",printQueued:"Stampa in coda",itemsQueued:"{{count}} elementi in coda",sending:"Invio...",sendingProgress:"Invio {{current}}/{{total}}...",adding:"Aggiunta...",addingProgress:"Aggiunta {{current}}/{{total}}...",savingProgress:"Salvataggio {{current}}/{{total}}...",clearQueue:"Svuota coda",clearHistory:"Svuota cronologia",emptyQueue:"La coda è vuota",position:"Posizione",scheduledTime:"Ora programmata",moveUp:"Sposta su",moveDown:"Sposta giù",startNow:"Avvia ora",printingInProgress:"Stampa in corso...",viewArchive:"Vedi archivio",viewInFileManager:"Vedi nel Gestore file",itemCount:"{{count}} elemento",itemCount_plural:"{{count}} elementi",dragToReorder:"Trascina per riordinare (solo ASAP)",reorderHint:"La posizione influisce solo sugli elementi ASAP. Quelli programmati partono all'orario.",sjf:{label:"SJF",tooltip:"Lavoro più breve prima — lo scheduler dà priorità alle stampe più brevi"},addedBy:"Aggiunto da {{name}}",nextInQueue:"Prossimo in coda",clearPlate:"Libera piatto e avvia il prossimo",clearPlateSuccess:"Piatto liberato — pronto per la prossima stampa",plateReady:"Piatto liberato — pronto per la prossima stampa",plateNumber:"Piatto {{index}}",quantity:"Quantità",quantityHint:"Crea {{count}} elementi in coda",activeBatches:"Lotti attivi",batchProgress:"{{completed}} di {{total}} completati",cancelBatch:"Annulla rimanenti",batchCancelled:"Elementi rimanenti del lotto annullati",cancelBatchConfirmTitle:"Annulla lotto",cancelBatchConfirmMessage:"Annullare tutti gli elementi in sospeso rimanenti in questo lotto?",batch:"Lotto",sections:{currentlyPrinting:"In stampa",queued:"In coda",history:"Cronologia"},status:{pending:"In attesa",waiting:"In attesa",printing:"In stampa",paused:"In pausa",completed:"Completato",failed:"Fallito",skipped:"Saltato",cancelled:"Annullato"},summary:{printing:"In stampa",queued:"In coda",totalTime:"Tempo totale coda",totalWeight:"Peso totale della coda",history:"Cronologia"},filter:{allPrinters:"Tutte le stampanti",unassigned:"Non assegnato",allStatus:"Tutti gli stati",allLocations:"Tutte le posizioni",any:"Qualsiasi"},sort:{byPosition:"Ordina per posizione",byName:"Ordina per nome",byPrinter:"Ordina per stampante",bySchedule:"Ordina per programma",byDate:"Ordina per data",ascendingOldest:"Crescente (più vecchi)",descendingNewest:"Decrescente (più recenti)"},badges:{staged:"In staging",requiresPrevious:"Richiede successo precedente",autoPowerOff:"Spegnimento automatico",gcodeInjection:"G-code"},empty:{title:"Nessuna stampa programmata",description:`Programma una stampa dalla pagina Archivi usando l'opzione "Programma" nel menu contestuale, o trascina i file per iniziare.`},time:{asap:"ASAP",overdue:"Scaduto",now:"Ora",lessThanMinute:"Tra meno di un minuto",inMinutes:"Tra {{count}} min",inHours:"Tra {{count}} ore"},actions:{stopPrint:"Ferma Stampa",startPrint:"Avvia Stampa",requeue:"Rimetti in coda"},bulkEdit:{title:"Modifica {{count}} elemento",title_plural:"Modifica {{count}} elementi",description:"Solo le impostazioni modificate saranno applicate agli elementi selezionati.",printer:"Stampante",noChange:"— Nessun cambio —",queueOptions:"Opzioni coda",staged:"In staging (avvio manuale)",autoPowerOff:"Spegnimento automatico dopo stampa",requirePrevious:"Richiede successo precedente",printOptions:"Opzioni stampa",bedLevelling:"Livellamento piatto",flowCalibration:"Calibrazione flusso",vibrationCalibration:"Calibrazione vibrazioni",layerInspection:"Controllo primo layer",timelapse:"Timelapse",useAms:"Usa AMS",applyChanges:"Applica modifiche",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",selected:"{{count}} selezionati",editSelected:"Modifica selezionati",cancelSelected:"Annulla selezionati"},confirm:{cancelTitle:"Annulla stampa programmata",cancelMessage:'Sei sicuro di annullare "{{name}}"?',stopTitle:"Ferma Stampa",stopMessage:'Sei sicuro di fermare la stampa corrente "{{name}}"? Questo annullerà il lavoro sulla stampante.',removeTitle:"Rimuovi dalla cronologia",removeMessage:'Sei sicuro di rimuovere "{{name}}" dalla cronologia coda?',clearHistoryTitle:"Svuota cronologia",clearHistoryMessage:"Sei sicuro di rimuovere {{count}} elemento(i) dalla cronologia?",cancelButton:"Annulla Stampa",stopButton:"Ferma Stampa",thisPrint:"questa stampa",thisItem:"questo elemento"},toast:{cancelled:"Elemento coda annullato",cancelFailed:"Annullamento non riuscito",removed:"Elemento coda rimosso",removeFailed:"Rimozione non riuscita",stopped:"Stampa fermata",stopFailed:"Impossibile fermare stampa",released:"Stampa rilasciata in coda",startFailed:"Avvio stampa non riuscito",reorderFailed:"Riordino coda non riuscito",historyCleared:"Cancellati {{count}} elementi cronologia",clearHistoryFailed:"Svuotamento cronologia non riuscito",updateFailed:"Aggiornamento elementi non riuscito",bulkCancelled:"Annullati {{count}} elementi",bulkCancelFailed:"Annullamento elementi non riuscito"},timeline:{listView:"Lista",timelineView:"Cronologia",unassigned:"Non assegnato",noData:"Nessuna stampa programmata per questo giorno",allDoneBy:"Tutte le stampe completate entro le {{time}}",staged:"In attesa",filterAll:"Mostra tutto",filterPrinting:"In stampa",filterQueued:"In coda",time:{anyMoment:"a momenti",minutesLeft:"{{minutes}}m rimanenti",hoursLeft:"{{hours}}h rimanenti",hoursMinutesLeft:"{{hours}}h {{minutes}}m rimanenti"},day:{previous:"Giorno precedente",next:"Giorno successivo",today:"Oggi"}},permissions:{noStopPrint:"Non hai il permesso di fermare stampe",noStartPrint:"Non hai il permesso di avviare stampe",noEdit:"Non hai il permesso di modificare questo elemento coda",noCancel:"Non hai il permesso di annullare questo elemento coda",noRequeue:"Non hai il permesso di rimettere in coda elementi",noRemove:"Non hai il permesso di rimuovere questo elemento coda",noClearHistory:"Non hai il permesso di svuotare tutta la cronologia",noEditItems:"Non hai il permesso di modificare elementi coda",noCancelItems:"Non hai il permesso di annullare elementi coda"}},backgroundDispatch:{unknownFile:"File sconosciuto",unknownPrinter:"Stampante sconosciuta",startingPrints:"Avvio stampe",progressSummary:"{{complete}}/{{total}} completati • Inviati: {{dispatched}} • In elaborazione: {{processing}}",expandDetails:"Espandi dettagli dispatch",collapseDetails:"Comprimi dettagli dispatch",dismissToast:"Chiudi notifica dispatch",cancelDispatchJob:"Annulla job dispatch",cancel:"Annulla",cancelling:"Annullamento…",status:{dispatched:"Inviato",processing:"In elaborazione",completed:"Completato",failed:"Fallito",cancelled:"Annullato"},toast:{cancellingUpload:"Annullamento upload...",cancelled:"Dispatch annullato",cancelFailed:"Impossibile annullare il dispatch",completeWithFailures:"Dispatch in background completato: {{completed}} riusciti, {{failed}} falliti",completeSuccess:"Dispatch in background completato: {{completed}} riusciti",printStartedRemaining:"{{completed}} stampa/e avviata/e, {{remaining}} in invio..."}},stats:{title:"Dashboard",subtitle:"Trascina i widget per riordinare. Clicca l'icona occhio per nascondere.",overview:"Panoramica",totalPrints:"Stampe totali",successRate:"Tasso di successo",totalPrintTime:"Tempo totale di stampa",printTime:"Tempo di stampa",totalFilament:"Filamento totale usato",filamentUsed:"Filamento usato",filamentCost:"Costo filamento",totalCost:"Costo totale",energyUsed:"Energia usata",energyCost:"Costo energia",averagePrintTime:"Tempo medio di stampa",printsPerDay:"Stampe al giorno",byPrinter:"Per stampante",printsByPrinter:"Stampe per stampante",byMaterial:"Per materiale",byMonth:"Per mese",last7Days:"Ultimi 7 giorni",last30Days:"Ultimi 30 giorni",last90Days:"Ultimi 90 giorni",allTime:"Sempre",quickStats:"Statistiche rapide",printActivity:"Attivita di stampa",filamentTypes:"Tipi di filamento",filamentTrends:"Trend filamento",failureAnalysis:"Analisi guasti",timeAccuracy:"Accuratezza tempo",successful:"Riuscite:",failed:"Fallite:",perfectEstimate:"100% = stima perfetta",noTimeAccuracyData:"Nessun dato accuratezza tempo",noFilamentData:"Nessun dato filamento",noPrinterData:"Nessun dato stampante",noPrintData:"Nessun dato stampa",noPrintDataLast30Days:"Nessun dato stampa negli ultimi 30 giorni",failureReasons:"Cause guasto",topFailureReasons:"Cause principali",failedPrintsCount:"{{failed}} / {{total}} stampe fallite",lastWeekRate:"Settimana scorsa: {{rate}}%",resetLayout:"Reimposta layout",recalculateCosts:"Ricalcola costi",recalculateCostsHint:"Ricalcola tutti i costi archivi usando i prezzi filamento correnti",exportStats:"Esporta statistiche",exportAsCsv:"Esporta come CSV",exportAsExcel:"Esporta come Excel",hiddenCount:"{{count}} Nascosti",exportDownloaded:"Export scaricato",exportFailed:"Export non riuscito",layoutReset:"Layout reimpostato",recalculatedCosts:"Costi ricalcolati per {{count}} archivi",recalculateFailed:"Ricalcolo costi non riuscito",loadingStats:"Caricamento statistiche...",noPermissionResetLayout:"Non hai il permesso di reimpostare il layout",noPermissionRecalculate:"Non hai il permesso di ricalcolare i costi",noPrintDataInRange:"Nessun dato nel periodo selezionato",periodFilament:"Filamento utilizzato",periodCost:"Costo",avgPerPrint:"Media per stampa",usageOverTime:"Utilizzo nel tempo",filamentByWeight:"Peso",printDuration:"Durata stampa",printerUtilization:"Utilizzo stampante",filamentSuccess:"Successo per materiale",printHabits:"Abitudini di stampa",printTimeOfDay:"Ora di stampa",colorDistribution:"Distribuzione colori",noColorData:"Nessun dato colore disponibile",records:"Record",longestPrint:"Stampa più lunga",heaviestPrint:"Stampa più pesante",mostExpensivePrint:"Più costosa",busiestDay:"Giorno più attivo",successStreak:"Serie di successi",streakPrint:"stampa consecutiva",streakPrints:"{{count}} stampe consecutive",printerStats:"Statistiche stampante",hours:"ore",avgPrints:"Media stampe",noArchiveData:"Nessun dato di stampa disponibile",filamentByTime:"Tempo",avgWeight:"Media peso",avgTime:"Media tempo",filamentByPrints:"Stampe",timeframe:{today:"Oggi","this-week":"Questa settimana","this-month":"Questo mese","last-7":"Ultimi 7 giorni","last-30":"Ultimi 30 giorni","last-90":"Ultimi 90 giorni","this-year":"Quest'anno","all-time":"Tutto",custom:"Personalizzato",from:"Da",to:"A"},allUsers:"Tutti gli utenti",noUser:"Nessun utente (Sistema)",filterByUser:"Filtra per utente"},maintenance:{title:"Manutenzione",overview:"Panoramica",allOk:"Tutta la manutenzione aggiornata",dueCount:"{{count}} elemento in scadenza",dueCount_plural:"{{count}} elementi in scadenza",warningCount:"{{count}} avviso",warningCount_plural:"{{count}} avvisi",totalPrintTime:"Tempo totale di stampa",nextMaintenance:"Prossima manutenzione",nothingDue:"Niente in scadenza",tasks:"Attivita",lastPerformed:"Ultima esecuzione",interval:"Intervallo",hoursRemaining:"{{hours}}h rimanenti",hoursOverdue:"{{hours}}h in ritardo",markDone:"Segna come fatto",performMaintenance:"Esegui manutenzione",history:"Cronologia",noHistory:"Nessuna cronologia manutenzione",editPrintHours:"Modifica ore stampa",currentHours:"Ore attuali",statusTab:"Stato",settingsTab:"Impostazioni",overdueCount:"{{count}} in ritardo",dueSoonCount:"{{count}} in scadenza",dueSoon:"In scadenza",allGood:"Tutto ok",overdueBy:"In ritardo di {{duration}}",dueIn:"Scade tra {{duration}}",timeLeft:"{{duration}} rimanenti",day:"1 giorno",days:"{{count}} giorni",week:"1 settimana",weeks:"{{count}} settimane",month:"1 mese",months:"{{count}} mesi",year:"1 anno",maintenanceTypes:"Tipi di manutenzione",maintenanceTypesDescription:"Tipi di sistema e tue attivita personalizzate",addCustomType:"Aggiungi tipo personalizzato",restoreDefaults:"Ripristina attivita predefinite",intervalType:"Tipo intervallo",intervalValue:"Intervallo ({{type}})",icon:"Icona",documentationLink:"Link documentazione (opzionale)",assignToPrinters:"Assegna alle stampanti",selectAtLeastOnePrinter:"Seleziona almeno una stampante",addType:"Aggiungi tipo",custom:"Personalizzato",printHours:"Ore di stampa",calendarDays:"Giorni calendario",exampleName:"es. Sostituisci filtro HEPA",viewDocumentation:"Vedi documentazione",timeBasedInterval:"Intervallo basato sul tempo",intervalOverrides:"Override intervallo",intervalOverridesDescription:"Personalizza intervalli per stampanti specifiche",assignedToPrinters:"Assegnato alle stampanti:",noPrintersAssigned:"Nessuna stampante assegnata",addPrinterShort:"Aggiungi:",printersAssignedClick:"{{count}} stampante(i) assegnata - clicca per gestire",removeFromPrinter:"Rimuovi da questa stampante",types:{lubricateCarbonRods:"Lubrifica aste in carbonio",lubricateRails:"Lubrifica guide lineari",cleanNozzle:"Pulisci ugello/Hotend",checkBelts:"Controlla tensione cinghie",cleanBuildPlate:"Pulisci piatto",checkExtruder:"Controlla ingranaggi estrusore",checkCooling:"Controlla ventole raffreddamento",generalInspection:"Ispezione generale",cleanCarbonRods:"Pulisci aste in carbonio",lubricateSteelRods:"Lubrifica aste in acciaio",cleanSteelRods:"Pulisci aste in acciaio",cleanLinearRails:"Pulisci guide lineari",checkPtfeTube:"Controlla tubo PTFE",replaceHepaFilter:"Sostituisci filtro HEPA",replaceCarbonFilter:"Sostituisci filtro carbone",lubricateLeftNozzleRail:"Lubrifica guida ugello sinistro"},maintenanceComplete:"Manutenzione segnata come completata",typeUpdated:"Tipo manutenzione aggiornato",typeDeleted:"Tipo manutenzione eliminato",defaultsRestored:"Ripristinate {{count}} attivita predefinite",printHoursUpdated:"Ore di stampa aggiornate",printerAssigned:"Stampante assegnata",printerRemoved:"Stampante rimossa",deleteTypeConfirm:'Eliminare "{{name}}"?',deleteSystemTypeTitle:"Eliminare attività di manutenzione predefinita?",deleteSystemTypeMessage:`Sei sicuro di voler eliminare l'attività di manutenzione predefinita "{{name}}"?`,noPermissionUpdate:"Non hai il permesso di aggiornare elementi manutenzione",noPermissionPerform:"Non hai il permesso di eseguire manutenzione",noPermissionEditTypes:"Non hai il permesso di modificare tipi manutenzione",noPermissionDeleteTypes:"Non hai il permesso di eliminare tipi manutenzione",noPermissionEditHours:"Non hai il permesso di modificare ore stampa",noPermissionRemovePrinter:"Non hai il permesso di rimuovere assegnazioni stampanti",noPermissionAssignPrinter:"Non hai il permesso di assegnare stampanti",noPermissionEditIntervals:"Non hai il permesso di modificare intervalli",configureSettings:"Configura tipi e intervalli manutenzione"},settings:{title:"Impostazioni",general:"Generale",tabs:{general:"Generale",smartPlugs:"Prese smart",notifications:"Notifiche",queue:"Workflow",filament:"Filamento",network:"Rete",apiKeys:"Chiavi API",virtualPrinter:"Stampante virtuale",users:"Utenti",backup:"Backup",emailAuth:"Autenticazione Email",ldap:"LDAP"},ldap:{title:"Autenticazione LDAP",enabledDesc:"L'autenticazione LDAP è attiva",disabledDesc:"L'autenticazione LDAP è disattivata",disabledHint:"Configura e salva le impostazioni LDAP qui sotto, poi attiva.",enabled:"Autenticazione LDAP attivata",disabled:"Autenticazione LDAP disattivata",feature1:"Gli utenti possono accedere con le credenziali LDAP",feature2:"L'account amministratore locale rimane come fallback",feature3:"I gruppi LDAP vengono mappati ai gruppi BamBuddy al login",serverConfig:"Configurazione server LDAP",serverUrl:"URL del server",serverUrlHint:"Usa ldap:// per standard o ldaps:// per connessioni SSL",security:"Sicurezza",securityHint:"StartTLS aggiorna una connessione semplice a TLS. LDAPS usa TLS fin dall'inizio.",bindDn:"Bind DN (account di servizio)",bindPassword:"Password Bind",searchBase:"Base DN di ricerca",userFilter:"Filtro di ricerca utente",userFilterHint:"{username} viene sostituito con il nome utente. Usa (uid={username}) per OpenLDAP.",autoProvision:"Provisioning automatico utenti",autoProvisionHint:"Crea automaticamente un account BamBuddy al primo accesso LDAP",defaultGroup:"Gruppo predefinito",defaultGroupNone:"— Nessuno (nessun fallback) —",defaultGroupHint:"Gruppo di fallback assegnato quando un utente LDAP si autentica ma non è presente in nessun gruppo LDAP mappato. Lascia vuoto per lasciare gli utenti non mappati senza autorizzazioni.",groupMapping:"Mappatura gruppi (JSON)",groupMappingHint:"Mappa i DN dei gruppi LDAP ai gruppi BamBuddy. Gruppi disponibili: ",testConnection:"Test connessione",settingsSaved:"Impostazioni LDAP salvate",errors:{serverRequired:"L'URL del server LDAP è obbligatorio",searchBaseRequired:"Il Base DN di ricerca è obbligatorio",enableAuthFirst:"Attiva prima l'autenticazione",configureLdapFirst:"Salva prima le impostazioni LDAP"}},email:{smtpSettings:"Configurazione SMTP",smtpHost:"Server SMTP",smtpPort:"Porta SMTP",security:"Sicurezza",authentication:"Autenticazione",username:"Nome utente",password:"Password",fromEmail:"Email mittente",fromName:"Nome mittente",testConnection:"Testa connessione SMTP",testRecipient:"Email destinatario test",sendTest:"Invia email di test",sending:"Invio...",save:"Salva impostazioni",saving:"Salvataggio...",advancedAuth:"Autenticazione avanzata",advancedAuthEnabled:"L'autenticazione avanzata è abilitata",advancedAuthEnabledDesc:"Le funzionalità di gestione utenti via email sono attive. I nuovi utenti riceveranno password generate automaticamente via email e potranno reimpostare la password tramite la funzione di recupero.",advancedAuthDisabled:"L'autenticazione avanzata è disabilitata",advancedAuthDisabledDesc:"Abilita l'autenticazione avanzata per attivare le funzionalità email per la gestione utenti.",enable:"Abilita",disable:"Disabilita",feature1:"Le password vengono generate automaticamente e inviate via email ai nuovi utenti",feature2:"Gli utenti possono accedere con nome utente o email",feature3:"La funzione di recupero password è disponibile",feature4:"Gli amministratori possono reimpostare le password utente via email",errors:{requiredFields:"Compilare tutti i campi obbligatori",usernameRequired:"Il nome utente è obbligatorio quando l'autenticazione è abilitata",enterTestEmail:"Inserire un indirizzo email di test",smtpServerAndEmail:"Compilare Server SMTP e Email mittente prima di testare",usernamePasswordRequired:"Nome utente e password sono obbligatori quando l'autenticazione è abilitata",configureSmtpFirst:"Configurare e testare le impostazioni SMTP prima",enableAuthFirst:"Per utilizzare le funzionalità basate sulla posta elettronica, è necessario prima abilitare l'autenticazione."},success:{settingsSaved:"Impostazioni SMTP salvate con successo"},securityOptions:{starttls:"STARTTLS (Porta 587)",ssl:"SSL/TLS (Porta 465)",none:"Nessuna (Porta 25)"},authOptions:{enabled:"Abilitata",disabled:"Disabilitata"}},appearance:"Aspetto",notifications:"Notifiche",smartPlugs:"Prese smart",spoolman:"Spoolman",updates:"Aggiornamenti",language:"Lingua",languageDescription:"Seleziona la lingua preferita",theme:"Tema",themeLight:"Chiaro",themeDark:"Scuro",themeSystem:"Sistema",defaultView:"Vista predefinita",defaultViewDescription:"Pagina da mostrare all'apertura dell'app",checkForUpdates:"Controlla aggiornamenti",autoUpdate:"Aggiornamento automatico",currentVersion:"Versione attuale",latestVersion:"Ultima versione",upToDate:"Sei aggiornato",updateAvailable:"Aggiornamento disponibile",notificationLanguage:"Lingua notifiche",notificationLanguageDescription:"Lingua per notifiche push",bedCooledThreshold:"Soglia raffreddamento piatto",bedCooledThresholdDescription:"Temperatura sotto la quale il piatto è considerato raffreddato dopo una stampa",userNotificationsEnabled:"Notifiche utente",userNotificationsEnabledDescription:"Abilita il menu notifiche utente e le notifiche e-mail per gli eventi di stampa. Richiede l'autenticazione avanzata.",userNotificationsDisabledHint:"Abilita l'autenticazione avanzata per usare le notifiche utente.",notificationProviders:"Provider notifiche",addProvider:"Aggiungi provider",editProvider:"Modifica provider",providerType:"Tipo provider",testNotification:"Notifica di test",testSuccess:"Notifica di test inviata",testFailed:"Invio notifica di test fallito",quietHours:"Ore silenziose",quietHoursDescription:"Non disturbare in queste ore",quietHoursStart:"Inizio",quietHoursEnd:"Fine",events:{title:"Eventi notifica",printStart:"Stampa avviata",printComplete:"Stampa completata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",printProgress:"Avanzamento",printProgressDescription:"Notifica al 25%, 50%, 75%",printerOffline:"Stampante offline",printerError:"Errore stampante",filamentLow:"Filamento in esaurimento",maintenanceDue:"Manutenzione dovuta",maintenanceDueDescription:"Notifica quando serve manutenzione"},smartPlug:{title:"Prese smart",add:"Aggiungi presa smart",edit:"Modifica presa smart",name:"Nome",ipAddress:"Indirizzo IP",linkedPrinter:"Stampante collegata",autoOn:"Accensione automatica",autoOnDescription:"Accendi all'avvio stampa",autoOff:"Spegnimento automatico",autoOffDescription:"Spegni dopo il completamento",offDelay:"Ritardo spegnimento",offDelayMinutes:"Minuti dopo la stampa",offDelayTemp:"Quando ugello sotto temperatura",currentState:"Stato attuale",turnOn:"Accendi",turnOff:"Spegni"},filamentTracking:"Tracciamento filamento",filamentTrackingDesc:"Scegli come tracciare le bobine di filamento. Puoi usare l'inventario integrato o collegare un server Spoolman esterno.",filamentChecks:"Controlli filamento",disableFilamentWarnings:"Disabilita avvisi filamento",disableFilamentWarningsDesc:"Non mostrare avvisi per filamento insufficiente durante la stampa o l'accodamento",preferLowestFilament:"Preferisci il filamento con meno residuo",preferLowestFilamentDesc:"Quando più bobine corrispondono, usa quella con meno filamento rimanente",trackingModeBuiltIn:"Inventario integrato",trackingModeBuiltInDesc:"Riconoscimento RFID automatico e tracciamento dell'uso inclusi",trackingModeSpoolmanDesc:"Server esterno per la gestione del filamento",builtInFeatureRfid:"Rileva automaticamente le bobine Bambu Lab RFID nell'AMS",builtInFeatureUsage:"Traccia il consumo di filamento per stampa",builtInFeatureCatalog:"Gestisci bobine, colori e profili K-factor",builtInFeatureThirdParty:"Le bobine di terze parti possono essere assegnate alle bobine dell'inventario",amsSyncButton:"Sincronizza pesi dall'AMS",amsSyncTitle:"Sincronizza pesi bobine dall'AMS",amsSyncMessage:"Questo sovrascriverà tutti i pesi delle bobine dell'inventario con i valori attuali di percentuale rimanente dell'AMS dalle stampanti connesse. Usa questa funzione per recuperare dati di peso corrotti. Le stampanti devono essere online.",amsSyncing:"Sincronizzazione...",amsSyncSuccess:"{{synced}} bobina/e sincronizzata/e, {{skipped}} saltata/e",amsSyncError:"Impossibile sincronizzare i pesi dall'AMS",spoolmanUrl:"URL Spoolman",spoolmanUrlHint:"URL del server Spoolman (es. http://localhost:7912)",spoolmanConnected:"Connesso",spoolmanDisconnected:"Disconnesso",status:"Stato",connect:"Connetti",disconnect:"Disconnetti",howSyncWorks:"Come funziona la sincronizzazione",syncInfoRfidOnly:"Solo le bobine ufficiali Bambu Lab con RFID vengono sincronizzate",syncInfoAutoCreate:"Le nuove bobine vengono create automaticamente in Spoolman alla prima sincronizzazione",syncInfoThirdPartySkipped:"Le bobine non Bambu Lab (terze parti, ricaricate) vengono saltate",linkingExistingSpools:"Collegamento bobine esistenti",linkingExistingSpoolsDesc:`Per collegare le bobine Spoolman esistenti all'AMS, passa il mouse su uno slot AMS e clicca "Collega a Spoolman".`,syncMode:"Modalità sincronizzazione",syncModeAuto:"Automatica",syncModeManual:"Solo manuale",syncModeAutoDesc:"I dati AMS si sincronizzano automaticamente quando vengono rilevate modifiche",syncModeManualDesc:"Sincronizzazione solo quando attivata manualmente",syncAmsData:"Sincronizza dati AMS",syncAmsDataDesc:"Sincronizza manualmente i dati AMS della stampante su Spoolman",allPrinters:"Tutte le stampanti",noDefaultPrinter:"Nessuna predefinita (chiedi ogni volta)",sidebarOrder:"Ordine barra laterale",saveThumbnails:"Salva miniature",captureFinishPhoto:"Acquisisci foto finale",noPrintersConfigured:"Nessuna stampante configurata",archiveMode:{always:"Crea sempre voce archivio",never:"Non creare mai voce archivio",ask:"Chiedi ogni volta"},checkForUpdatesLabel:"Controlla aggiornamenti",checkPrinterFirmware:"Controlla firmware stampante",includeBetaUpdates:"Includi versioni beta",includeBetaUpdatesDesc:"Notifica versioni beta e prerelease durante il controllo aggiornamenti",enableRetry:"Abilita retry",homeAssistantDescription:"Controlla prese smart tramite Home Assistant",environmentManagedLabel:"(Gestito dall'ambiente)",autoEnabledViaEnv:"Abilitato automaticamente tramite variabili d'ambiente",urlFromEnvReadOnly:"Valore impostato dalla variabile d'ambiente HA_URL (sola lettura)",tokenFromEnvReadOnly:"Valore impostato dalla variabile d'ambiente HA_TOKEN (sola lettura)",mqttConnectedTo:"Connesso a",prometheusDescription:"Esponi dati stampante in formato Prometheus",noSmartPlugsTitle:"Nessuna presa smart configurata",noSmartPlugsDescription:"Aggiungi una presa smart Tasmota per monitorare energia e automatizzare il controllo.",noProvidersTitle:"Nessun provider configurato",noProvidersDescription:"Aggiungi un provider per ricevere avvisi.",noTemplatesAvailable:"Nessun template disponibile. Riavvia il backend per generare i template predefiniti.",apiPermissionView:"Visualizza stato stampante e coda",apiPermissionEdit:"Aggiungi e rimuovi elementi dalla coda di stampa",apiKeysEmptyTitle:"Nessuna chiave API",apiKeysEmptyDescription:"Crea una chiave API per integrare servizi esterni.",noUsersFound:"Nessun utente trovato",noGroupsFound:"Nessun gruppo trovato",noGroupsAvailable:"Nessun gruppo disponibile",passwordsDoNotMatch:"Le password non coincidono",systemGroupWarning:"I nomi dei gruppi di sistema non possono essere modificati",authDisabledTitle:"Autenticazione disabilitata",authDisabledFeature1:"Richiedi accesso per usare il sistema",authDisabledFeature2:"Crea più utenti con permessi basati sui gruppi",authDisabledFeature3:"Controlla accesso con 50+ permessi granulari",userHasCreated:"Questo utente ha creato:",userItemsQuestion:"Cosa vuoi fare con questi elementi?",deleteUserConfirm:"Sei sicuro di voler eliminare questo utente?",actionCannotBeUndone:"Questa azione non può essere annullata.",addFirstSmartPlug:"Aggiungi la tua prima presa smart",providers:"Provider",log:"Log",testAll:"Testa tutto",testResults:"Risultati test",testPassedCount:"{{count}} riusciti",testFailedCount:"{{count}} falliti",messageTemplates:"Template messaggi",messageTemplatesDescription:"Personalizza i messaggi per ogni evento.",apiKeys:"Chiavi API",apiKeysDescription:"Crea chiavi API per integrazioni esterne e webhook.",createKey:"Crea chiave",apiKeyCreated:"Chiave API creata con successo",apiKeyCopyWarning:"Copia questa chiave ora - non verra mostrata di nuovo!",useInApiBrowser:"Usa nel Browser API",createNewApiKey:"Crea nuova chiave API",keyName:"Nome chiave",keyNamePlaceholder:"es., Home Assistant, OctoPrint",readStatus:"Leggi stato",readStatusDescription:"Visualizza stato stampante e coda",manageQueue:"Gestisci coda",manageQueueDescription:"Aggiungi e rimuovi elementi dalla coda di stampa",controlPrinter:"Controlla stampante",controlPrinterDescription:"Metti in pausa, riprendi e ferma stampe",unnamedKey:"Chiave senza nome",lastUsed:"Ultimo uso",read:"Lettura",control:"Controllo",createFirstKey:"Crea la tua prima chiave",webhookEndpoints:"Endpoint webhook",webhookApiKeyHint:"Usa la tua chiave API nell'header X-API-Key.",webhook:{getAllStatus:"Ottieni stato di tutte le stampanti",getSpecificStatus:"Ottieni stato di una stampante",addToQueue:"Aggiungi alla coda di stampa",pausePrint:"Metti in pausa stampa",resumePrint:"Riprendi stampa",stopPrint:"Ferma stampa"},apiBrowser:"Browser API",apiBrowserDescription:"Esplora e testa tutti gli endpoint API disponibili.",apiKeyForTesting:"Chiave API per test",apiKeyPlaceholder:"Incolla qui la tua chiave API per testare gli endpoint autenticati...",apiKeyHint:"Questa chiave verra inviata come header X-API-Key.",deleteApiKeyTitle:"Elimina chiave API",deleteApiKeyMessage:"Sei sicuro di voler eliminare questa chiave API? Le integrazioni che la usano non funzioneranno più.",deleteKey:"Elimina chiave",amsDisplayThresholds:"Soglie visualizzazione AMS",amsThresholdsDescription:"Configura soglie colore per umidità e temperatura AMS.",humidity:"Umidità",goodGreen:"Buono (verde)",fairOrange:"Discreto (arancione)",aboveFairBad:"Sopra soglia discreta mostra rosso (scarso)",fairAlsoDryingThreshold:"Questa soglia viene usata anche per attivare l'asciugatura automatica",temperature:"Temperatura",goodBlue:"Buono (blu)",aboveFairHot:"Sopra soglia discreta mostra rosso (caldo)",historyRetention:"Conservazione cronologia",keepSensorHistory:"Mantieni cronologia sensori per",historyRetentionDescription:"I dati più vecchi saranno eliminati automaticamente",defaultPrintOptions:"Opzioni di stampa predefinite",defaultPrintOptionsDescription:"Imposta i valori predefiniti per le opzioni di stampa. Possono essere modificati nella finestra di stampa.",defaultBedLevelling:"Livellamento piatto",defaultBedLevellingDesc:"Livellamento automatico del piatto prima della stampa",defaultFlowCali:"Calibrazione flusso",defaultFlowCaliDesc:"Calibra il flusso di estrusione",defaultVibrationCali:"Calibrazione vibrazioni",defaultVibrationCaliDesc:"Riduce gli artefatti di ringing",defaultLayerInspect:"Ispezione primo strato",defaultLayerInspectDesc:"Ispezione IA del primo strato",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Registra un video timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Conferma piatto libero",requirePlateClear:"Richiedi conferma piatto libero",requirePlateClearDescription:"Quando abilitato, lo scheduler attende la conferma per stampante che il piatto è libero prima di avviare le stampe in coda su stampanti con lavori completati. Disabilitare per flussi di lavoro in farm dove i piatti vengono verificati fisicamente.",gcodeInjection:"Iniezione G-code",gcodeInjectionDescription:`Configura G-code personalizzato da iniettare all'inizio e/o alla fine delle stampe per sistemi di stampa automatica come Farmloop, SwapMod, AutoClear e Printflow 3D. Gli snippet sono configurati per modello di stampante e applicati quando "Inietta G-code" è abilitato su un elemento della coda.`,gcodeInjectionNoPrinters:"Nessuna stampante trovata. Aggiungi stampanti per configurare gli snippet G-code.",gcodeStartLabel:"G-code iniziale",gcodeEndLabel:"G-code finale",gcodeStartPlaceholder:"G-code inserito prima dell'inizio della stampa...",gcodeEndPlaceholder:"G-code aggiunto dopo la fine della stampa...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Asciugatura automatica",queueDryingDescription:"Asciugare automaticamente il filamento AMS quando la stampante è inattiva tra le stampe in coda. Usa la soglia di umidità sopra.",queueDryingEnabled:"Abilita asciugatura automatica",queueDryingEnabledDescription:"Avvia l'asciugatura AMS automaticamente quando la stampante è inattiva e l'umidità supera la soglia",queueDryingBlock:"Attendi completamento asciugatura",queueDryingBlockDescription:"Blocca la coda di stampa fino al completamento dell'asciugatura. Se disattivato, le stampe hanno priorità.",ambientDryingEnabled:"Asciugatura ambientale",ambientDryingEnabledDescription:"Asciuga automaticamente il filamento sulle stampanti inattive quando l'umidità supera la soglia, anche senza stampe in coda.",dryingPresets:"Preset di asciugatura",dryingPresetsDescription:"Temperatura e durata per tipo di filamento. AMS 2 Pro usa temperature più basse, AMS-HT supporta temperature più alte.",dryingFilament:"Filamento",printModal:"Modale stampa",expandCustomMapping:"Espandi mapping personalizzato di default",expandCustomMappingDescription:"Quando stampi su più stampanti, mostra mapping AMS per stampante espanso",authentication:"Autenticazione",authEnabledDescription:"La tua istanza è protetta con autenticazione",authDisabledDescription:"Abilita per richiedere accesso e gestire utenti",authDisabledMessage:"Abilita autenticazione per creare account, gestire permessi e proteggere la tua istanza Bambuddy.",enableAuthentication:"Abilita autenticazione",currentUser:"Utente corrente",changePassword:"Cambia password",admin:"Admin",users:"Utenti",addUser:"Aggiungi utente",groups:"Gruppi",addGroup:"Aggiungi gruppo",system:"Sistema",noDescription:"Nessuna descrizione",userCount:"{{count}} utenti",permissionCount:"{{count}} permessi",createUser:"Crea utente",username:"Nome utente",enterUsername:"Inserisci nome utente",password:"Password",enterPassword:"Inserisci password (min 6 caratteri)",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password",viewReleaseOnGitHub:"Vedi release su GitHub",turnAllPlugsOn:"Accendi tutte le prese",turnAllPlugsOff:"Spegni tutte le prese",clearNotificationLogs:"Cancella log notifiche",clearLogsMessage:"Questo eliminerà definitivamente tutti i log notifiche più vecchi di 30 giorni. Questa azione non può essere annullata.",clearLogs:"Cancella log",resetUiPreferences:"Reimposta preferenze UI",resetUiPreferencesMessage:"Questo reimposterà le preferenze UI ai valori predefiniti: ordine barra laterale, tema, layout dashboard, modalità vista e preferenze ordinamento. Stampanti, archivi e impostazioni server NON saranno modificati. La pagina si ricaricherà dopo la cancellazione.",resetPreferences:"Reimposta preferenze",deleteGroupTitle:"Elimina gruppo",deleteGroupMessage:"Sei sicuro di voler eliminare questo gruppo? Gli utenti in questo gruppo perderanno questi permessi.",deleteGroup:"Elimina gruppo",disableAuthenticationTitle:"Disabilita autenticazione",disableAuthenticationMessage:"Sei sicuro di voler disabilitare l'autenticazione? Questo renderà la tua istanza Bambuddy accessibile senza login. Tutti gli utenti resteranno nel database ma l'autenticazione sarà disabilitata.",disableAuthentication:"Disabilita autenticazione",configureBambuddy:"Configura Bambuddy",systemDefault:"Predefinito di sistema",archiveSettings:"Impostazioni archivio",newWindow:"Nuova finestra",embeddedOverlay:"Overlay incorporato",preferredSlicer:"Slicer preferito",preferredSlicerDescription:"Scegli quale applicazione slicer usare per aprire i file",externalCameras:"Camere esterne",costTracking:"Tracciamento costi",printsOnly:"Solo stampe",totalConsumption:"Consumo totale",dataManagement:"Gestione dati",storageUsage:"Memoria utilizzata",storageUsageDescription:"Ripartizione della memoria per categoria",storageUsageTotal:"Totale",storageUsageErrors:"Errori",storageUsageOtherBreakdown:"Altro (include risorse statiche, script e file di configurazione)",storageUsageSystem:"Sistema",storageUsageData:"Dati",storageUsageUnavailable:"Informazioni sull'utilizzo della memoria non disponibili",clearNotificationLogsDescription:"Elimina log notifiche più vecchi di 30 giorni",resetUiPreferencesDescription:"Reimposta ordine barra laterale, tema, modalità vista e preferenze layout. Stampanti, archivi e impostazioni non vengono modificati.",enableHomeAssistant:"Abilita Home Assistant",enableMqtt:"Abilita MQTT",useTls:"Usa TLS",enableMetricsEndpoint:"Abilita endpoint metriche",availableMetrics:"Metriche disponibili",editUser:"Modifica utente",deleteUserTitle:"Elimina utente",groupName:"Nome gruppo",leaveEmptyForAnonymous:"Lascia vuoto per anonimo",leaveEmptyForNoAuth:"Lascia vuoto per nessuna autenticazione",enterNewPassword:"Inserisci nuova password",confirmNewPassword:"Conferma nuova password",enterGroupName:"Inserisci nome gruppo",enterDescriptionOptional:"Inserisci descrizione (opzionale)",enterCurrentPassword:"Inserisci password attuale",enterNewPasswordMin6:"Inserisci nuova password (min 6 caratteri)",toast:{keyCopied:"Chiave copiata negli appunti",copyFailed:"Copia chiave fallita",keyAddedToBrowser:"Chiave aggiunta al Browser API",clearLogsFailed:"Eliminazione log fallita",uiPreferencesReset:"Preferenze UI reimpostate. Aggiornamento...",authDisabled:"Autenticazione disabilitata con successo",authDisableFailed:"Disabilitazione autenticazione fallita",apiKeyCreated:"Chiave API creata",apiKeyDeleted:"Chiave API eliminata",userCreated:"Utente creato con successo",userUpdated:"Utente aggiornato con successo",userDeleted:"Utente eliminato con successo",groupCreated:"Gruppo creato con successo",groupUpdated:"Gruppo aggiornato con successo",groupDeleted:"Gruppo eliminato con successo",fillRequiredFields:"Compila tutti i campi obbligatori",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri",enterGroupName:"Inserisci un nome gruppo",settingsSaved:"Impostazioni salvate",cameraSettingsSaved:"Impostazioni camera salvate",enterCameraUrl:"Inserisci un URL camera",passwordChanged:"Password cambiata con successo",connectionFailed:"Connessione fallita",testFailed:"Test fallito",cameraConnected:"Camera connessa{{resolution}}"},testConnection:"Testa connessione",catalog:{spoolCatalog:"Catalogo bobine",spoolCatalogDescription:"Pesi delle bobine vuote per marca/tipo. Utilizzato per la ricerca automatica del peso quando si aggiungono bobine.",searchCatalog:"Cerca nel catalogo...",addNewEntry:"Aggiungi nuova voce",namePlaceholder:"Nome (es. Bambu Lab - Plastica)",weight:"Peso",type:"Tipo",default:"Predefinito",custom:"Personalizzato",noMatch:"Nessuna voce corrisponde alla ricerca",empty:"Nessuna voce nel catalogo",deleteEntry:"Elimina voce",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',resetCatalog:"Ripristina catalogo",resetConfirm:"Ripristinare il catalogo ai valori predefiniti? Tutte le voci personalizzate verranno rimosse.",loadFailed:"Impossibile caricare il catalogo bobine",nameWeightRequired:"Nome e peso sono obbligatori",entryAdded:"Voce aggiunta",addFailed:"Impossibile aggiungere la voce",entryUpdated:"Voce aggiornata",updateFailed:"Impossibile aggiornare la voce",entryDeleted:"Voce eliminata",deleteFailed:"Impossibile eliminare la voce",resetSuccess:"Catalogo ripristinato ai valori predefiniti",resetFailed:"Impossibile ripristinare il catalogo",exported:"{{count}} voci esportate",imported:"{{added}} voci importate ({{skipped}} saltate)",importFailed:"Impossibile importare: formato JSON non valido",exportTooltip:"Esporta catalogo in JSON",importTooltip:"Importa catalogo da JSON",resetTooltip:"Ripristina valori predefiniti",selectedCount:"{{count}} selezionati",deleteSelected:"Elimina selezionati",bulkDeleteConfirm:"Eliminare {{count}} voci?",bulkDeleted:"{{count}} voci eliminate",bulkDeleteFailed:"Impossibile eliminare le voci"},colorCatalog:{title:"Catalogo colori",description:"Colori del filamento per produttore/materiale. Utilizzato per la ricerca automatica del colore quando si aggiungono bobine.",searchColors:"Cerca colori...",allManufacturers:"Tutti i produttori",addNewColor:"Aggiungi nuovo colore",manufacturer:"Produttore",colorName:"Nome colore",hex:"Hex",materialOptional:"Materiale (opzionale)",showing:"Visualizzazione di {{filtered}} su {{total}} colori",noMatch:"Nessun colore corrisponde alla ricerca",empty:"Nessun colore nel catalogo",deleteColor:"Elimina colore",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',resetCatalog:"Ripristina catalogo colori",resetConfirm:"Ripristinare il catalogo ai valori predefiniti? Tutti i colori personalizzati verranno rimossi.",sync:"Sincronizza",starting:"Avvio...",syncTooltip:"Sincronizza da FilamentColors.xyz (2000+ colori, potrebbe richiedere un minuto)",loadFailed:"Impossibile caricare il catalogo colori",fieldsRequired:"Produttore, nome colore e colore hex sono obbligatori",colorAdded:"Colore aggiunto",addFailed:"Impossibile aggiungere il colore",colorUpdated:"Colore aggiornato",updateFailed:"Impossibile aggiornare il colore",colorDeleted:"Colore eliminato",deleteFailed:"Impossibile eliminare il colore",resetSuccess:"Catalogo colori ripristinato ai valori predefiniti",resetFailed:"Impossibile ripristinare il catalogo",syncUpToDate:"Già aggiornato ({{count}} colori verificati)",syncComplete:"{{added}} nuovi colori aggiunti ({{skipped}} già esistenti)",syncError:"Errore di sincronizzazione",syncFailed:"Impossibile sincronizzare da FilamentColors.xyz",exported:"{{count}} colori esportati",imported:"{{added}} colori importati ({{skipped}} saltati)",importFailed:"Impossibile importare: formato JSON non valido",selectedCount:"{{count}} selezionati",deleteSelected:"Elimina selezionati",bulkDeleteConfirm:"Eliminare {{count}} colori?",bulkDeleted:"{{count}} colori eliminati",bulkDeleteFailed:"Impossibile eliminare i colori"},dateFormat:"Formato data",dateFormatUs:"US (MM/GG/AAAA)",dateFormatEu:"EU (GG/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-GG)",timeFormat:"Formato ora",timeFormat12:"12 ore (3:30 PM)",timeFormat24:"24 ore (15:30)",defaultPrinter:"Stampante predefinita",defaultPrinterDescription:"Preseleziona questa stampante per upload, ristampe e altre operazioni.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Trascina gli elementi nella barra laterale per riordinare. Ripristina l'ordine predefinito qui.",setDefault:"Imposta predefinito",sidebarOrderSetDefaultHint:"Imposta predefinito applica l'ordine attuale del menu agli utenti che non hanno ancora personalizzato il proprio.",sidebarDefaultSet:"L'ordine predefinito del menu è stato impostato.",sidebarDefaultCleared:"Ordine predefinito del menu cancellato.",sidebarDefaultFailed:"Impossibile impostare l'ordine predefinito del menu.",reset:"Ripristina",darkMode:"Modalità scura",lightMode:"Modalità chiara",active:"(attivo)",background:"Sfondo",accent:"Accento",style:"Stile",bgNeutral:"Neutro",bgWarm:"Caldo",bgCool:"Freddo",bgOled:"OLED Nero",bgSlate:"Blu ardesia",bgForest:"Verde foresta",accentGreen:"Verde",accentTeal:"Verde acqua",accentBlue:"Blu",accentOrange:"Arancione",accentPurple:"Viola",accentRed:"Rosso",styleClassic:"Classico",styleGlow:"Luminoso",styleVibrant:"Vibrante",themeToggleHint:"Passa tra modalità scura e chiara con l'icona sole/luna nella barra laterale.",autoArchivePrints:"Archiviazione automatica stampe",autoArchiveDescription:"Salva automaticamente i file 3MF al completamento delle stampe",saveThumbnailsDescription:"Estrai e salva le immagini di anteprima dai file 3MF",captureFinishPhotoDescription:"Scatta una foto dalla fotocamera della stampante al completamento della stampa",ffmpegNotInstalled:"ffmpeg non installato",ffmpegRequired:"L'acquisizione dalla fotocamera richiede ffmpeg. Installalo tramite <brew>brew install ffmpeg</brew> (macOS) o <apt>apt install ffmpeg</apt> (Linux).",camera:"Fotocamera",cameraViewMode:"Modalità visualizzazione fotocamera",cameraOverlayDescription:"La fotocamera si apre in un overlay ridimensionabile sulla schermata principale",cameraWindowDescription:"La fotocamera si apre in una finestra separata del browser",externalCamerasDescription:"Configura fotocamere esterne per sostituire la fotocamera integrata della stampante. Supporta stream MJPEG, RTSP, snapshot HTTP e fotocamere USB (V4L2). Quando abilitata, la fotocamera esterna viene usata per la vista in diretta e le foto di completamento.",cameraPlaceholderUsb:"Percorso dispositivo (/dev/video0)",cameraPlaceholderUrl:"URL fotocamera (rtsp://... o http://...)",cameraTypeMjpeg:"Stream MJPEG",cameraTypeRtsp:"Stream RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Fotocamera USB (V4L2)",cameraRotation:"Rotazione",test:"Test",connected:"Connesso",disconnected:"Disconnesso",currency:"Valuta",defaultFilamentCost:"Costo filamento predefinito (per kg)",electricityCost:"Costo elettricità per kWh",energyDisplayMode:"Modalità visualizzazione energia",energyModePrintDescription:"La dashboard mostra la somma dell'energia usata durante le stampe",energyModeTotalDescription:"La dashboard mostra l'energia totale dalle prese smart",fileManager:"Gestore file",createArchiveEntry:"Crea voce archivio durante la stampa",createArchiveEntryDescription:"Quando si stampa dal gestore file, crea opzionalmente una voce di archivio",lowDiskSpaceWarning:"Avviso spazio disco insufficiente",lowDiskSpaceDescription:"Mostra avviso quando lo spazio disco scende sotto questa soglia",printerFirmware:"Firmware stampante",checkFirmwareDescription:"Controlla aggiornamenti firmware da Bambu Lab",bambuddySoftware:"Software Bambuddy",autoCheckDescription:"Controlla automaticamente nuove versioni all'avvio",checkNow:"Controlla ora",updateAvailableVersion:"Aggiornamento disponibile: v{{version}}",releaseNotes:"Note di rilascio",updateViaDocker:"Aggiorna tramite Docker Compose:",installUpdate:"Installa aggiornamento",latestVersionRunning:"Stai usando l'ultima versione",failedToCheckUpdates:"Controllo aggiornamenti fallito: {{error}}",backupRestore:"Backup e ripristino",backupRestoreDescription:"Esporta/importa impostazioni e configura backup GitHub",goToBackup:"Vai al backup",externalUrl:"URL esterno",externalUrlDescription:"L'URL esterno dove Bambuddy è accessibile. Usato per immagini di notifica e integrazioni esterne.",bambuddyUrl:"URL Bambuddy",externalUrlHint:"Includi protocollo e porta (es. http://192.168.1.100:8000)",ftpRetry:"Riprova FTP",ftpRetryDescription:"Riprova le operazioni FTP quando il WiFi della stampante è instabile. Si applica a download 3MF, upload stampe, download timelapse e aggiornamenti firmware.",autoRetryDescription:"Riprova automaticamente le operazioni FTP fallite",retryAttempts:"Tentativi di ripetizione",retryDelay:"Ritardo ripetizione",connectionTimeout:"Timeout connessione",time_one:"{{count}} volta",time_other:"{{count}} volte",second_one:"{{count}} secondo",second_other:"{{count}} secondi",nSeconds:"{{count}} secondi",increaseForWeakWifi:"Aumenta per stampanti con WiFi debole",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Connetti a Home Assistant per controllare le prese smart tramite l'API REST HA. Supporta entità switch, light, input_boolean e script.",homeAssistantUrl:"URL Home Assistant",longLivedAccessToken:"Token di accesso a lunga durata",haTokenHint:"Crea un token in HA: Profilo → Token di accesso a lunga durata → Crea token",connectionSuccessful:"Connessione riuscita",connectionFailed:"Connessione fallita",haConnectionSuccess:"Connesso con successo a Home Assistant.",haConnectionFailed:"Connessione a Home Assistant fallita.",mqttPublishing:"Pubblicazione MQTT",mqttDescription:"Pubblica eventi BamBuddy su un broker MQTT esterno per l'integrazione con Node-RED, Home Assistant e altri sistemi di automazione.",mqttEnableDescription:"Pubblica eventi su broker MQTT esterno",brokerHostname:"Hostname broker",port:"Porta",usernameOptional:"Nome utente (opzionale)",passwordOptional:"Password (opzionale)",topicPrefix:"Prefisso topic",topicPrefixHint:"I topic saranno: {{prefix}}/printers/<serial>/status, ecc.",prometheusMetrics:"Metriche Prometheus",prometheusEndpointDescription:"Esponi metriche stampante su <code>/api/v1/metrics</code> per monitoraggio Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (opzionale)",bearerTokenHint:"Se impostato, le richieste devono includere <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Stato connessione",metricsPrinterState:"Stato stampante (idle/printing/ecc)",metricsPrintProgress:"Progresso stampa 0-100%",metricsBedTemp:"Temperatura piatto",metricsNozzleTemp:"Temperatura ugello",metricsPrintsTotal:"Stampe totali per risultato",metricsMore:"...e altro (strati, ventole, coda, consumo filamento)",smartPlugsDescription:"Connetti prese smart (Tasmota o Home Assistant) per automatizzare il controllo dell'alimentazione e monitorare il consumo energetico delle stampanti.",allOn:"Tutte accese",allOff:"Tutte spente",addSmartPlug:"Aggiungi presa smart",energySummary:"Riepilogo energia",currentPower:"Potenza attuale",plugsOnline:"{{reachable}}/{{total}} prese online",today:"Oggi",yesterday:"Ieri",total:"Totale",enablePlugsForSummary:"Abilita le prese per vedere il riepilogo energia",addNotificationProvider:"Aggiungi",systemBadge:"(Sistema)",creating:"Creazione...",changing:"Modifica...",deleteUserAndItems:"Elimina utente E i suoi elementi",deleteUserKeepItems:"Elimina utente, mantieni elementi (diventeranno senza proprietario)",ok:"OK"},notification:{printStarted:{title:"Stampa avviata",body:"{{printer}}: {{filename}} ha iniziato a stampare"},printCompleted:{title:"Stampa completata",body:"{{printer}}: {{filename}} completata con successo"},printFailed:{title:"Stampa fallita",body:"{{printer}}: {{filename}} fallita"},printStopped:{title:"Stampa interrotta",body:"{{printer}}: {{filename}} interrotta"},printProgress:{title:"Avanzamento stampa",body:"{{printer}}: {{filename}} al {{percent}}% completamento"},printerOffline:{title:"Stampante offline",body:"{{printer}} e offline"},printerError:{title:"Errore stampante",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filamento in esaurimento",body:"{{printer}}: Filamento in esaurimento"},maintenanceDue:{title:"Manutenzione dovuta",body:"{{printer}}: {{items}} richiedono attenzione"}},errors:{generic:"Qualcosa e andato storto",networkError:"Errore di rete. Controlla la connessione.",notFound:"Non trovato",unauthorized:"Non autorizzato",serverError:"Errore server",validationError:"Controlla i dati inseriti",printerConnectionFailed:"Connessione alla stampante fallita",saveFailed:"Salvataggio modifiche fallito",deleteFailed:"Eliminazione fallita",loadFailed:"Caricamento dati fallito"},hmsErrors:{title:"Errori - {{name}}",noErrors:"Nessun errore",viewOnWiki:"Vedi su Bambu Lab Wiki",clearInstructions:"Cancella gli errori sulla stampante per rimuoverli qui.",clearErrors:"Cancella errori",clearSuccess:"Errori HMS cancellati",clearFailed:"Impossibile cancellare gli errori HMS"},mqttDebug:{title:"Log debug MQTT",searchPlaceholder:"Cerca topic o payload...",noMessages:"Nessun messaggio registrato",startLoggingHint:'Clicca "Avvia logging" per iniziare a catturare messaggi MQTT',noMessagesMatch:"Nessun messaggio corrisponde al filtro",adjustFilterHint:"Prova a modificare la ricerca o i filtri",incoming:"In ingresso",outgoing:"In uscita",loggingStopped:"Logging fermato",loggingActive:"Logging attivo - i messaggi si aggiornano automaticamente",startLogging:"Avvia logging",stopLogging:"Ferma logging",clearLog:"Pulisci log",topic:"Topic",timestamp:"Timestamp",direction:"Direzione",all:"Tutti"},printerFiles:{title:"Gestore file",storageUsed:"Usato:",storageFree:"Libero:",filterPlaceholder:"Filtra file...",deleteButton:"Elimina",deleteFiles:"Elimina {{count}} file",deleteFileConfirm:'Eliminare "{{name}}"? Questa azione non può essere annullata.',deleteFilesConfirm:"Eliminare {{count}} file selezionati? Questa azione non può essere annullata.",noFiles:"Nessun file sulla stampante",loadingFiles:"Caricamento file...",failedToLoad:"Caricamento file fallito",toast:{filesDeleted:"Eliminati {{count}} file",deleteFailed:"Eliminazione fallita: {{error}}"}},confirm:{delete:"Sei sicuro di voler eliminare questo?",unsavedChanges:"Hai modifiche non salvate. Sei sicuro di voler uscire?",clearQueue:"Sei sicuro di voler svuotare la coda?"},login:{title:"Login Bambuddy",subtitle:"Accedi al tuo account",username:"Nome utente",usernamePlaceholder:"Inserisci il nome utente",usernameOrEmail:"Nome utente o email",usernameOrEmailPlaceholder:"Nome utente o @ Email",password:"Password",passwordPlaceholder:"Inserisci la password",signIn:"Accedi",signingIn:"Accesso in corso...",forgotPassword:"Hai dimenticato la password?",loginSuccess:"Accesso riuscito",loginFailed:"Accesso fallito",enterCredentials:"Inserisci nome utente e password",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"},setup:{title:"Configurazione Bambuddy",subtitle:"Configura autenticazione per la tua istanza Bambuddy",enableAuth:"Abilita autenticazione",adminAccount:"Account admin",adminAccountDesc:"Se esistono già admin, l'autenticazione verrà abilitata usando gli account esistenti. Lascia i campi sotto vuoti per usare gli admin esistenti, oppure inserisci nuove credenziali per creare un nuovo utente admin.",adminUsername:"Nome utente admin",adminPassword:"Password admin",optionalIfAdminExists:"(opzionale se esistono admin)",adminUsernamePlaceholder:"Inserisci nome utente admin (opzionale)",adminPasswordPlaceholder:"Inserisci password admin (opzionale)",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password admin",settingUp:"Configurazione...",completeSetup:"Completa configurazione",toast:{authEnabledAdminCreated:"Autenticazione abilitata e utente admin creato",authEnabledExistingAdmins:"Autenticazione abilitata usando admin esistenti",setupCompleted:"Configurazione completata",enterBothCredentials:"Inserisci nome utente e password admin, oppure lascia entrambi vuoti per usare admin esistenti",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri"}},changePassword:{title:"Cambia password",currentPassword:"Password attuale",currentPasswordPlaceholder:"Inserisci password attuale",newPassword:"Nuova password",newPasswordPlaceholder:"Inserisci nuova password (min 6 caratteri)",confirmPassword:"Conferma nuova password",confirmPasswordPlaceholder:"Conferma nuova password",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri",changing:"Modifica in corso...",success:"Password cambiata con successo",failed:"Modifica password fallita"},plateAlert:{title:"Stampa in pausa!",message:"Oggetti rilevati sul piatto. La stampa è stata messa automaticamente in pausa. Svuota il piatto e riprendi la stampa.",understand:"Ho capito"},camera:{title:"Vista camera",invalidPrinterId:"ID stampante non valido",live:"Live",snapshot:"Snapshot",restartStream:"Riavvia stream",refreshSnapshot:"Aggiorna snapshot",fullscreen:"Schermo intero",exitFullscreen:"Esci da schermo intero",connectingToCamera:"Connessione alla camera...",capturingSnapshot:"Acquisizione snapshot...",connectionLost:"Connessione persa",connectionFailed:"Connessione camera fallita",reconnecting:"Riconnessione tra {{countdown}}s... (tentativo {{attempt}}/{{max}})",reconnectNow:"Riconnetti ora",cameraUnavailable:"Camera non disponibile",cameraUnavailableDesc:"Assicurati che la stampante sia accesa e connessa.",noCamera:"Nessuna camera disponibile",retry:"Riprova",cameraStream:"Stream camera",zoomOut:"Zoom indietro",zoomIn:"Zoom avanti",resetZoom:"Reset zoom",recording:"Registrazione",startRecording:"Avvia registrazione",stopRecording:"Ferma registrazione",chamberLight:"Accendi/Spegni luce camera"},groups:{title:"Gestione gruppi",subtitle:"Gestisci gruppi permessi per controllo accesso",backToSettings:"Torna a Impostazioni",createGroup:"Crea gruppo",noPermission:"Non hai il permesso di accedere a questa pagina.",system:"Sistema",noDescription:"Nessuna descrizione",usersCount:"{{count}} utenti",permissionsCount:"{{count}} permessi",edit:"Modifica",delete:"Elimina",toast:{created:"Gruppo creato con successo",updated:"Gruppo aggiornato con successo",deleted:"Gruppo eliminato con successo",enterGroupName:"Inserisci un nome gruppo"},modal:{editGroup:"Modifica gruppo",createGroup:"Crea gruppo",cancel:"Annulla",saving:"Salvataggio...",creating:"Creazione...",saveChanges:"Salva modifiche"},form:{groupName:"Nome gruppo",groupNamePlaceholder:"Inserisci nome gruppo",systemGroupWarning:"I nomi dei gruppi di sistema non possono essere modificati",description:"Descrizione",descriptionPlaceholder:"Inserisci descrizione (opzionale)",permissions:"Permessi ({{count}} selezionati)"},deleteModal:{title:"Elimina gruppo",message:"Sei sicuro di voler eliminare questo gruppo? Gli utenti in questo gruppo perderanno questi permessi.",confirm:"Elimina gruppo"},editor:{title:"Modifica gruppo",createTitle:"Crea gruppo",search:"Cerca permessi...",selectAll:"Seleziona tutto",clearAll:"Deseleziona tutto",permissionsSelected:"{{count}} selezionati",noResults:"Nessun permesso corrisponde alla ricerca"}},users:{title:"Gestione utenti",subtitle:"Gestisci utenti e accesso alla tua istanza Bambuddy",backToSettings:"Torna a Impostazioni",createUser:"Crea utente",noPermission:"Non hai il permesso di accedere a questa pagina.",admin:"Admin",noGroups:"Nessun gruppo",active:"Attivo",inactive:"Inattivo",edit:"Modifica",delete:"Elimina",system:"Sistema",noGroupsAvailable:"Nessun gruppo disponibile",table:{username:"Nome utente",groups:"Gruppi",status:"Stato",actions:"Azioni"},toast:{created:"Utente creato con successo",updated:"Utente aggiornato con successo",deleted:"Utente eliminato con successo",fillRequired:"Compila tutti i campi obbligatori",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri"},modal:{createUser:"Crea utente",editUser:"Modifica utente",cancel:"Annulla",creating:"Creazione...",saving:"Salvataggio...",saveChanges:"Salva modifiche",advancedAuthSubtitle:"con autenticazione avanzata"},form:{username:"Nome utente",usernamePlaceholder:"Inserisci nome utente",email:"Email",emailPlaceholder:"utente@esempio.com",password:"Password",passwordPlaceholder:"Inserisci password",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password",newPasswordPlaceholder:"Inserisci nuova password",confirmNewPasswordPlaceholder:"Conferma nuova password",leaveBlankToKeep:"lascia vuoto per mantenere attuale",groups:"Gruppi",optional:"opzionale",autoGeneratedPassword:"Una password sicura verrà generata automaticamente e inviata via email all'utente.",passwordManagedByAdvancedAuth:`La password è gestita dall'autenticazione avanzata. Usa "Reimposta password" per inviare una nuova password all'utente via email.`,resetPassword:"Reimposta password",resettingPassword:"Reimpostazione password..."},deleteModal:{title:"Elimina utente",message:"Sei sicuro di voler eliminare questo utente? Questa azione non può essere annullata.",confirm:"Elimina utente"}},streamOverlay:{title:"Overlay stream",invalidPrinterId:"ID stampante non valido",cameraStream:"Stream camera",progress:"Avanzamento",eta:"ETA",printerIdle:"Stampante inattiva",printerOffline:"Stampante offline",status:{printing:"In stampa",paused:"In pausa",finished:"Completata",failed:"Fallita",idle:"Inattiva",unknown:"Sconosciuto"}},profiles:{title:"Profili",subtitle:"Gestisci preset slicer e calibrazioni pressure advance",tabs:{cloud:"Profili cloud",local:"Profili locali",kprofiles:"K-Profiles"},localProfiles:{title:"Profili locali",subtitle:"Importa e gestisci preset slicer da OrcaSlicer",import:"Importa profili",importDesc:"Trascina file .bbscfg, .bbsflmt, .orca_filament, .zip o .json qui",importing:"Importazione...",search:"Cerca preset locali...",noPresets:"Nessun preset locale ancora",badge:"Locale",edit:"Modifica",delete:"Elimina",cancel:"Annulla",deleteConfirmTitle:"Elimina preset",deleteConfirm:"Sei sicuro di voler eliminare questo preset? Questa azione non può essere annullata.",source:"Fonte",inheritsFrom:"Eredita da",filamentType:"Tipo",vendor:"Produttore",compatiblePrinters:"Stampanti",nozzleTemp:"Temp. ugello",cost:"Costo",density:"Densità",pressureAdvance:"Pressure Advance",filament:"Filamento",process:"Processo",printer:"Stampante",toast:{importSuccess:"{{count}} preset importati",importSkipped:"{{count}} preset saltati (duplicati)",importError:"{{count}} errori durante l'importazione",deleted:"Preset eliminato",updated:"Preset aggiornato"}},connectedAs:"Connesso come",logout:"Esci",noLogoutPermission:"Non hai il permesso di disconnetterti",failedToLoad:"Caricamento profili fallito",retry:"Riprova",time:{justNow:"Proprio ora",minsAgo:"{{count}}m fa",hoursAgo:"{{count}}h fa",daysAgo:"{{count}}g fa"},toast:{loggedOut:"Disconnesso"},login:{title:"Connetti a Bambu Cloud",subtitle:"Sincronizza i preset del slicer tra dispositivi",email:"Email",password:"Password",region:"Regione",regionGlobal:"Globale",regionChina:"Cina",verificationCode:"Codice di verifica",totpCode:"Codice autenticatore",checkEmail:"Controlla la tua email ({{email}}) per un codice a 6 cifre",enterTotpHint:"Inserisci il codice a 6 cifre dalla tua app autenticatore",accessToken:"Access Token",accessTokenHint:"Incolla il tuo access token Bambu Lab (da Bambu Studio)",back:"Indietro",loginButton:"Accedi",verifyButton:"Verifica",setTokenButton:"Imposta token",useToken:"Usa access token invece",useEmail:"Accedi con email invece",toast:{loggedIn:"Accesso riuscito",codeSent:"Codice di verifica inviato via email",enterTotp:"Inserisci il codice dalla tua app autenticatore",tokenSet:"Token impostato con successo"}},presets:{myPreset:"Il mio preset (modificabile)",duplicate:"Duplica",editable:"Modificabile",failedToLoadDetails:"Caricamento dettagli preset fallito",deleteConfirm:"Eliminare questo preset?",deleteWarning:'Questo eliminerà definitivamente "{{name}}" da Bambu Cloud. Questa azione non può essere annullata.',noDuplicatePermission:"Non hai il permesso di duplicare preset",noEditPermission:"Non hai il permesso di modificare preset",noDeletePermission:"Non hai il permesso di eliminare preset",types:{filament:"Preset filamento",printer:"Preset stampante",process:"Preset processo"},toast:{deleted:"Preset eliminato",created:"Preset creato",updated:"Preset aggiornato",duplicated:"Preset duplicato",fieldAdded:'Campo "{{key}}" aggiunto',exported:"Preset esportato"},baseLabel:"Base: {{name}}",currentLabel:"Corrente: {{name}}",newPreset:"Nuovo preset",editPreset:"Modifica preset",duplicatePreset:"Duplica preset",createNewPreset:"Crea nuovo preset",customizeSettings:"Personalizza le impostazioni per il nuovo preset",compareWithBase:"Confronta con base",compare:"Confronta",basePreset:"Preset base",selectBasePreset:"Seleziona preset base...",presetName:"Nome preset",myCustomPreset:"Il mio preset personalizzato",inheritsFrom:"Deriva da",dropJsonToImport:"Rilascia JSON per importare",tabs:{common:"Comune",allFields:"Tutti i campi"},availableFields:"Campi disponibili",searchFieldsPlaceholder:"Cerca campi...",noMatchingFields:"Nessun campo corrispondente",allFieldsAdded:"Tutti i campi aggiunti",addCustomField:"Aggiungi campo personalizzato",yourOverrides:"Le tue override",noOverridesYet:"Nessun override ancora",clickFieldsToAdd:"Clicca i campi a sinistra per aggiungerli",saveAsTemplate:"Salva come template",jsonTip:"Suggerimento: trascina e rilascia un file .json ovunque in questa modale per importare impostazioni"},cloudView:{searchPlaceholder:"Cerca preset...",templates:"Template",refresh:"Aggiorna",newPreset:"Nuovo preset",clearFilters:"Pulisci filtri",compareMode:"Modalita confronto",selectAnotherPreset:"Seleziona un altro preset {{type}}",clickTwoPresets:"Clicca due preset dello stesso tipo per confrontare",selectFirst:"1. Seleziona il primo",selectSecond:"2. Seleziona il secondo",compareNow:"Confronta ora",lastSynced:"Ultima sincronizzazione:",showingCount:"Mostrati {{showing}} di {{total}} preset",noPresetsFound:"Nessun preset trovato",columns:{filament:"Filamento",process:"Processo",printer:"Stampante"},noFilamentPresets:"Nessun preset filamento",noProcessPresets:"Nessun preset processo",noPrinterPresets:"Nessun preset stampante",filters:{type:"Tipo",owner:"Proprietario",printer:"Stampante",nozzle:"Ugello",filament:"Filamento",layer:"Layer",all:"Tutti",myPresets:"I miei preset",builtIn:"Integrati",process:"Processo"},noTemplatesPermission:"Non hai il permesso di gestire i template",noRefreshPermission:"Non hai il permesso di aggiornare i profili",noCreatePermission:"Non hai il permesso di creare preset"},templates:{title:"Template rapidi",noTemplates:"Nessun template ancora",createFirst:"Crea template dall'editor preset",typeFilter:"Tipo:",deleteTitle:"Elimina template",deleteWarning:"Questa azione non può essere annullata",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',namePlaceholder:"Nome template",descriptionPlaceholder:"Descrizione",settingsJson:"Impostazioni (JSON)",fieldsCount:"{{count}} campi",shownInModals:"Mostrati nelle modali",hiddenInModals:"Nascosti nelle modali",apply:"Applica",toast:{deleted:"Template eliminato",updated:"Template aggiornato",created:"Template creato",applied:"Template applicato"}}},support:{debugLoggingActive:"Log debug attivo",manageLogs:"Gestisci",collectItem7:"Connettività stampante e versioni firmware",collectItem8:"Stato integrazioni (Spoolman, MQTT, HA)",collectItem9:"Interfacce di rete (solo subnet)",collectItem10:"Versioni dei pacchetti Python",collectItem11:"Controlli di integrità del database",collectItem12:"Dettagli dell'ambiente Docker"},fileManager:{title:"Gestore file",subtitle:"Organizza e gestisci i tuoi file di stampa",uploadFiles:"Carica file",newFolder:"Nuova cartella",folderName:"Nome cartella",folderNamePlaceholder:"es., Parti funzionali",renameFile:"Rinomina file",renameFolder:"Rinomina cartella",moveFiles:"Sposta {{count}} file",rootNoFolder:"Root (nessuna cartella)",current:"corrente",linkFolder:"Collega cartella",linkFolderDescription:'Collega "{{name}}" a un progetto o archivio per accesso rapido.',project:"Progetto",archive:"Archivio",noProjectsFound:"Nessun progetto trovato",noArchivesFound:"Nessun archivio trovato",unlink:"Scollega",link:"Collega",dragDropFiles:"Trascina e rilascia file qui",dropFilesHere:"Rilascia file qui",orClickToBrowse:"oppure clicca per sfogliare",allFileTypesSupported:"Tutti i tipi di file supportati. I file ZIP saranno estratti.",zipFilesDetected:"File ZIP rilevati",zipExtractOptions:"I file ZIP saranno estratti. Scegli come gestire la struttura cartelle:",preserveZipStructure:"Mantieni struttura cartelle dal ZIP",createFolderFromZip:"Crea cartella dal nome ZIP",stlThumbnailGeneration:"Generazione miniature STL",zipMayContainStl:"I file ZIP possono contenere STL. Le miniature possono essere generate durante l'estrazione.",thumbnailsCanBeGenerated:"Le miniature possono essere generate per file STL. I modelli grandi possono richiedere più tempo.",generateThumbnailsForStl:"Genera miniature per file STL",threemfDetected:"File 3MF rilevati",threemfExtractionInfo:"Modello stampante, materiale, colore e impostazioni stampa saranno estratti automaticamente dai file 3MF.",willBeExtracted:"Sara estratto",filesExtracted:"{{count}} file estratti",uploadComplete:"Caricamento completato: {{succeeded}} riusciti",uploadFailed:"Caricamento fallito",zipFilesFailed:"{{count}} file falliti",uploading:"Caricamento...",changeLink:"Cambia collegamento...",linkTo:"Collega a...",linkToProjectOrArchive:"Collega a progetto o archivio",addToQueue:"Aggiungi alla coda",schedulePrint:"Pianifica",generateThumbnail:"Genera miniatura",generateThumbnails:"Genera miniature",generateThumbnailsForMissing:"Genera miniature per STL senza miniatura",gridView:"Vista griglia",listView:"Vista elenco",lowDiskSpaceWarning:"Avviso spazio disco basso",lowDiskSpaceDetails:"Solo {{free}} liberi su {{total}} totali. La soglia e {{threshold}} GB nelle impostazioni.",files:"File",folders:"Cartelle",size:"Dimensione",free:"Libero",allFiles:"Tutti i file",wrap:"A capo",enableTextWrapping:"Abilita a capo testo",disableTextWrapping:"Disabilita a capo testo",dragToResizeTooltip:"Trascina per ridimensionare, doppio clic per reset",searchFiles:"Cerca file...",allTypes:"Tutti i tipi",prints:"Stampe",ascending:"Crescente",descending:"Decrescente",resultsCount:"{{showing}} di {{total}} file",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",selected:"{{count}} selezionati",adding:"Aggiunta...",loadingFiles:"Caricamento file...",folderIsEmpty:"La cartella e vuota",noFilesYet:"Nessun file ancora",folderEmptyDescription:"Carica file o sposta file in questa cartella per iniziare.",noFilesDescription:"Carica file per iniziare a organizzare i file di stampa.",noMatchingFiles:"Nessun file corrispondente",noMatchingFilesDescription:"Nessun file corrisponde ai criteri di ricerca o filtro.",clearFilters:"Pulisci filtri",printedCount:"Stampato {{count}}x",uploadedBy:"Caricato da",deleteFolder:"Elimina cartella",deleteFile:"Elimina file",deleteFilesCount:"Elimina {{count}} file",deleteFolderConfirm:"Sei sicuro di voler eliminare questa cartella? Tutti i file dentro saranno eliminati.",deleteFileConfirm:"Sei sicuro di voler eliminare questo file?",deleteFilesConfirm:"Sei sicuro di voler eliminare {{count}} file selezionati? Questa azione non può essere annullata.",deleting:"Eliminazione...",noPermissionRenameFolder:"Non hai il permesso di rinominare cartelle",noPermissionLinkFolder:"Non hai il permesso di collegare cartelle",noPermissionDeleteFolder:"Non hai il permesso di eliminare cartelle",noPermissionPrint:"Non hai il permesso di stampare",noPermissionAddToQueue:"Non hai il permesso di aggiungere alla coda",noPermissionDownload:"Non hai il permesso di scaricare file",noPermissionRenameFile:"Non hai il permesso di rinominare questo file",noPermissionGenerateThumbnail:"Non hai il permesso di generare miniature",noPermissionDeleteFile:"Non hai il permesso di eliminare questo file",noPermissionCreateFolder:"Non hai il permesso di creare cartelle",noPermissionUpload:"Non hai il permesso di caricare file",noPermissionMoveFiles:"Non hai il permesso di spostare file",noPermissionDeleteFiles:"Non hai il permesso di eliminare file",linkExternal:"Collega esterno",linkExternalFolder:"Collega cartella esterna",linkExternalFolderDescription:"Monta una directory host (NAS, USB, condivisione di rete) nel File Manager. I file non vengono copiati — vengono letti direttamente dal percorso originale.",externalFolderNamePlaceholder:"es. Stampe NAS",externalPath:"Percorso host",externalPathHelp:"Percorso assoluto della directory sull'host Docker. Deve essere montato come bind nel container.",readOnly:"Sola lettura",readOnlyHelp:"impedisce caricamenti e cancellazioni",showHiddenFiles:"Mostra file nascosti (file punto)",externalFolder:"Cartella esterna",scanFolder:"Scansiona",toast:{folderCreated:"Cartella creata",folderDeleted:"Cartella eliminata",fileDeleted:"File eliminato",filesDeleted:"Eliminati {{count}} file",filesMoved:"File spostati",folderLinked:"Cartella collegata",folderUnlinked:"Cartella scollegata",externalFolderLinked:"Cartella esterna collegata e scansionata",folderScanned:"Scansione completata: {{added}} aggiunti, {{removed}} rimossi",addedToQueue:"Aggiunti {{count}} file alla coda",addedToQueuePartial:"Aggiunti {{added}} file, {{failed}} falliti",failedToAddToQueue:"Aggiunta file fallita: {{error}}",fileRenamed:"File rinominato",folderRenamed:"Cartella rinominata",thumbnailsGenerated:"Generate {{count}} miniature",thumbnailsGeneratedPartial:"Generate {{succeeded}} miniature, {{failed}} fallite",noStlMissingThumbnails:"Nessun file STL senza miniature",failedToGenerateThumbnails:"Generazione miniature fallita: {{error}}",thumbnailGenerated:"Miniatura generata",failedToGenerateThumbnail:"Generazione miniatura fallita: {{error}}"}},projects:{title:"Progetti",subtitle:"Organizza e traccia i tuoi progetti di stampa 3D",newProject:"Nuovo progetto",editProject:"Modifica progetto",deleteProject:"Elimina progetto",projectName:"Nome progetto",description:"Descrizione",noProjects:"Nessun progetto ancora",noProjectsFiltered:"Nessun progetto {{status}}",noProjectsFilteredHelp:"Non hai progetti {{status}}. I progetti appariranno qui quando il loro stato cambia.",createFirst:"Crea il tuo primo progetto per organizzare stampe correlate, tracciare progressi e gestire i tuoi build.",createFirstButton:"Crea il tuo primo progetto",create:"Crea",files:"File",prints:"Stampe",plates:"piatti",parts:"parti",lastModified:"Ultima modifica",deleteConfirm:"Sei sicuro di voler eliminare questo progetto? Archivi e elementi in coda saranno scollegati ma non eliminati.",addFiles:"Aggiungi file",removeFile:"Rimuovi file",viewDetails:"Vedi dettagli",namePlaceholder:"es., Build Voron 2.4",descriptionPlaceholder:"Descrizione opzionale...",color:"Colore",targetPlates:"Piatti target",targetPlatesPlaceholder:"es., 25",targetPlatesHelp:"Numero di job di stampa",targetParts:"Parti target",targetPartsPlaceholder:"es., 150",targetPartsHelp:"Totale oggetti necessari",tagsLabel:"Tag (separati da virgola)",tagsPlaceholder:"es., voron, funzionale, regalo",dueDate:"Data scadenza",priority:"Priorita",priorityLow:"Bassa",priorityNormal:"Normale",priorityHigh:"Alta",priorityUrgent:"Urgente",statusActive:"Attivo",statusCompleted:"Completato",statusArchived:"Archiviato",done:"Fatto",completed:"completato",failed:"fallito",inQueue:"in coda",noPrintsYet:"Nessuna stampa ancora",printJobs:"Job di stampa (piatti)",partsPrinted:"Parti stampate",failedParts:"Parti fallite",import:"Importa",export:"Esporta",importProject:"Importa progetto",exportAll:"Esporta tutti i progetti",loading:"Caricamento progetti...",noEditPermission:"Non hai il permesso di modificare progetti",noDeletePermission:"Non hai il permesso di eliminare progetti",noCreatePermission:"Non hai il permesso di creare progetti",noImportPermission:"Non hai il permesso di importare progetti",noExportPermission:"Non hai il permesso di esportare progetti",toast:{created:"Progetto creato",updated:"Progetto aggiornato",deleted:"Progetto eliminato",imported:"Progetto importato",multipleImported:"{{count}} progetti importati",importFailed:"Import fallito",exported:"Progetti esportati (solo metadati)"}},projectDetail:{notFound:"Progetto non trovato",backToProjects:"Torna a Progetti",export:"Esporta",exportProject:"Esporta progetto",noExportPermission:"Non hai il permesso di esportare progetti",noEditPermission:"Non hai il permesso di modificare progetti",partOf:"Parte di:",priorityLabel:"Priorita:",noPrints:"Nessuna stampa in questo progetto ancora",status:{active:"Attivo",completed:"Completato",archived:"Archiviato"},priority:{low:"Bassa",normal:"Normale",high:"Alta",urgent:"Urgente"},dueDate:{overdue:"Scaduto",today:"Scade oggi",daysLeft:"{{count}} giorni rimanenti"},progress:{platesProgress:"Avanzamento piatti",partsProgress:"Avanzamento parti",printJobs:"job di stampa",parts:"parti",percentComplete:"{{percent}}% completato",remaining:"{{count}} rimanenti"},stats:{printJobs:"Job di stampa",total:"totale",failed:"{{count}} falliti",partsPrinted:"{{count}} parti stampate",printTime:"Tempo di stampa",filamentUsed:"Filamento usato"},cost:{title:"Tracciamento costi",filamentCost:"Costo filamento",energy:"Energia",totalCost:"Costo totale",total:"Totale",includesBom:"incl. distinta materiali",budget:"Budget",remaining:"Rimanente"},subProjects:{title:"Sotto-progetti ({{count}})"},notes:{title:"Note",noEditPermission:"Non hai il permesso di modificare le note",placeholder:"Aggiungi note su questo progetto...",empty:"Nessuna nota ancora. Clicca Modifica per aggiungere note."},files:{title:"File",linkFolders:"Collega cartelle dal Gestore file",forQuickAccess:"a questo progetto per accesso rapido.",fileCount:"{{count}} file",empty:"Nessuna cartella collegata. Vai a Gestore file e collega una cartella a questo progetto."},bom:{title:"Distinta materiali",acquired:"{{completed}}/{{total}} acquisiti",showAll:"Mostra tutti",hideDone:"Nascondi completati",addPart:"Aggiungi parte",noAddPermission:"Non hai il permesso di aggiungere parti",partNamePlaceholder:"Nome parte (es., viti M3x8)",partName:"Nome parte",qty:"Qta",price:"Prezzo ({{currency}})",sourcingUrlPlaceholder:"URL fornitura (opzionale)",remarksPlaceholder:"Note (opzionale)",deletePart:"Elimina parte",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',noUpdatePermission:"Non hai il permesso di aggiornare parti",noEditPermission:"Non hai il permesso di modificare parti",noDeletePermission:"Non hai il permesso di eliminare parti",totalCost:"Costo totale:",empty:"Nessuna parte nella distinta materiali. Aggiungi hardware, elettronica o altri componenti da reperire."},timeline:{title:"Timeline attivita",empty:"Nessuna attivita ancora."},template:{saveAsTemplate:"Salva come template",noCreatePermission:"Non hai il permesso di creare template"},queue:{title:"Coda",viewAll:"Vedi tutto",printing:"{{count}} in stampa",queued:"{{count}} in coda"},prints:{title:"Stampe ({{count}})"},toast:{projectUpdated:"Progetto aggiornato",partAdded:"Parte aggiunta",partRemoved:"Parte rimossa",exportFailed:"Export fallito",projectExported:"Progetto esportato",templateCreated:"Template creato"}},system:{title:"Informazioni sistema",version:"Versione",uptime:"Tempo attivo",cpuUsage:"Uso CPU",memoryUsage:"Uso memoria",diskUsage:"Uso disco",networkInfo:"Info rete",logs:"Log",debugMode:"Modalita debug",enableDebug:"Abilita log debug",disableDebug:"Disabilita log debug",downloadLogs:"Scarica log",clearLogs:"Cancella log",dockerInfo:"Info Docker",containerName:"Nome container",imageName:"Nome immagine",platform:"Piattaforma",architecture:"Architettura"},library:{title:"Libreria filamenti",addFilament:"Aggiungi filamento",editFilament:"Modifica filamento",deleteFilament:"Elimina filamento",vendor:"Produttore",material:"Materiale",color:"Colore",kFactor:"K Factor",temperature:"Temperatura",noFilaments:"Nessun filamento in libreria",deleteConfirm:"Sei sicuro di voler eliminare questo filamento?",importFromPrinter:"Importa da stampante",exportToFile:"Esporta su file"},spoolman:{title:"Integrazione Spoolman",enabled:"Spoolman abilitato",url:"URL Spoolman",connected:"Connesso",disconnected:"Non connesso",testConnection:"Testa connessione",sync:"Sincronizza",syncing:"Sincronizzazione...",lastSync:"Ultima sincronizzazione",linkToSpoolman:"Collega a Spoolman",openInSpoolman:"Apri in Spoolman",unlinkSpool:"Scollega bobina",unlinkConfirmTitle:"Scollegare bobina?",unlinkConfirmMessage:"Questo disconnetterà lo spool da Spoolman. I dati dello spool in Spoolman rimarranno invariati.",selectSpool:"Seleziona bobina",noUnlinkedSpools:"Nessuna bobina scollegata disponibile",linkSuccess:"Bobina collegata a Spoolman con successo",linkFailed:"Collegamento bobina fallito",unlinkSuccess:"Bobina scollegata da Spoolman con successo",unlinkFailed:"Impossibile scollegare la bobina",spoolId:"ID bobina",fillSourceLabel:"(Spoolman)",weight:"Peso",remaining:"Rimanente",disableWeightSync:"Disabilita sync peso stimato AMS",disableWeightSyncDesc:"Non aggiornare la capacità rimanente dalle stime AMS. Usalo se preferisci il tracciamento di Spoolman rispetto alle stime AMS. Le nuove bobine useranno comunque la stima AMS come peso iniziale.",reportPartialUsage:"Segnala uso parziale per stampe fallite",reportPartialUsageDesc:"Quando una stampa fallisce o viene annullata, segnala il filamento stimato usato fino a quel punto in base all'avanzamento layer."},inventory:{title:"Inventario Bobine",addSpool:"Aggiungi Bobina",editSpool:"Modifica Bobina",material:"Materiale",selectMaterial:"Seleziona materiale...",subtype:"Sottotipo",brand:"Marchio",searchBrand:"Cerca marchio...",useCustomBrand:'Usa "{{brand}}"',useCustomMaterial:"Usa materiale personalizzato: {{material}}",colorName:"Nome Colore",colorNamePlaceholder:"Jade White, Fire Red...",color:"Colore",hexColor:"Colore Hex",pickColor:"Scegli colore personalizzato",labelWeight:"Peso da Etichetta",coreWeight:"Peso Bobina Vuota",searchSpoolWeight:"Cerca peso bobina...",weightUsed:"Utilizzato",currentWeight:"Peso Rimanente",measuredWeight:"Peso Misurato",spoolName:"Bobina",costPerKg:"Costo per kg",measuredWeightError:"Il peso misurato deve essere compreso tra {{min}}g e {{max}}g.",slicerFilament:"Filamento Slicer",slicerFilamentName:"Nome Preset Slicer",slicerPreset:"Preset Slicer",searchPresets:"Cerca preset filamento...",selectedPreset:"Selezionato",noPresetsFound:"Nessun preset trovato",tempOverrides:"Override Temperatura",note:"Nota",notePlaceholder:"Eventuali note aggiuntive su questa bobina...",archive:"Archivia",restore:"Ripristina",noSpools:"Ancora nessuna bobina. Aggiungi la tua prima bobina per iniziare.",noManualSpools:"Nessuna bobina aggiunta manualmente disponibile. Aggiungi prima una bobina al tuo inventario.",kProfiles:"K-Profiles",addKProfile:"Aggiungi K-Profile",assignSpool:"Assegna Bobina",unassignSpool:"Scollega",assignSuccess:"Bobina assegnata e slot AMS configurato",assignFailed:"Assegnazione bobina fallita",selectSpool:"Seleziona una bobina da assegnare a questo slot",assigned:"Assegnato",assigning:"Assegnazione...",searchSpools:"Cerca bobine...",showAllSpools:"Mostra tutte le bobine",allMaterials:"Tutti i Materiali",filterByBrand:"Filtra per marchio...",showArchived:"Mostra archiviate",quickAdd:"Aggiunta rapida (Scorta)",quantity:"Quantità",stock:"Scorta",configured:"Configurata",spoolsCreated:"{{count}} bobine create",spoolCreated:"Bobina creata",spoolUpdated:"Bobina aggiornata",spoolDeleted:"Bobina eliminata",spoolArchived:"Bobina archiviata",spoolRestored:"Bobina ripristinata",deleteConfirm:"Sei sicuro di voler eliminare questa bobina? Questa azione non può essere annullata.",archiveConfirm:"Sei sicuro di voler archiviare questa bobina?",advancedSettings:"Impostazioni Avanzate",filamentInfoTab:"Info filamento",paProfileTab:"Profilo PA",filamentInfo:"Filamento",additional:"Aggiuntivo",loadingPresets:"Caricamento preset cloud...",cloudConnected:"Cloud connesso",cloudNotConnected:"Cloud non connesso (valori predefiniti)",recentColors:"Recenti",searchColors:"Cerca colori...",searchResults:"Risultati della ricerca",allColors:"Tutti i colori",commonColors:"Colori comuni",showLess:"Mostra meno",showAll:"Mostra tutto",noColorsFound:"Nessun colore corrisponde alla ricerca",noResults:"Nessun risultato trovato",selectMaterialFirst:"Selezionare prima un materiale nella scheda Info filamento.",noPrintersConfigured:"Nessuna stampante configurata. Aggiungi stampanti per usare i profili PA.",matchingFilter:"Corrispondenti",anyBrand:"Qualsiasi marca",anyVariant:"Qualsiasi variante",autoSelect:"Selezione automatica",matches:"corrispondenze",match:"corrispondenza",noMatches:"Nessuna corrispondenza",connected:"Connessa",offline:"Offline",printerOffline:"La stampante è offline. Connetti per visualizzare i profili di calibrazione.",noKProfilesMatch:"Nessun profilo K corrisponde al filamento selezionato.",leftNozzle:"Ugello sinistro",rightNozzle:"Ugello destro",profilesSelected:"profili di calibrazione selezionati",totalInventory:"Inventario totale",totalConsumed:"Totale consumato",byMaterial:"Per materiale",inPrinter:"In stampante",lowStock:"Scorta bassa",sinceTracking:"Dall'inizio del tracciamento",loadedInAms:"Caricato in AMS/Est",remaining:"Rimanente",weightCheck:"Controllo Peso",lastWeighed:"Ultima pesatura",neverWeighed:"Mai pesato",search:"Cerca bobine...",showing:"Visualizzazione",to:"a",of:"di",show:"Mostra",spools:"bobine",spool:"bobina",page:"Pagina",noSpoolsMatch:"Nessun risultato trovato",noSpoolsMatchDesc:"Prova a modificare la ricerca o i filtri per trovare quello che cerchi.",active:"Attive",archived:"Archiviate",all:"Tutte",used:"Usato",new:"Nuovo",clearFilters:"Cancella filtri",table:"Tabella",cards:"Schede",net:"Netto",groupSimilar:"Raggruppa",groupedSpools:"{{count}} bobine identiche",groupedRows:"righe",columns:"Colonne",configureColumns:"Configura colonne",configureColumnsDesc:"Trascina per riordinare le colonne o usa le frecce. Attiva/disattiva la visibilità con l'icona dell'occhio.",visible:"visibili",reset:"Ripristina",cancel:"Annulla",applyChanges:"Applica modifiche",moveUp:"Sposta su",moveDown:"Sposta giù",hideColumn:"Nascondi colonna",showColumn:"Mostra colonna",linkToSpool:"Collega a bobina",tagLinked:"Tag collegato alla bobina",tagLinkFailed:"Impossibile collegare il tag",tagAlreadyLinked:"Tag già collegato a un'altra bobina",unknownTag:"Tag RFID sconosciuto rilevato",usageHistory:"Cronologia utilizzo",noUsageHistory:"Nessun utilizzo registrato",printName:"Nome stampa",weightConsumed:"Peso consumato",clearHistory:"Cancella",historyCleared:"Cronologia utilizzo cancellata",fillSourceLabel:"(Inv)",lowStockThresholdError:"La soglia deve essere tra 0.1 e 99.9",assignMismatchTitle:"Materiale non corrispondente",assignMismatchMessage:'Il materiale della bobina selezionata "{{spoolMaterial}}" non corrisponde al materiale del vassoio "{{trayMaterial}}" per {{location}}. Assegnare comunque?',assignMismatchConfirm:"Assegna comunque",assignPartialMismatchMessage:'Il materiale della bobina "{{spoolMaterial}}" è simile ma non corrisponde esattamente a "{{trayMaterial}}" in {{location}}. Vuoi procedere?',assignProfileMismatchMessage:'Il profilo della bobina "{{spoolProfile}}" non corrisponde al profilo del vassoio "{{trayProfile}}" in {{location}}. Vuoi procedere?'},timelapse:{title:"Timelapse",create:"Crea timelapse",download:"Scarica",delete:"Elimina",preview:"Anteprima",frameRate:"Frame rate",quality:"Qualità",processing:"Elaborazione...",noTimelapses:"Nessun timelapse disponibile"},ams:{title:"AMS",slot:"Slot",empty:"Vuoto",emptySlot:"Slot vuoto",unknown:"Sconosciuto",humidity:"Umidità",temperature:"Temperatura",filamentType:"Tipo filamento",filamentColor:"Colore",remaining:"Rimanente",history:"Cronologia AMS",noHistory:"Nessuna cronologia disponibile",configureSlot:"Configura slot",externalSpool:"Bobina esterna",profile:"Profilo",kFactor:"K Factor",fill:"Livello",configure:"Configura",used:"utilizzato",remainingUnit:"rimanente"},printModal:{title:"Avvia stampa",selectPrinter:"Seleziona stampante",selectPlate:"Seleziona piatto",filamentMapping:"Mappatura filamento",totalCost:"Costo totale:",slotRemainingShort:" - {{grams}}g rim.",printSettings:"Impostazioni stampa",bedLeveling:"Livellamento piatto",flowCalibration:"Calibrazione flusso",vibrationCalibration:"Calibrazione vibrazioni",layerInspection:"Ispezione primo layer",timelapse:"Timelapse",startPrint:"Avvia stampa",addToQueue:"Aggiungi alla coda",cancel:"Annulla",noPrintersAvailable:"Nessuna stampante disponibile",printerBusy:"Stampante occupata",printerOffline:"Stampante offline",sameTypeDifferentColor:"Stesso tipo, colore diverso",filamentTypeNotLoaded:"Tipo di filamento non caricato",openCalendar:"Apri calendario",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Ugello sinistro",rightNozzleTooltip:"Ugello destro",filamentOverride:"Sostituzione filamento",filamentOverrideHint:"Sostituisci opzionalmente i filamenti per l'assegnazione basata sul modello. Lo scheduler abbinerà i filamenti selezionati invece dei valori 3MF originali.",originalFilament:"Originale",overrideWith:"Sostituisci con",resetToOriginal:"Ripristina originale",insufficientFilamentTitle:"Filamento insufficiente",insufficientFilamentMessage:"Alcune bobine assegnate hanno meno filamento rimanente di quanto necessario per questa stampa:",insufficientFilamentLine:"{{printer}} - {{slot}}: necessita di {{required}}g, rimanenti {{remaining}}g",printAnyway:"Stampa comunque",forceColorMatch:"Forza corrispondenza colore",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Scagliona a {{count}} stampanti",gcodeInjection:"Inietta G-code auto-stampa"},backup:{title:"Backup e ripristino",createBackup:"Crea backup",restoreBackup:"Ripristina backup",restoreDescription:"Sostituisci tutti i dati da un file di backup",downloadBackup:"Scarica backup",uploadBackup:"Carica backup",lastBackup:"Ultimo backup",autoBackup:"Backup automatico",backupNow:"Esegui backup ora",restoreWarning:"Avviso: il ripristino sovrascriverà tutti i dati attuali.",includeArchives:"Includi archivi",includeSettings:"Includi impostazioni",includeProfiles:"Includi profili",backupSuccess:"Backup creato con successo",restoreSuccess:"Backup ripristinato con successo",backupFailed:"Backup fallito",restoreFailed:"Ripristino fallito",restoreNote:"La stampante virtuale verrà fermata durante il ripristino",githubBackup:"Backup GitHub",enabled:"Abilitato",cloudLoginRequired:"Accesso Bambu Cloud richiesto. Accedi in Profili → Profili Cloud per abilitare il backup GitHub.",cloudLoginRequiredShort:"Accesso Cloud richiesto",githubDescription:"Sincronizza automaticamente i tuoi profili con un repository GitHub privato per backup e cronologia delle versioni.",repositoryUrl:"URL del repository",personalAccessToken:"Token di accesso personale",tokenSaved:"(salvato)",enterNewToken:"Inserisci un nuovo token per aggiornare",tokenHint:"Token a grana fine con permesso di lettura/scrittura dei contenuti",branch:"Branch",manualOnly:"Solo manuale",hourly:"Ogni ora",daily:"Giornaliero",weekly:"Settimanale",includeInBackup:"Includi nel backup",kProfiles:"K-Profili",kProfilesDescription:"Calibrazione dell'avanzamento pressione dalle stampanti connesse",noPrintersConnected:"Nessuna stampante connessa",printersConnected:"{{connected}}/{{total}} connesse",cloudProfiles:"Profili Cloud",cloudProfilesDescription:"Preset di filamento, stampante e processo da Bambu Cloud",appSettings:"Impostazioni App",appSettingsDescription:"Configurazione Bambuddy (database completo)",spoolInventory:"Inventario bobine",spoolInventoryDescription:"Bobine di filamento, cronologia utilizzo e tracciamento costi",printArchives:"Archivi di stampa",printArchivesDescription:"Metadati della cronologia di stampa (nessun file gcode/3MF)",lastBackupAt:"Ultimo backup:",noBackupsYet:"Nessun backup ancora",next:"Prossimo:",startingBackup:"Avvio del backup...",test:"Test",enableBackup:"Abilita backup",testConnection:"Testa connessione",enterRepoUrl:"Inserisci l'URL del repository",enterRepoAndToken:"Inserisci l'URL del repository e il token di accesso",repoRequired:"L'URL del repository è obbligatorio",tokenRequired:"Il token di accesso è obbligatorio",githubBackupEnabled:"Backup GitHub abilitato",tokenUpdated:"Token aggiornato",settingsSaved:"Impostazioni salvate",failedToSave:"Salvataggio fallito: {{message}}",backupCompleteFiles:"Backup completato - {{count}} file aggiornati",backupSkippedNoChanges:"Backup saltato - nessuna modifica",backupFailed2:"Backup fallito: {{message}}",clearedLogs:"{{count}} log eliminati",failedToClearLogs:"Eliminazione log fallita: {{message}}",history:"Cronologia",clear:"Cancella",date:"Data",status:"Stato",commit:"Commit",localBackup:"Backup locale",localBackupDescription:"Crea un backup completo dei tuoi dati Bambuddy includendo database, archivi, upload e tutti i file.",downloadBackupLabel:"Scarica backup",completeBackupZip:"Backup completo: database + tutti i file (ZIP)",download:"Scarica",preparingBackup:"Preparazione del backup...",creatingArchive:"Creazione dell'archivio di backup... Potrebbe richiedere del tempo per archivi di grandi dimensioni.",downloadingFile:"Download del file di backup...",backupDownloaded:"Backup scaricato con successo",failedToCreateBackup:"Creazione del backup fallita: {{message}}",restore:"Ripristina",restoreReplacesAll:"Il ripristino sostituisce tutti i dati.",restoreReplacesAllDetail:"Il database e i file attuali verranno completamente sostituiti. È necessario un riavvio dopo il ripristino.",restoreConfirmTitle:"Ripristina backup",restoreConfirmMessage:`Sei sicuro di voler ripristinare da "{{filename}}"? Questo sostituirà completamente il tuo database e tutti i file. L'applicazione dovrà essere riavviata dopo il ripristino.`,restoreConfirmButton:"Ripristina backup",uploadingFile:"Caricamento del file di backup...",backupRestoredRestart:"Backup ripristinato. Riavvia Bambuddy.",failedToRestore:"Ripristino del backup fallito. Controlla il formato del file.",reloadNow:"Ricarica ora",creatingBackup:"Creazione del backup",restoringBackup:"Ripristino del backup",preparing:"Preparazione...",processing:"Elaborazione...",doNotClosePage:"Non chiudere questa pagina e non navigare altrove. Questa operazione potrebbe richiedere diversi minuti per backup di grandi dimensioni.",restoring:"Ripristino in corso...",restoreComplete:"Ripristino completato",restoreFailed2:"Ripristino fallito",importSettings:"Importa impostazioni da un file di backup",pleaseWaitRestoring:"Attendere durante il ripristino dei dati",selectBackupFile:"Clicca per selezionare un file di backup (.json o .zip)",duplicateHandling:"Come funziona la gestione dei duplicati:",matchPrinters:"Stampanti",matchPrintersBy:"corrispondenza per numero di serie",matchSmartPlugs:"Smart Plug",matchSmartPlugsBy:"corrispondenza per indirizzo IP",matchNotificationProviders:"Provider di notifica",matchNotificationProvidersBy:"corrispondenza per nome",matchFilaments:"Filamenti",matchFilamentsBy:"corrispondenza per nome + tipo + marca",matchArchives:"Archivi",matchArchivesBy:"corrispondenza per hash del contenuto (sempre saltato)",matchPendingUploads:"Upload in sospeso",matchPendingUploadsBy:"corrispondenza per nome file",matchSettingsTemplates:"Impostazioni e modelli",matchSettingsTemplatesBy:"sempre sovrascritti",replaceExisting:"Sostituisci dati esistenti",keepExisting:"Mantieni dati esistenti",overwriteDescription:"Sovrascrivi gli elementi già esistenti con i dati del backup",keepDescription:"Ripristina solo gli elementi che non esistono ancora",overwriteCaution:"Attenzione:",overwriteWarning:"La sovrascrittura sostituirà le configurazioni attuali con i dati del backup. I codici di accesso delle stampanti non vengono mai sovrascritti per sicurezza.",cancel:"Annulla",processingBackup:"Elaborazione del file di backup...",itemsRestored:"Elementi ripristinati",itemsSkipped:"Elementi saltati",restored:"Ripristinati",skippedAlreadyExist:"Saltati (già esistenti)",filesCategory:"File (3MF, miniature, ecc.)",andMore:"...e altri {{count}}",newApiKeysGenerated:"Nuove chiavi API generate",keysShownOnce:"Queste chiavi vengono mostrate solo una volta. Copiale ora!",copy:"Copia",noDataFound:"Nessun dato da ripristinare trovato nel file di backup.",close:"Chiudi",categories:{settings:"Impostazioni",notification_providers:"Provider di notifica",notification_templates:"Modelli di notifica",smart_plugs:"Smart Plug",printers:"Stampanti",filaments:"Filamenti",maintenance_types:"Tipi di manutenzione",archives:"Archivi",projects:"Progetti",pending_uploads:"Upload in sospeso",external_links:"Link esterni",api_keys:"Chiavi API"}},tags:{title:"Tag",addTag:"Aggiungi tag",editTag:"Modifica tag",deleteTag:"Elimina tag",tagName:"Nome tag",tagColor:"Colore tag",noTags:"Nessun tag",deleteConfirm:"Sei sicuro di voler eliminare questo tag?",manageTags:"Gestisci tag"},uploadModal:{title:"Carica file 3MF",dragDrop:"Trascina e rilascia file .3mf qui",or:"o",browseFiles:"Sfoglia file",extractionInfo:"Il modello stampante sarà estratto automaticamente dai metadati del file 3MF.",uploaded:"caricati",failed:"falliti",uploading:"Caricamento...",upload:"Carica",uploadFailed:"Caricamento fallito"},editArchive:{title:"Modifica archivio",name:"Nome",namePlaceholder:"Nome stampa",printer:"Stampante",noPrinter:"Nessuna stampante",project:"Progetto",noProject:"Nessun progetto",itemsPrinted:"Elementi stampati",itemsPrintedHelp:"Numero di elementi prodotti in questo job di stampa",notes:"Note",notesPlaceholder:"Aggiungi note su questa stampa...",externalLink:"Link esterno",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link a Printables, Thingiverse o altra fonte",tags:"Tag",tagsPlaceholder:"Aggiungi tag...",addMoreTags:"Aggiungi altri tag...",matchingTags:'Tag corrispondenti "{{query}}"',existingTags:"Tag esistenti",clickToAdd:"(clicca per aggiungere)",status:"Stato",failureReason:"Motivo fallimento",selectReason:"Seleziona motivo...",photos:"Foto del risultato stampato",photosHelp:"Clicca + per aggiungere foto del risultato stampato",printResult:"Risultato stampa",saving:"Salvataggio...",failureReasons:{adhesionFailure:"Fallimento adesione",spaghettiDetached:"Spaghetti / staccato",layerShift:"Spostamento layer",cloggedNozzle:"Ugello intasato",filamentRunout:"Filamento esaurito",warping:"Warping",stringing:"Stringing",underExtrusion:"Sotto-estrusione",powerFailure:"Mancanza corrente",userCancelled:"Annullato dall'utente",other:"Altro"},statuses:{completed:"Completato",failed:"Fallito",aborted:"Annullato",printing:"In stampa"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Nessuna stampante configurata",addPrinterInSettings:"Aggiungi una stampante in Impostazioni per gestire i K-profiles",noActivePrinters:"Nessuna stampante attiva",enablePrinterConnection:"Abilita una connessione stampante per vedere i K-profiles",loadingProfiles:"Caricamento K-Profiles...",printerOffline:"Stampante offline",printerOfflineDesc:"La stampante selezionata non e connessa. Accendila per vedere i K-profiles.",noMatchingProfiles:"Nessun profilo corrispondente",noMatchingProfilesDesc:"Nessun profilo corrisponde ai criteri di ricerca",noKProfiles:"Nessun K-Profile",noKProfilesDesc:"Nessun profilo pressure advance per ugello da {{diameter}}mm",createFirstProfile:"Crea primo profilo",printer:"Stampante",nozzle:"Ugello",refresh:"Aggiorna",addProfile:"Aggiungi profilo",export:"Esporta",import:"Importa",select:"Seleziona",selectAll:"Seleziona tutto",delete:"Elimina",searchPlaceholder:"Cerca per nome o filamento...",allExtruders:"Tutti gli estrusori",leftOnly:"Solo sinistro",rightOnly:"Solo destro",allFlow:"Tutto flow",hfOnly:"Solo HF",sOnly:"Solo S",sortName:"Ordina: Nome",sortKValue:"Ordina: K-Value",sortFilament:"Ordina: Filamento",leftExtruder:"Estrusore sinistro",rightExtruder:"Estrusore destro",modal:{addTitle:"Aggiungi K-Profile",editTitle:"Modifica K-Profile",profileName:"Nome profilo",profileNamePlaceholder:"Il mio profilo PLA",kValue:"K-Value",kValuePlaceholder:"0.020",kValueHelp:"Intervallo tipico: 0.01 - 0.06 per PLA, 0.02 - 0.10 per PETG",filament:"Filamento",selectFilament:"Seleziona filamento...",noFilamentsHelp:"Nessun filamento trovato. Crea prima un K-profile in Bambu Studio.",flowType:"Tipo flow",highFlow:"High Flow",standard:"Standard",nozzleSize:"Dimensione ugello",extruder:"Estrusore",extruders:"Estrusori",left:"Sinistra",right:"Destra",notes:"Note (salvate localmente)",notesPlaceholder:"Aggiungi note su questo profilo...",notesHelp:"Le note sono salvate in Bambuddy, non sulla stampante",syncing:"Sincronizzazione con stampante...",savingExtruder:"Salvataggio su estrusore {{current}}/{{total}}...",pleaseWait:"Attendere"},deleteConfirm:{title:"Elimina profilo",cannotUndo:"Questo non può essere annullato",message:'Sei sicuro di voler eliminare "{{name}}" dalla stampante?'},bulkDelete:{title:"Elimina profili",cannotUndo:"Questo non può essere annullato",message:"Sei sicuro di voler eliminare {{count}} profili selezionati dalla stampante?"},toast:{profileSaved:"K-profile salvato",profilesSaved:"K-profile salvato su {{count}} estrusori",selectAtLeastOneExtruder:"Seleziona almeno un estrusore",profileDeleted:"K-profile eliminato",profilesDeleted:"Eliminati {{count}} profili",exportedProfiles:"Esportati {{count}} profili",importedProfiles:"Importati {{count}} di {{total}} profili",noProfilesToExport:"Nessun profilo da esportare",invalidFileFormat:"Formato file non valido",failedToParseImport:"Parsing file import fallito",failedToSaveBatch:"Salvataggio K-profiles fallito",noteSaved:"Nota salvata",failedToSaveNote:"Salvataggio nota fallito"},permission:{noRead:"Non hai il permesso di aggiornare i profili",noCreate:"Non hai il permesso di aggiungere profili",noUpdate:"Non hai il permesso di aggiornare K-profiles",noDelete:"Non hai il permesso di eliminare K-profiles",noExport:"Non hai il permesso di esportare profili",noImport:"Non hai il permesso di importare profili"}},virtualPrinter:{title:"Stampante virtuale",running:"In esecuzione",stopped:"Ferma",description:{default:"Abilita una stampante virtuale che appare in Bambu Studio e OrcaSlicer. I file inviati a questa stampante saranno archiviati senza stampare.",proxy:"Abilita un proxy che inoltra il traffico slicer a una stampante reale, permettendo la stampa remota su qualsiasi rete."},enable:{title:"Abilita stampante virtuale",visibleInSlicer:'Visibile come "Bambuddy" nella ricerca slicer',proxyingTo:"In proxy verso {{name}}",notActive:"Non attivo"},model:{title:"Modello stampante",description:"Seleziona il modello stampante da emulare.",restartWarning:"Cambiare il modello riavviera la stampante virtuale"},accessCode:{title:"Codice accesso",isSet:"Codice accesso impostato",notSet:"Nessun codice accesso impostato - richiesto per abilitare",placeholder:"Inserisci codice 8 caratteri",placeholderChange:"Inserisci nuovo codice per cambiare",hint:"Deve essere esattamente 8 caratteri. Usato dagli slicer per autenticarsi.",charCount:"({{count}}/8)"},targetPrinter:{title:"Stampante target",configured:"Target proxy configurato",notConfigured:"Nessuna stampante target selezionata - richiesta per modalita proxy",placeholder:"Seleziona una stampante...",hint:"Seleziona la stampante a cui fare proxy. La stampante deve essere in modalita LAN.",noPrinters:"Nessuna stampante configurata. Aggiungi una stampante per usare la modalita proxy."},remoteInterface:{title:"Sovrascrittura interfaccia di rete",configured:"Sovrascrittura interfaccia attiva",optional:"Opzionale - usare se l'IP rilevato automaticamente e sbagliato (es. piu NIC, Docker, VPN)",placeholder:"Rilevamento automatico (predefinito)...",hint:"Sovrascrive l'indirizzo IP pubblicizzato via SSDP e usato nel certificato TLS. Utile quando Bambuddy ha piu interfacce di rete."},mode:{title:"Modalita",archive:"Archivio",archiveDesc:"Archivia subito i file",review:"Revisione",reviewDesc:"Rivedi prima di archiviare",queue:"Coda",queueDesc:"Archivia e aggiungi alla coda",proxy:"Proxy",proxyDesc:"Inoltra a stampante reale"},autoDispatch:{title:"Avvio automatico",description:"Avvia automaticamente le stampe aggiunte alla coda. Se disattivato, le stampe attendono l'avvio manuale."},setupRequired:{title:"Configurazione necessaria",description:"La stampante virtuale richiede configurazioni di sistema aggiuntive prima di funzionare. Include port forwarding, regole firewall e impostazioni specifiche della piattaforma.",readGuide:"Leggi la guida prima di abilitare"},howItWorks:{title:"Come funziona",step1:"Sulla stessa LAN, le stampanti virtuali appaiono automaticamente nel tuo slicer (Bambu Studio / OrcaSlicer). Da altre reti, aggiungile manualmente tramite indirizzo IP e codice di accesso.",step2:'In modalità Archivio, Revisione e Coda, usa il pulsante "Invia" nel tuo slicer per caricare file 3MF su Bambuddy. Lo slicer mostrerà "Stampa riuscita" — il file viene salvato, non stampato.',step3:"In modalità Proxy, la stampante virtuale inoltra tutto il traffico a una stampante reale — le stampe partono immediatamente come con una connessione diretta."},status:{title:"Dettagli stato",printerName:"Nome stampante",model:"Modello",serialNumber:"Numero seriale",mode:"Modalita",pendingFiles:"File in sospeso",targetPrinter:"Stampante target",ftpPort:"Porta FTP",mqttPort:"Porta MQTT",ftpConnections:"Connessioni FTP",mqttConnections:"Connessioni MQTT"},toast:{updated:"Impostazioni stampante virtuale aggiornate",failedToUpdate:"Aggiornamento impostazioni fallito",accessCodeRequired:"Imposta prima un codice accesso",targetPrinterRequired:"Seleziona prima una stampante target",bindIpRequired:"Impostare prima un indirizzo IP",accessCodeEmpty:"Il codice accesso non può essere vuoto",accessCodeLength:"Il codice accesso deve essere esattamente 8 caratteri",created:"Stampante virtuale creata",failedToCreate:"Impossibile creare la stampante virtuale",deleted:"Stampante virtuale eliminata",failedToDelete:"Impossibile eliminare la stampante virtuale"},list:{title:"Stampanti virtuali",add:"Aggiungi",addFirst:"Aggiungi stampante virtuale",empty:"Nessuna stampante virtuale configurata. Aggiungine una per iniziare."},bindIp:{title:"Interfaccia di rete",placeholder:"Seleziona interfaccia...",hint:"Interfaccia di rete a cui questa stampante virtuale si collega. Deve essere unica per stampante."},proxy:{accessCodeHint:"In modalita proxy, usa il codice di accesso della stampante di destinazione nello slicer. La connessione viene inoltrata in modo trasparente alla stampante reale."},addDialog:{title:"Aggiungi stampante virtuale",name:"Nome",hint:"Potrai configurare il codice di accesso, la stampante di destinazione e altre impostazioni dopo la creazione.",create:"Crea"},deleteConfirm:{title:"Elimina stampante virtuale",message:'Sei sicuro di voler eliminare "{{name}}"? Tutti i servizi di questa stampante verranno interrotti.'}},modelViewer:{openInSlicer:"Apri nello slicer",tabs:{model:"Modello 3D",gcode:"Anteprima G-code"},notAvailable:"non disponibile",notSliced:"non sezionato",plates:"Piatti",allPlates:"Tutti i piatti",plateNumber:"Piatto {{number}}",plateCount:"{{count}} piatto",plateCount_other:"{{count}} piatti",objectCount:"{{count}} oggetto",objectCount_other:"{{count}} oggetti",filamentCount:"{{count}} filamento",filamentCount_other:"{{count}} filamenti",eta:"ETA {{minutes}} min",noPreview:"Nessuna anteprima disponibile per questo file",pagination:{pageOf:"Pagina {{current}} di {{total}}",prev:"Prec",next:"Succ"},errors:{failedToLoad:"Caricamento file fallito",noMeshes:"Nessuna mesh trovata nel file 3MF",unsupportedFormat:"Formato file non supportato"}},maintenanceDescriptions:{lubricateCarbonRods:"Applica lubrificante alle aste in carbonio per un movimento fluido",lubricateRails:"Applica lubrificante alle guide lineari per un movimento fluido",cleanNozzle:"Pulisci hotend e ugello per prevenire intasamenti",checkBelts:"Verifica tensione cinghie per stampe accurate",cleanBuildPlate:"Pulisci il piatto per migliorare l'adesione",checkExtruder:"Ispeziona ingranaggi estrusore per usura",checkCooling:"Assicurati che le ventole di raffreddamento funzionino",generalInspection:"Ispezione generale stampante",cleanCarbonRods:"Pulisci le aste in carbonio per ridurre attrito",lubricateSteelRods:"Applica lubrificante alle aste in acciaio per un movimento fluido",cleanSteelRods:"Pulisci le aste in acciaio per ridurre attrito",cleanLinearRails:"Pulisci le guide lineari per rimuovere polvere e detriti",checkPtfeTube:"Ispeziona il tubo PTFE per usura o danni",replaceHepaFilter:"Sostituisci filtro HEPA per qualità aria",replaceCarbonFilter:"Sostituisci filtro a carbone attivo",lubricateLeftNozzleRail:"Lubrifica guida ugello sinistro (serie H2)"},smartPlugs:{offline:"Offline",admin:"Amministrazione",openPlugAdminPage:"Apri pagina amministrazione presa",deleteSmartPlug:"Elimina presa smart",turnOnSmartPlug:"Accendi presa smart",turnOffSmartPlug:"Spegni presa smart",turnOn:"Accendi",turnOff:"Spegni",addSmartPlug:{scanningNetwork:"Scansione rete...",chooseEntity:"Scegli un'entità...",connectionFailed:"Connessione fallita",searchEntities:"Cerca entità...",searchPowerSensors:"Cerca sensori di potenza...",searchEnergySensors:"Cerca sensori di energia...",placeholders:{plugName:"Presa soggiorno",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Stesso del topic potenza, o diverso"}},linkedTo:"Collegato a:",monitorOnly:"Solo monitoraggio",alerts:"Avvisi",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Potenza",kwhToday:"kWh Oggi",settings:"Impostazioni",automationSettings:"Impostazioni automazione",showInSwitchbar:"Mostra nella barra interruttori",quickAccessSidebar:"Accesso rapido dalla barra laterale",enabled:"Abilitato",enableAutomation:"Abilita automazione per questa presa",autoOn:"Auto On",autoOnDescription:"Accendi quando inizia la stampa",autoOff:"Auto Off",autoOffDescription:"Spegni quando la stampa è completata (una tantum)",autoOffPersistent:"Mantieni attivo",autoOffPersistentDescription:"Resta attivo tra le stampe invece di una tantum",turnOffDelayMode:"Modalità ritardo spegnimento",time:"Tempo",temp:"Temp",delayMinutes:"Ritardo (minuti)",tempThreshold:"Soglia temperatura (°C)",tempThresholdDescription:"Si spegne quando l'ugello si raffredda sotto questa temperatura",edit:"Modifica",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"? Questa azione non può essere annullata.',turnOnConfirm:'Sei sicuro di voler accendere "{{name}}"?',turnOffConfirm:`Sei sicuro di voler spegnere "{{name}}"? Questo interromperà l'alimentazione del dispositivo collegato.`,failedToTurn:'Impossibile {{action}} "{{name}}"',unknown:"Sconosciuto",addTitle:"Aggiungi presa smart",editTitle:"Modifica presa smart",stopScanning:"Interrompi scansione",discoverTasmota:"Scopri dispositivi Tasmota",foundDevices:"{{count}} dispositivo/i trovato/i - clicca per selezionare:",noDevicesFound:"Nessun dispositivo Tasmota trovato nella rete",haNotConfigured:"Home Assistant non è configurato. Configuralo in",haSettingsPath:"Impostazioni → Rete → Home Assistant",selectEntity:"Seleziona entità *",ipAddress:"Indirizzo IP *",nameLabel:"Nome *",username:"Nome utente",password:"Password",authHint:"Lascia vuoto se il tuo dispositivo Tasmota non richiede autenticazione",linkToPrinter:"Collega alla stampante",noPrinter:"Nessuna stampante (solo controllo manuale)",linkingDescription:"Il collegamento abilita accensione/spegnimento automatico all'inizio/fine stampa",powerAlerts:"Avvisi potenza",alertAbove:"Avviso se sopra (W)",alertBelow:"Avviso se sotto (W)",alertDescription:"Ricevi notifiche quando il consumo supera queste soglie. Lascia vuoto per disabilitare quella direzione.",dailySchedule:"Programma giornaliero",turnOnAt:"Accendi alle",turnOffAt:"Spegni alle",scheduleDescription:"Accendi/spegni automaticamente la presa a questi orari ogni giorno. Lascia vuoto per saltare quell'azione.",showOnPrinterCard:"Mostra sulla scheda stampante",displayOnPrinterCard:"Mostra pulsante sulla scheda stampante",connectedResult:"Connesso!",deviceLabel:"Dispositivo: {{name}} - ",stateLabel:"Stato: {{state}}",test:"Test",delete:"Elimina",save:"Salva",add:"Aggiungi",cancel:"Annulla",failedToStartScan:"Impossibile avviare la scansione",nameRequired:"Il nome è obbligatorio",entityRequired:"L'entità è obbligatoria per le prese Home Assistant",mqttTopicRequired:"Almeno un topic MQTT deve essere configurato per potenza, energia o monitoraggio stato",loadingEntities:"Caricamento entità...",loading:"Caricamento...",failedToLoadEntities:"Impossibile caricare le entità: {{error}}",noEntitiesMatching:'Nessuna entità trovata corrispondente a "{{search}}"',noEntitiesAvailable:"Nessuna entità disponibile",searchingEntities:"Ricerca in tutte le entità ({{count}} trovate)",showingEntities:"Mostrando switch, light, input_boolean ({{count}} disponibili)",energyMonitoringOptional:"Monitoraggio energia (Opzionale)",energyMonitoringHint:"Cerca e seleziona i sensori che forniscono dati di potenza/energia.",powerSensorW:"Sensore potenza (W)",energyTodayKwh:"Energia oggi (kWh)",totalEnergyKwh:"Energia totale (kWh)",noMatchingSensors:"Nessun sensore corrispondente",none:"Nessuno",mqttNotConfigured:"Broker MQTT non configurato. Imposta l'indirizzo del broker in",mqttSettingsPath:"Impostazioni → Rete → Pubblicazione MQTT",mqttNotConfiguredSuffix:"(non è necessario abilitare la pubblicazione, basta inserire i dettagli del broker).",mqttMonitorOnlyDescription:"Le prese MQTT ricevono dati di potenza/energia tramite sottoscrizione MQTT. Il controllo on/off non è disponibile - usa il tuo broker MQTT o sistema domotico.",powerMonitoring:"Monitoraggio potenza",energyMonitoring:"Monitoraggio energia",stateMonitoring:"Monitoraggio stato",optional:"opzionale",topic:"Topic",jsonPath:"Percorso JSON",multiplier:"Moltiplicatore",onValue:"Valore ON",mqttPowerHint:`Il percorso JSON estrae il valore dal payload JSON (es. "power_l1"). Lascia vuoto se il topic pubblica valori numerici grezzi.
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL potenza",restPowerPath:"Power JSON Path",restPowerMultiplier:"Moltiplicatore potenza",restEnergyUrl:"URL energia",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Moltiplicatore energia",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL separato per i dati di potenza (usa l'URL di stato se vuoto)",restEnergyUrlHint:"URL separato per i dati di energia (usa l'URL di stato se vuoto)",restEnergyHint:"Ogni valore può usare il proprio URL o ricadere sull'URL di stato. Usa i moltiplicatori per la conversione delle unità (es. 0.001 per convertire Wh in kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Nessun interruttore nella barra",enableSwitchbarHint:'Abilita "Mostra nella barra interruttori" in Impostazioni > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notifiche email tramite SMTP",telegram:"Notifiche tramite bot Telegram",discord:"Invia a un canale Discord tramite webhook",ntfy:"Notifiche push gratuite e self-hostabili",pushover:"Notifiche push semplici e affidabili",callmebot:"Notifiche WhatsApp gratuite tramite CallMeBot",webhook:"POST HTTP generico verso qualsiasi URL",homeassistant:"Notifiche persistenti nella dashboard di Home Assistant"},lastSuccess:"Ultimo: {{date}}",error:"Errore",printer:"Stampante:",allPrinters:"Tutte le stampanti",sendTestNotification:"Invia notifica di prova",eventSettings:"Impostazioni eventi",enabled:"Abilitato",sendFromProvider:"Invia notifiche da questo provider",printEvents:"Eventi di stampa",printerStatus:"Stato stampante",amsAlarms:"Allarmi AMS",amsHtAlarms:"Allarmi AMS-HT",printQueue:"Coda di stampa",start:"Avvio",plateCheck:"Controllo piatto",complete:"Completato",failed:"Fallito",stopped:"Interrotto",progress:"Avanzamento",offline:"Offline",lowFilament:"Filamento scarso",maintenance:"Manutenzione",amsHumidity:"Umidità AMS",amsTemp:"Temp AMS",amsHtHumidity:"Umidità AMS-HT",amsHtTemp:"Temp AMS-HT",bedCooled:"Piatto raffreddato",firstLayer:"Primo strato",quiet:"Silenzioso",digest:"Riepilogo {{time}}",printStarted:"Stampa avviata",plateNotEmpty:"Piatto non vuoto",plateNotEmptyDescription:"Oggetti rilevati prima della stampa",printCompleted:"Stampa completata",bedCooledLabel:"Piatto raffreddato",bedCooledDescription:"Piatto raffreddato sotto la soglia dopo la stampa",firstLayerCompleteLabel:"Primo strato completato",firstLayerCompleteDescription:"Notifica con foto al termine del primo strato",missingSpoolAssignmentLabel:"Assegnazione bobina mancante",missingSpoolAssignmentDescription:"Notifica quando una stampa parte e i vassoi richiesti non hanno una bobina assegnata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",progressMilestones:"Traguardi di avanzamento",progressMilestonesDescription:"Notifica al 25%, 50%, 75%",printerOffline:"Stampante offline",printerError:"Errore stampante",lowFilamentLabel:"Filamento scarso",maintenanceDue:"Manutenzione necessaria",maintenanceDueDescription:"Notifica quando è necessaria la manutenzione",amsHumidityHigh:"Umidità AMS elevata",amsHumidityHighDescription:"L'umidità dell'AMS standard supera la soglia",amsTemperatureHigh:"Temperatura AMS elevata",amsTemperatureHighDescription:"La temperatura dell'AMS standard supera la soglia",amsHtHumidityHigh:"Umidità AMS-HT elevata",amsHtHumidityHighDescription:"L'umidità dell'AMS-HT supera la soglia",amsHtTemperatureHigh:"Temperatura AMS-HT elevata",amsHtTemperatureHighDescription:"La temperatura dell'AMS-HT supera la soglia",jobAdded:"Lavoro aggiunto",jobAddedDescription:"Lavoro aggiunto alla coda",jobAssigned:"Lavoro assegnato",jobAssignedDescription:"Lavoro basato su modello assegnato alla stampante",jobStarted:"Lavoro avviato",jobStartedDescription:"Lavoro in coda avviato per la stampa",jobWaiting:"Lavoro in attesa",jobWaitingDescription:"Lavoro in attesa di filamento o stampante",jobSkipped:"Lavoro saltato",jobSkippedDescription:"Lavoro saltato (precedente fallito)",jobFailed:"Lavoro fallito",jobFailedDescription:"Avvio del lavoro fallito",queueComplete:"Coda completata",queueCompleteDescription:"Tutti i lavori in coda completati",quietHours:"Ore silenziose",noNotificationsDuring:"Nessuna notifica durante queste ore",editProviderToChangeQuietHours:"Modifica il provider per cambiare le ore silenziose",dailyDigest:"Riepilogo giornaliero",batchNotifications:"Raggruppa le notifiche in un unico riepilogo giornaliero",sendAt:"Invia alle {{time}}",editProviderToChangeDigestTime:"Modifica il provider per cambiare l'orario del riepilogo",edit:"Modifica",deleteProvider:"Elimina provider di notifica",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"? Questa azione non può essere annullata.',delete:"Elimina",addTitle:"Aggiungi provider di notifica",editTitle:"Modifica provider di notifica",nameLabel:"Nome *",namePlaceholder:"Le mie notifiche",providerTypeLabel:"Tipo di provider *",configuration:"Configurazione",testConfiguration:"Testa configurazione",printerFilter:"Filtro stampante",onlyFromPrinter:"Invia notifiche solo per eventi da questa stampante",quietHoursDnd:"Ore silenziose (Non disturbare)",quietStart:"Inizio",quietEnd:"Fine",dailyDigestLabel:"Riepilogo giornaliero",sendDigestAt:"Invia riepilogo alle",digestCollected:"Gli eventi verranno raccolti e inviati come riepilogo unico a quest'ora",notificationEvents:"Eventi di notifica",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(dopo il completamento della stampa)",cancel:"Annulla",save:"Salva",add:"Aggiungi",nameRequired:"Il nome è obbligatorio",fieldRequired:"{{field}} è obbligatorio",phoneNumber:"Numero di telefono",apiKey:"Chiave API",serverUrl:"URL del server",topic:"Argomento",authToken:"Token di autenticazione",userKey:"Chiave utente",appToken:"Token applicazione",priority:"Priorità",botToken:"Token del bot",chatId:"ID chat",smtpServer:"Server SMTP",smtpPort:"Porta SMTP",security:"Sicurezza",authentication:"Autenticazione",username:"Nome utente",password:"Password",fromEmail:"Email mittente",toEmail:"Email destinatario",webhookUrl:"URL webhook",payloadFormat:"Formato payload",authorization:"Autorizzazione",titleFieldName:"Nome campo titolo",messageFieldName:"Nome campo messaggio",editTemplate:"Modifica modello: {{name}}",titleLabel:"Titolo",bodyLabel:"Corpo",titlePlaceholder:"Titolo della notifica...",bodyPlaceholder:"Corpo della notifica...",availableVariables:"Variabili disponibili",clickToInsert:"Clicca per inserire alla posizione del cursore nel corpo",livePreview:"Anteprima live",hide:"Nascondi",show:"Mostra",loadingPreview:"Caricamento anteprima...",enterTemplateContent:"Inserisci il contenuto del modello per vedere l'anteprima",titlePreview:"Titolo:",bodyPreview:"Corpo:",resetToDefault:"Ripristina predefinito",titleRequired:"Il titolo è obbligatorio",bodyRequired:"Il corpo è obbligatorio",notificationLog:"Registro notifiche",showFailedOnly:"Solo fallite",last24Hours:"Ultime 24 ore",last7Days:"Ultimi 7 giorni",last30Days:"Ultimi 30 giorni",last90Days:"Ultimi 90 giorni",justNow:"Proprio ora",noFailedNotifications:"Nessuna notifica fallita",noNotificationsLogged:"Nessuna notifica registrata",unknownProvider:"Provider sconosciuto",logTitle:"Titolo",logMessage:"Messaggio",logError:"Errore",logProvider:"Provider: {{type}}",logTime:"Ora: {{time}}",refresh:"Aggiorna",clearOld:"Cancella vecchie",statsSummary:"Ultimi {{days}} giorni:",statsNotifications:"notifiche",statsSent:"{{count}} inviate",statsFailed:"{{count}} fallite",eventTypes:{print_start:"Stampa avviata",print_complete:"Stampa completata",print_failed:"Stampa fallita",print_stopped:"Stampa interrotta",print_progress:"Avanzamento",printer_offline:"Stampante offline",printer_error:"Errore stampante",filament_low:"Filamento scarso",maintenance_due:"Manutenzione necessaria",test:"Prova"},userEmail:{title:"Notifiche",emailNotifications:"Notifiche via e-mail",emailNotificationsDesc:"Ricevi notifiche via e-mail per i tuoi lavori di stampa. Le e-mail vengono inviate tramite le impostazioni SMTP configurate nell'autenticazione avanzata.",sendingTo:"Le notifiche verranno inviate a",noEmailWarning:"Il tuo account non ha un indirizzo e-mail. Contatta un amministratore per aggiungerne uno.",printJobNotifications:"Notifiche lavori di stampa",printJobNotificationsDesc:"Scegli quali eventi attivano le notifiche e-mail per i lavori di stampa che invii.",printJobStarts:"Inizio lavoro di stampa",printJobStartsDesc:"Ricevi una notifica quando il tuo lavoro di stampa inizia.",printJobFinishes:"Fine lavoro di stampa",printJobFinishesDesc:"Ricevi una notifica quando il tuo lavoro di stampa si completa correttamente.",printErrors:"Errori di stampa",printErrorsDesc:"Ricevi una notifica quando il tuo lavoro di stampa fallisce o incontra un errore.",printJobStops:"Lavoro di stampa interrotto",printJobStopsDesc:"Ricevi una notifica quando il tuo lavoro di stampa viene annullato o interrotto.",saveSuccess:"Preferenze di notifica salvate.",saveError:"Impossibile salvare le preferenze di notifica."}},richTextEditor:{bold:"Grassetto",italic:"Corsivo",underline:"Sottolineato",bulletList:"Elenco puntato",numberedList:"Elenco numerato",alignLeft:"Allinea a sinistra",alignCenter:"Allinea al centro",alignRight:"Allinea a destra",addLink:"Aggiungi link",removeLink:"Rimuovi link"},externalLinks:{noLinksConfigured:"Nessun link esterno configurato",deleteLink:"Elimina link",removeCustomIcon:"Rimuovi icona personalizzata",openInNewTab:"Apri in nuova scheda",placeholders:{linkName:"Il mio link"}},keyboardShortcuts:{title:"Scorciatoie da tastiera",navigation:"Navigazione",archivesSection:"Archivi",kProfilesSection:"Profili K",generalSection:"Generale",shortcuts:{goToPrinters:"Vai a Stampanti",goToArchives:"Vai ad Archivi",goToQueue:"Vai a Coda",goToStats:"Vai a Statistiche",goToProfiles:"Vai a Profili cloud",goToSettings:"Vai a Impostazioni",focusSearch:"Vai alla ricerca",openUploadModal:"Apri finestra di caricamento",clearSelection:"Cancella selezione / deseleziona input",contextMenu:"Menu contestuale sulle schede",refreshProfiles:"Aggiorna profili",newProfile:"Nuovo profilo",exitSelectionMode:"Esci dalla modalità selezione",showHelp:"Mostra questa guida"},footer:"Premi Esc o clicca fuori per chiudere"},notificationLog:{title:"Registro notifiche",events:{printStarted:"Stampa avviata",printComplete:"Stampa completata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",progress:"Avanzamento",printerOffline:"Stampante offline",printerError:"Errore stampante",lowFilament:"Filamento in esaurimento",maintenanceDue:"Manutenzione in scadenza",test:"Test"},timeAgo:{justNow:"Adesso",minutesAgo:"{{minutes}} min fa",hoursAgo:"{{hours}} ore fa"}},restoreBackup:{title:"Ripristina backup",restoring:"Ripristino...",restoreComplete:"Ripristino completato",restoreFailed:"Ripristino fallito",importSettings:"Importa impostazioni da un file di backup",pleaseWait:"Attendere il ripristino dei dati",clickToSelect:"Clicca per selezionare il file di backup (.json o .zip)",howDuplicateHandling:"Come funziona la gestione dei duplicati:",categories:{printers:"Stampanti",smartPlugs:"Prese smart",notificationProviders:"Provider di notifica",filaments:"Filamenti",archives:"Archivi",pendingUploads:"Caricamenti in sospeso",settingsTemplates:"Impostazioni e modelli"},matchingInfo:{printers:"abbinati per numero di serie",smartPlugs:"abbinati per indirizzo IP",notificationProviders:"abbinati per nome",filaments:"abbinati per nome + tipo + marca",archives:"abbinati per hash del contenuto",pendingUploads:"abbinati per nome file",settingsTemplates:"sempre sovrascritti"},replaceExisting:"Sostituisci dati esistenti",keepExisting:"Mantieni dati esistenti",replaceDescription:"Sovrascrivi gli elementi già esistenti con i dati del backup",keepDescription:"Ripristina solo gli elementi che non esistono già",caution:"Attenzione:",cautionText:"La sovrascrittura sostituirà le configurazioni attuali con i dati del backup. I codici di accesso delle stampanti non vengono mai sovrascritti per sicurezza.",itemsRestored:"Elementi ripristinati",itemsSkipped:"Elementi saltati",restored:"Ripristinati",skipped:"Saltati (già esistenti)",filesLabel:"File (3MF, miniature, ecc.)",newApiKeysGenerated:"Nuove chiavi API generate",newApiKeysWarning:"Queste chiavi vengono mostrate una sola volta. Copiale adesso!",processingBackup:"Elaborazione file di backup...",noDataFound:"Nessun dato trovato da ripristinare nel file di backup.",failedToRestore:"Impossibile ripristinare il backup. Verificare il formato del file."},backupExport:{title:"Esporta backup",selectData:"Seleziona i dati da includere",selectAll:"Seleziona tutto",selectNone:"Deseleziona tutto",categoryDescriptions:{settings:"Lingua, tema, preferenze di aggiornamento",notifications:"ntfy, Pushover, Discord, ecc.",templates:"Modelli di messaggi personalizzati",smartPlugs:"Configurazioni prese Tasmota",externalLinks:"Link della barra laterale a servizi esterni",printers:"Info stampanti (codici di accesso esclusi)",plateDetection:"Immagini di riferimento piatto vuoto",filaments:"Tipi di filamento e costi",maintenance:"Programmi di manutenzione personalizzati",archives:"Tutti i dati di stampa + file (3MF, miniature, foto)",projects:"Progetti, elementi BOM e allegati",pendingUploads:"Caricamenti della stampante virtuale in attesa di revisione",apiKeys:"Chiavi API webhook (nuove chiavi generate all'importazione)"},requiresPrinters:"Richiede la selezione di Stampanti",zipFileWarning:"Verrà creato un file ZIP.",zipFileDescription:"Include tutti i file 3MF, miniature, timelapse e foto. Potrebbe richiedere tempo e produrre un file di grandi dimensioni.",includeAccessCodes:"Includi codici di accesso",includeAccessCodesDescription:"Per il trasferimento su un'altra macchina",includeAccessCodesWarning:"I codici di accesso saranno inclusi in testo semplice. Mantieni sicuro questo file di backup!",categoriesSelected:"{{selectedCount}} categorie selezionate"},pendingUploads:{placeholders:{notes:"Aggiungi note su questa stampa..."},discardUpload:"Scarta caricamento",archiveAllUploads:"Archivia tutti i caricamenti",discardAllUploads:"Scarta tutti i caricamenti",archive:"Archivia",timeAgo:{justNow:"Adesso",minutesAgo:"{{minutes}} min fa",hoursAgo:"{{hours}} ore fa",daysAgo:"{{days}} giorni fa"}},apiBrowser:{placeholders:{requestBody:"Corpo della richiesta JSON...",searchEndpoints:"Cerca endpoint..."}},configureAmsSlot:{title:"Configura Slot AMS",slotConfigured:"Slot configurato!",configuringSlot:"Configurazione slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Cerca preset...",colorPlaceholder:"Nome colore o hex (es. marrone, FF8800)",clearCustomColor:"Cancella colore personalizzato",noCloudPresets:"Nessun preset cloud. Accedi a Bambu Cloud per sincronizzare.",noPresetsAvailable:"Nessun preset disponibile. Accedi a Bambu Cloud o importa profili locali.",noMatchingPresets:"Nessun preset corrispondente trovato.",custom:"Personalizzato",builtin:"Integrato",settingsSentToPrinter:"Impostazioni inviate alla stampante",filamentProfile:"Profilo filamento",kProfileLabel:"Profilo K (Pressure Advance)",filteringFor:"Filtrando per: {{material}}",noKProfile:"Nessun profilo K (usa predefinito 0.020)",noMatchingKProfiles:"Nessun profilo K corrispondente. Verrà usato K=0.020 predefinito.",selectFilamentFirst:"Seleziona prima un profilo filamento",kFromCalibration:"K={{value}} dalla calibrazione stampante",customColorLabel:"Colore personalizzato (opzionale)",presetColors:"Colori {{name}}:",showLessColors:"Mostra meno colori",showMoreColors:"Mostra più colori",clear:"Cancella",hexLabel:"Hex: #{{hex}}",resetting:"Ripristino...",resetSlot:"Ripristina slot",cancel:"Annulla",configuring:"Configurazione...",configureSlot:"Configura slot"},githubBackup:{title:"Backup GitHub",history:"Cronologia",downloadBackup:"Scarica backup",restoreBackup:"Ripristina backup",noBackupsYet:"Nessun backup ancora"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Cerca tag...",renameTag:"Rinomina tag",deleteTag:"Elimina tag"},notificationTemplates:{placeholders:{title:"Titolo notifica...",body:"Corpo notifica..."}},batchTag:{placeholders:{newTag:"Inserisci nuovo tag..."}},photoGallery:{deletePhoto:"Elimina foto"},filamentHoverCard:{copySpoolUuid:"Copia UUID bobina"},kProfilesView:{hasNote:"Ha una nota",copyProfile:"Copia profilo"},layout:{openMenu:"Apri menu",noPermissionSystemInfo:"Non hai il permesso di visualizzare le informazioni di sistema"},dashboard:{dragToReorder:"Trascina per riordinare",hideWidget:"Nascondi widget"},notificationProviderCard:{deleteNotificationProvider:"Elimina provider di notifica"},fileManagerModal:{closeFileManager:"Chiudi gestore file",sortFiles:"Ordina file",goToParentFolder:"Vai alla cartella superiore",threeView:"Vista 3D"},embeddedCameraViewer:{refreshStream:"Aggiorna stream",close:"Chiudi",zoomOut:"Rimpicciolisci",resetZoom:"Reimposta zoom",zoomIn:"Ingrandisci",dragToResize:"Trascina per ridimensionare"},timelapseViewer:{skipBack5s:"Indietro 5s",skipForward5s:"Avanti 5s"},notificationProviders:{descriptions:{email:"Notifiche email via SMTP",telegram:"Notifiche tramite bot Telegram",discord:"Invia a canale Discord tramite webhook",ntfy:"Notifiche push gratuite e self-hostabili",pushover:"Notifiche push semplici e affidabili",callmebot:"Notifiche WhatsApp gratuite tramite CallMeBot",webhook:"POST HTTP generico a qualsiasi URL"}},logViewer:{searchPlaceholder:"Cerca messaggio o nome logger...",noLogEntries:"Nessuna voce di log trovata"},switchbarPopover:{noSwitchesInSwitchbar:"Nessun interruttore nella barra"},projectPageModal:{placeholders:{title:"Titolo",designer:"Designer",license:"Licenza",description:"Inserisci descrizione...",profileTitle:"Titolo profilo",profileDescription:"Descrizione profilo..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"In attesa",justNow:"Proprio ora",now:"Ora",minsAgo:"{{count}}m fa",inMins:"tra {{count}}m",hoursAgo:"{{count}}h fa",inHours:"tra {{count}}h",daysAgo:"{{count}}g fa",inDays:"tra {{count}}g"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventario",writeTag:"Scrivi",settings:"Impostazioni"},status:{nfcReady:"NFC pronto",nfcOff:"NFC spento",offline:"Offline",online:"Online",noPrinters:"Nessuna stampante",deviceOffline:"Dispositivo offline",waitingConnection:"In attesa della connessione...",systemReady:"Sistema pronto",status:"Stato"},dashboard:{readyToScan:"Pronto per la scansione",idleMessage:"Posiziona una bobina sulla bilancia per identificarla",nfcHint:"Il tag NFC verrà letto automaticamente",device:"Dispositivo",syncWeight:"Sincronizza peso",weightSynced:"Sincronizzato!",unknownTag:"Tag sconosciuto",newTag:"Nuovo tag rilevato",onScale:"sulla bilancia",linkSpool:"Collega a bobina",linkTagTitle:"Collega tag a bobina",linkTag:"Collega tag",selectSpool:"Seleziona una bobina da collegare a questo tag:",noUntagged:"Nessuna bobina senza tag trovata",tagDetected:"Tag rilevato",noTag:"Nessun tag",tagId:"Tag",grossWeight:"Peso lordo",spoolSize:"Dimensione bobina",close:"Chiudi",currentSpool:"Bobina attuale"},modal:{spoolDetected:"Bobina rilevata",assignToAms:"Assegna all'AMS",syncWeight:"Sincronizza peso",weightSynced:"Sincronizzato!",syncing:"Sincronizzazione...",newTagDetected:"Nuovo tag rilevato",addToInventory:"Aggiungi all'inventario",assignToAmsTitle:"Assegna all'AMS",selectSlot:"Seleziona uno slot",assign:"Assegna",assigning:"Assegnazione...",assignSuccess:"Assegnato!",assignError:"Impossibile assegnare la bobina. Riprovare.",noPrinterSelected:"Seleziona una stampante...",noAmsDetected:"Nessun AMS rilevato su questa stampante",slot:"Slot"},weight:{noReading:"Nessuna lettura",stable:"Stabile",measuring:"Misurazione...",tare:"Tara",calibrate:"Calibra"},spool:{remaining:"Rimanente",material:"Materiale",brand:"Marca",color:"Colore",coreWeight:"Nucleo",labelWeight:"Etichetta",scaleWeight:"Bilancia",netWeight:"Netto",lastUsed:"Ultimo utilizzo"},ams:{noData:"Nessun AMS rilevato",connectAms:"Collega un AMS per vedere gli slot",noPrinter:"Nessuna stampante selezionata",selectPrinter:"Seleziona una stampante dalla barra superiore",printerDisconnected:"Stampante disconnessa",humidity:"Umidità",level:"Livello",active:"Attivo",slot:"Slot",empty:"Vuoto"},inventory:{search:"Cerca bobine...",empty:"Nessuna bobina nell'inventario",noResults:"Nessuna bobina corrispondente",spools:"bobine",addSpool:"Aggiungi bobina"},settings:{tabDevice:"Dispositivo",tabDisplay:"Display",tabScale:"Bilancia",tabUpdates:"Aggiornamenti",nfcReader:"Lettore NFC",type:"Tipo",connection:"Connessione",notConnected:"N/A",deviceInfo:"Info dispositivo",hostname:"Host",uptime:"Tempo di attività",brightness:"Luminosità",saved:"Salvato",noBacklight:"Nessuna retroilluminazione DSI rilevata. Il controllo luminosità richiede un display DSI.",screenBlank:"Timeout spegnimento schermo",screenBlankDesc:"Lo schermo si spegne dopo inattività. Tocca per riattivare.",displayNote:"La luminosità viene applicata come filtro software.",scaleCalibration:"Calibrazione bilancia",currentWeight:"Peso attuale",tareOffset:"Tara",calFactor:"Fattore",knownWeight:"Peso noto",calStep1:"Rimuovere tutto dalla bilancia e premere Imposta zero.",calStep2:"Posizionare il peso noto sulla bilancia.",setZero:"Imposta zero",calibrateNow:"Calibra",calibrated:"Calibrato",tareSet:"Comando tara inviato. In attesa del dispositivo...",tareFailed:"Invio comando tara fallito",zeroSet:"Punto zero impostato. Posizionare il peso noto sulla bilancia.",calibrationDone:"Calibrazione completata!",calibrationFailed:"Calibrazione fallita",lastCalibrated:"Ultima calibrazione",stable:"Stabile",settling:"Stabilizzazione...",firmware:"Firmware",scale:"Bilancia",noDevice:"Nessun dispositivo SpoolBuddy trovato",daemonVersion:"Versione daemon",currentVersion:"Attuale",versionPending:"In attesa del daemon...",checking:"Verifica...",checkUpdates:"Verifica aggiornamenti",updateAvailable:"Aggiornamento disponibile",updateInstructions:"Aggiorna via SSH: esegui lo script di installazione SpoolBuddy.",upToDate:"Aggiornato",includeBeta:"Includi versioni beta"},writeTag:{tabExisting:"Bobina esistente",tabNew:"Nuova bobina",tabReplace:"Sostituisci tag",searchPlaceholder:"Cerca per materiale, colore, marca...",noUntaggedSpools:"Nessuna bobina senza tag",noTaggedSpools:"Nessuna bobina con tag",selectSpool:"Seleziona una bobina, poi posiziona un NTAG sul lettore",placeTag:"Posiziona un NTAG sul lettore",tagReady:"Tag rilevato — pronto per la scrittura",writeTag:"Scrivi tag",replaceTag:"Sostituisci tag",writing:"Scrittura tag...",waiting:"In attesa di SpoolBuddy...",writeSuccess:"Tag scritto con successo!",writeFailed:"Scrittura fallita",queueFailed:"Impossibile accodare il comando di scrittura",tryAgain:"Riprova",cancel:"Annulla",replaceWarning:"Il vecchio tag verrà scollegato. Il nuovo tag lo sostituirà.",deviceOffline:"SpoolBuddy è offline",material:"Materiale",colorName:"Nome colore",color:"Colore",brand:"Marca",weight:"Peso (g)",createSpool:"Crea bobina",creating:"Creazione...",spoolCreated:"Bobina creata! Pronto per la scrittura.",createFailed:"Impossibile creare la bobina"},quickMenu:{printerPower:"Alimentazione stampante",systemControls:"Sistema",restartDaemon:"Riavvia daemon",restartBrowser:"Riavvia browser",reboot:"Riavvia",shutdown:"Spegni",swipeToClose:"Scorri verso il basso per chiudere",confirmTitle:"Conferma",confirmShutdown:"Sei sicuro di voler spegnere lo SpoolBuddy? Avrai bisogno di accesso fisico per riaccenderlo.",confirmReboot:"Sei sicuro di voler riavviare lo SpoolBuddy?",confirmRestartDaemon:"Riavviare il daemon SpoolBuddy? NFC e bilancia saranno temporaneamente non disponibili.",confirmRestartBrowser:"Riavviare il browser kiosk? Lo schermo diventerà brevemente nero.",confirm:"Conferma",confirmPlugOn:"Accendere {{name}}?",confirmPlugOff:"Spegnere {{name}}?",turnOn:"Accendi",turnOff:"Spegni"}},bugReport:{title:"Segnala un bug",description:"Descrizione",descriptionPlaceholder:"Cosa è andato storto? Descrivi il problema...",email:"Email (opzionale)",emailPlaceholder:"tua@email.it",emailPrivacy:"Se fornita, la tua email sarà inclusa in una sezione compressa dell'issue GitHub per permettere al manutentore di contattarti.",screenshot:"Screenshot",uploadOrPaste:"Carica, incolla o trascina un'immagine",dataCollectedSummary:"Quali dati sono inclusi nel report?",dataIncluded:"Inclusi:",dataIncludedList:"Versione app, OS, architettura, versione Python, statistiche database (solo conteggi), modelli stampante, numero ugelli, versioni firmware, stato connessione, stato integrazioni (Spoolman, MQTT, HA), impostazioni non sensibili, conteggio interfacce di rete, dettagli Docker, versioni dipendenze.",dataNeverIncluded:"Mai inclusi:",dataNeverIncludedList:"Nomi stampanti, numeri di serie, codici di accesso, password, indirizzi IP, indirizzi email, chiavi API, token, URL webhook, nomi host o nomi utente.",submit:"Invia",startLogging:"Avvia registrazione debug",stepEnableLogging:"Registrazione debug attivata",stepReproduce:"Riproduci il problema ora",stepStopLogging:"Ferma & invia rapporto",stopAndSubmit:"Ferma & Invia",maxDuration:"Arresto automatico dopo {{minutes}} min",stoppingLogs:"Raccolta log & invio...",submitting:"Invio segnalazione bug...",submitSuccess:"Segnalazione bug inviata con successo!",submitFailed:"Impossibile inviare la segnalazione bug",thankYou:"Grazie!",submitted:"La tua segnalazione bug è stata inviata.",viewIssue:"Vedi issue",unexpectedError:"Si è verificato un errore imprevisto"}},Pue={nav:{printers:"Impressoras",archives:"Arquivos",queue:"Fila",stats:"Estatísticas",profiles:"Perfis",maintenance:"Manutenção",projects:"Projetos",inventory:"Inventário",files:"Gerenciador de Arquivos",notifications:"Notificações",settings:"Configurações",system:"Sistema",collapseSidebar:"Recolher barra lateral",expandSidebar:"Expandir barra lateral",update:"Atualizar",updateAvailable:"Atualização disponível: v{{version}}",updateAvailableBanner:"Versão {{version}} está disponível!",viewUpdate:"Ver atualização",viewOnGithub:"Ver no GitHub",keyboardShortcuts:"Atalhos de teclado (?)",switchToLight:"Mudar para modo claro",switchToDark:"Mudar para modo escuro",smartSwitches:"Interruptores inteligentes",logout:"Sair"},common:{save:"Salvar",saving:"Salvando...",cancel:"Cancelar",delete:"Excluir",edit:"Editar",add:"Adicionar",close:"Fechar",confirm:"Confirmar",loading:"Carregando...",error:"Erro",success:"Sucesso",warning:"Aviso",enabled:"Ativado",disabled:"Desativado",yes:"Sim",no:"Não",on:"Ligado",off:"Desligado",all:"Todos",none:"Nenhum",search:"Pesquisar",filter:"Filtrar",sort:"Ordenar",refresh:"Atualizar",download:"Baixar",upload:"Enviar",uploading:"Enviando...",uploadFailed:"Falha no envio",actions:"Ações",status:"Status",name:"Nome",description:"Descrição",date:"Data",time:"Hora",hours:"Horas",minutes:"Minutos",seconds:"Segundos",days:"Dias",enable:"Ativar",disable:"Desativar",permissions:"Permissões",noPrinters:"Nenhuma impressora configurada",noData:"Nenhum dado disponível",linkNotFound:"Link não encontrado",required:"Obrigatório",optional:"Opcional",dismiss:"Dispensar",apply:"Aplicar",reset:"Redefinir",export:"Exportar",import:"Importar",clear:"Limpar",selectAll:"Selecionar tudo",deselectAll:"Desmarcar tudo",noChange:"— Sem alterações —",unchanged:"Inalterado",unassigned:"Não atribuído",unknown:"Desconhecido",unknownError:"Erro desconhecido",today:"Hoje",tomorrow:"Amanhã",asap:"O mais rápido possível",overdue:"Atrasado",now:"Agora",collapse:"Recolher",expand:"Expandir",viewArchive:"Ver arquivo",viewInFileManager:"Ver no Gerenciador de Arquivos",addedBy:"Adicionado por {{username}}",prints:"impressões",more:"+{{count}} mais",ascending:"Crescente",descending:"Decrescente",printer:"Impressora",remove:"Remover",type:"Tipo",print:"Imprimir",rename:"Renomear",move:"Mover",create:"Criar",duplicate:"Duplicar",left:"Esquerda",right:"Direita"},printers:{title:"Impressoras",addPrinter:"Adicionar Impressora",editPrinter:"Editar Impressora",deletePrinter:"Excluir Impressora",printerName:"Nome da Impressora",serialNumber:"Número de Série",ipAddress:"Endereço IP / Nome do Host",accessCode:"Código de Acesso",model:"Modelo",nozzleCount:"Número de Bicos",autoArchive:"Arquivamento Automático",status:{available:"Disponível",idle:"Ocioso",printing:"Imprimindo",paused:"Pausado",offline:"Offline",problem:"Problema",error:"Erro",finished:"Concluído",unknown:"Desconhecido"},temperatures:{nozzle:"Bico",bed:"Cama",chamber:"Câmara"},progress:"{{percent}}% concluído",timeRemaining:"{{time}} restante",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',maintenanceOk:"Manutenção OK",maintenanceWarning:"{{count}} aviso",maintenanceWarning_plural:"{{count}} avisos",maintenanceDue:"{{count}} devido",maintenanceDue_plural:"{{count}} devido",sort:{name:"Nome",status:"Status",model:"Modelo",location:"Localização",ascending:"Ordem crescente",descending:"Ordem decrescente"},cardSize:{small:"Cartões pequenos",medium:"Cartões médios",large:"Cartões grandes",extraLarge:"Cartões extra grandes"},hideOffline:"Ocultar offline",nextAvailable:"Próximo disponível",powerOn:"Ligar",offlinePrintersWithPlugs:"Impressoras offline com tomadas inteligentes",noPrintersConfigured:"Nenhuma impressora configurada ainda",search:"Pesquisar impressoras...",noSearchResults:"Nenhuma impressora corresponde à sua pesquisa ou filtros",filter:{allStatuses:"Todos os status",allLocations:"Todos os locais"},readyToPrint:"Pronto para imprimir",external:"Externo",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Excluir arquivos de impressão",noLabel:"Sem etiqueta",printPreview:"Pré-visualização de impressão",width:"Largura",height:"Altura",noObjectsFound:"Nenhum objeto encontrado",objectsLoadedOnPrintStart:"Objetos são carregados quando uma impressão começa",willBeSkipped:"Será ignorado",name:"Nome",serialCannotBeChanged:"Número de série não pode ser alterado",locationHelp:"Usado para agrupar impressoras e filtrar trabalhos na fila",wifiSignal:{veryWeak:"Muito fraco",weak:"Fraco",fair:"Regular",good:"Bom",excellent:"Excelente"},maintenanceUpToDate:"Toda a manutenção está em dia - Clique para ver",chamberLightOn:"Ligar luz da câmara",chamberLightOff:"Desligar luz da câmara",files:"Arquivos",browseFiles:"Procurar arquivos da impressora",autoOffAfterPrint:"Desligamento automático após impressão",autoOffExecuted:"Desligamento automático executado - ligue a impressora para reiniciar",hmsErrors:"Erros HMS",viewHmsErrors:"Ver {{count}} erro(s) HMS",resume:"Retomar",pause:"Pausar",stop:"Parar",camera:"âmera",skipObject:"Ignorar objeto",reconnect:"Reconectar",mqttDebug:"Depuração MQTT",printerInformation:"Informações da impressora",copyToClipboard:"Copiar",copied:"Copiado!",state:"Estado",wifiSignalLabel:"Sinal WiFi",developerMode:"Modo desenvolvedor",enabled:"Ativado",disabled:"Desativado",addedOn:"Adicionada em",sdCard:"Cartão SD",inserted:"Inserido",notInserted:"Não inserido",totalPrintHours:"Horas de impressão",activeNozzle:"Ativo: {{nozzle}} bico",nozzleRack:"Suporte de bicos",nozzleDocked:"Acoplado",nozzleMounted:"Montado",nozzleActive:"Ativo",nozzleIdle:"Ocioso",nozzleDiameter:"Diâmetro",nozzleType:"Tipo",nozzleStatus:"Status",nozzleFilament:"Filamento",nozzleWear:"Desgaste",nozzleMaxTemp:"Temp Máx",nozzleSerial:"Serial",nozzleHardenedSteel:"Aço Endurecido",nozzleStainlessSteel:"Aço Inoxidável",nozzleTungstenCarbide:"Carboneto de Tungstênio",nozzleFlow:"Fluxo",nozzleHighFlow:"Alto Fluxo",nozzleStandardFlow:"Fluxo Padrão",firmwareUpdate:"Atualização de Firmware",firmwareInstructions:"No visor da impressora, vá para",firmwareNav:"Navegar para",settings:"Configurações",firmware:"Firmware",discoverPrinters:"Descobrir Impressoras",searching:"Procurando...",manualEntry:"Entrada Manual",addFromCloud:"Adicionar da Nuvem",toast:{printerDeleted:"Impressora excluída",missingSpoolAssignment:"Impressão iniciada em {{printer}}. Atribuição de bobina ausente para: {{slots}}",printerAdded:"Impressora adicionada",printerUpdated:"Impressora atualizada",failedToDelete:"Falha ao excluir impressora",failedToAdd:"Falha ao adicionar impressora",failedToUpdate:"Falha ao atualizar impressora",commandSent:"Comando enviado",failedToSendCommand:"Falha ao enviar comando",turnedOn:"{{name}} ligado",failedToPowerOn:"Falha ao ligar {{name}}",scriptTriggered:"Script acionado",printStopped:"Impressão parada",printPaused:"Impressão pausada",printResumed:"Impressão retomada",referenceDeleted:"Referência excluída",detectionAreaSaved:"Área de detecção salva",failedToRunScript:"Falha ao executar script",failedToStopPrint:"Falha ao parar impressão",failedToPausePrint:"Falha ao pausar impressão",failedToResumePrint:"Falha ao retomar impressão",failedToControlChamberLight:"Falha ao controlar a luz da câmara",failedToSetSpeed:"Falha ao definir a velocidade de impressão",failedToUpdateSetting:"Falha ao atualizar configuração",failedToSkipObjects:"Falha ao ignorar objetos",failedToRereadRfid:"Falha ao reler RFID",failedToCheckPlate:"Falha ao verificar a placa",failedToUpdateLabel:"Falha ao atualizar etiqueta",failedToDeleteReference:"Falha ao excluir referência",failedToSaveDetectionArea:"Falha ao salvar área de detecção",plateCheckEnabled:"Verificação da placa ativada",plateCheckDisabled:"Verificação da placa desativada",calibrationSaved:"Calibração salva!",calibrationFailed:"Falha na calibração",rfidRereadInitiated:"Releitura de RFID iniciada"},connection:{connected:"Conectado",offline:"Offline"},queue:{inQueue:"{{count}} impressão na fila",inQueue_plural:"{{count}} impressões na fila"},controls:"Controles",rfid:{reread:"Releitura de RFID"},permission:{noAdd:"Você não tem permissão para adicionar impressoras",noEdit:"Você não tem permissão para editar impressoras",noDelete:"Você não tem permissão para excluir impressoras",noControl:"Você não tem permissão para controlar impressoras",noFiles:"Você não tem permissão para acessar arquivos de impressora",noAmsRfid:"Você não tem permissão para reler RFID AMS",noSmartPlugControl:"Você não tem permissão para controlar tomadas inteligentes",noCamera:"Você não tem permissão para visualizar câmeras"},modal:{addTitle:"Adicionar Impressora",editTitle:"Editar Impressora",myPrinter:"Minha Impressora",selectModel:"Selecionar modelo...",locationGroup:"Localização / Grupo (opcional)",locationPlaceholder:"ex.: Oficina, Escritório, Porão",autoArchiveLabel:"Arquivar automaticamente impressões concluídas",fromPrinterSettings:"A partir das configurações da impressora",modelOptional:"Modelo (opcional)",saveChanges:"Salvar alterações"},skipObjects:{tooltip:"Ignorar objetos",onlyWhilePrinting:"Ignorar objetos (apenas durante a impressão)",requiresMultiple:"Ignorar objetos (requer 2+ objetos)",title:"Ignorar Objetos",matchIdsInfo:"Correspondência de IDs com o display da sua impressora",printerShowsIds:"A tela da impressora mostra os IDs dos objetos na placa de construção",skipSelected:"Ignorar Selecionados",skipping:"Ignorando...",noObjectsSelected:"Nenhum objeto selecionado",selectObjectsToSkip:"Selecione os objetos que deseja ignorar na impressão atual",skipped:"Ignorado",objectsSkipped:"Objetos ignorados",activeCount:"{{count}} ativo",waitForLayer:"Aguarde a camada 2+ para ignorar objetos (atualmente na camada {{layer}})",skip:"Ignorar",confirmTitle:"Ignorar Objeto?",confirmMessage:'Tem certeza de que deseja ignorar "{{name}}"? Isso não pode ser desfeito.'},confirm:{deleteTitle:"Excluir Impressora",deleteMessage:'Tem certeza de que deseja excluir "{{name}}"? Isso removerá todas as configurações de conexão.',deleteArchivesNote:"Todo o histórico de impressão desta impressora será permanentemente excluído.",keepArchivesNote:"O histórico de impressão será mantido, mas não estará mais associado a esta impressora.",stopTitle:"Parar Impressão",stopMessage:'Tem certeza de que deseja parar a impressão atual em "{{name}}"? Isso cancelará o trabalho de impressão.',stopButton:"Parar Impressão",pauseTitle:"Pausar Impressão",pauseMessage:'Tem certeza de que deseja pausar a impressão atual em "{{name}}"?',pauseButton:"Pausar Impressão",resumeTitle:"Retomar Impressão",resumeMessage:'Tem certeza de que deseja retomar a impressão em "{{name}}"?',resumeButton:"Retomar Impressão",powerOnTitle:"Ligar Impressora",powerOnMessage:'Tem certeza de que deseja ligar a impressora "{{name}}"?',powerOnButton:"Ligar",powerOffTitle:"Desligar Impressora",powerOffMessage:'Tem certeza de que deseja desligar a impressora "{{name}}"?',powerOffWarning:'AVISO: "{{name}}" está imprimindo no momento! Tem certeza de que deseja desligar a impressora? Isso interromperá a impressão e pode danificar a impressora.',powerOffButton:"Desligar"},bulk:{select:"Selecionar",selectAll:"Selecionar tudo",selectByLocation:"Selecionar por local",selected:"{{count}} selecionado(s)",actions:{stop:"Parar",pause:"Pausar",resume:"Retomar",clearPlate:"Limpar mesa",clearHMS:"Limpar notificações"},confirm:{stopTitle:"Parar {{count}} impressões",stopMessage:"Isso cancelará as impressões ativas em {{count}} impressora(s). Esta ação não pode ser desfeita.",stopButton:"Parar todas",pauseTitle:"Pausar {{count}} impressões",pauseMessage:"Isso pausará as impressões ativas em {{count}} impressora(s).",pauseButton:"Pausar todas",clearPlateTitle:"Limpar {{count}} mesas de impressão",clearPlateMessage:"Isso limpará a mesa de impressão em {{count}} impressora(s) e pode iniciar trabalhos na fila.",clearPlateButton:"Limpar todas"},success:"{{action}} concluído em {{count}} impressora(s)",partial:"{{succeeded}} bem-sucedido(s), {{failed}} falhou/falharam",noneApplicable:"Nenhuma impressora selecionada está no estado correto para esta ação",selectByState:"Selecionar por estado"},discovery:{title:"Descobrir Impressoras",searching:"Procurando...",scanning:"Escaneando...",scanProgress:"Escaneando... {{scanned}}/{{total}}",foundPrinters:"{{count}} impressora(s) encontrada(s)",noPrintersFound:"Nenhuma impressora encontrada",noPrintersFoundSubnet:"Nenhuma impressora encontrada na sub-rede especificada.",noPrintersFoundNetwork:"Nenhuma impressora encontrada na rede.",allConfigured:"Todas as impressoras descobertas já estão configuradas.",alreadyAdded:"Já adicionada",select:"Selecionar",manualEntry:"Entrada Manual",addFromCloud:"Adicionar da Nuvem",subnetToScan:"Sub-rede para escanear",dockerNote:"Docker detectado. Insira a sub-rede da sua impressora em notação CIDR. Requer network_mode: host no docker-compose.yml.",scanSubnet:"Escanear Sub-rede para Impressoras",discoverNetwork:"Descobrir Impressoras na Rede",scanningSubnet:"Escaneando sub-rede para impressoras Bambu...",scanningNetwork:"Escaneando rede...",serialRequired:"Serial necessário",unknown:"Desconhecido",failedToStart:"Falha ao iniciar a descoberta"},drying:{start:"Iniciar secagem",stop:"Parar secagem",temperature:"Temperatura",duration:"Duração",hours:"horas",timeRemaining:"{{time}} restante",active:"Secagem",notSupported:"Secagem não suportada",powerRequired:"Conecte o adaptador de energia AMS para ativar a secagem",startingDrying:"Iniciando secagem...",stoppingDrying:"Parando secagem...",rotateTray:"Girar o carretel durante a secagem"},filaments:"Filamentos",openCameraOverlay:"Abrir sobreposição da câmera",openCameraWindow:"Abrir câmera em nova janela",firmwareUpdateAvailable:"Atualização de firmware disponível: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Atualizado",firmwareUpdateButton:"Atualizar",plateDetection:{noPermission:"Você não tem permissão para atualizar impressoras",enabledClick:"Verificação da placa ativada - Clique para desativar",disabledClick:"Verificação da placa desativada - Clique para ativar",manageCalibration:"Gerenciar calibração da detecção da placa",calibrationRequired:"Calibração necessária",calibrationInstructions:"Certifique-se de que a placa de construção esteja <strong>completamente vazia</strong>, em seguida clique em Calibrar.",calibrationDescription:"A calibração captura uma imagem de referência da placa vazia. Verificações futuras compararão com esta referência para detectar objetos.",calibrationTip:"<strong>Dica:</strong> Você pode armazenar até 5 calibrações para diferentes placas. O sistema usa automaticamente a melhor correspondência ao verificar.",plateEmpty:"A placa parece vazia",objectsDetected:"Objetos detectados na placa",confidence:"Confiança",difference:"Diferença",analysisPreview:"Pré-visualização da análise:",analysisLegend:"Caixa verde = área de detecção, Sobreposição vermelha = diferenças em relação à calibração",savedReferences:"Referências salvas ({{count}}/{{max}})",deleteReference:"Excluir referência",labelPlaceholder:"Etiqueta...",clickToEdit:"{{label}} - Clique para editar",clickToAddLabel:"Clique para adicionar etiqueta"},speed:{title:"Velocidade de impressão",silent:"Silencioso (50%)",standard:"Padrão (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},fans:{partCooling:"Ventilador de resfriamento da peça",auxiliary:"Ventilador auxiliar",chamber:"Ventilador da câmara"},clickToViewHmsErrors:"Clique para ver erros do HMS",estimatedCompletion:"Tempo estimado de conclusão",plateNumber:"Placa {{number}}",slotOptions:"Opções de slot",amsPopup:{friendlyName:"Nome do AMS",friendlyNamePlaceholder:"ex.: Nome amigável do AMS",serialNumber:"Número de série",firmwareVersion:"Firmware",save:"Salvar",clear:"Limpar",noEditPermission:"Você não tem permissão para renomear unidades AMS"},firmwareModal:{title:"Atualização de Firmware",titleUpToDate:"Informações do Firmware",currentVersion:"Atual:",latestVersion:"Última:",releaseNotes:"Notas de Lançamento",checkingPrereqs:"Verificando pré-requisitos...",sdCardReady:"Cartão SD pronto. Clique abaixo para enviar o firmware.",uploadedSuccess:"Firmware enviado para o cartão SD!",applyInstructions:"Para aplicar a atualização na sua impressora:",step1:"Na tela sensível ao toque da impressora, vá para <strong>Configurações</strong>",step2:"Navegue até <strong>Firmware</strong>",step3:"Selecione <strong>Atualizar a partir do cartão SD</strong>",step4:"A atualização levará de 10 a 20 minutos",done:"Concluído",starting:"Iniciando...",uploadFirmware:"Enviar Firmware",uploadFailed:"Falha ao iniciar o envio: {{error}}",uploadedToast:"Firmware enviado! Inicie a atualização na tela da impressora."},accessCodePlaceholder:"Deixe vazio para manter o atual",roi:{title:"Área de Detecção (ROI)",xStart:"Início X",yStart:"Início Y",width:"Largura",height:"Altura",instruction:"Ajuste a área de detecção para focar na placa de construção. A caixa verde na pré-visualização mostra a área atual."},developerModeWarning:"O modo desenvolvedor LAN não está ativado em: {{names}}. Alguns recursos podem não funcionar.",howToEnable:"Como ativar",incompatibleFile:"Este arquivo foi fatiado para {{slicedFor}}, mas esta impressora é uma {{printerModel}}",dropNotPrintable:"Apenas arquivos .gcode e .gcode.3mf podem ser impressos",dropToPrint:"Solte para imprimir",cannotPrint:"Impressora ocupada"},archives:{title:"Arquivos de Impressão",searchPlaceholder:"Pesquisar arquivos...",filterByPrinter:"Filtrar por impressora",filterByStatus:"Filtrar por status",sortBy:"Ordenar por",sortNewest:"Mais recentes primeiro",sortOldest:"Mais antigos primeiro",sortName:"Nome",sortDuration:"Duração",sortLargest:"Maiores primeiro",sortSmallest:"Menores primeiro",sortSize:"Tamanho",noArchives:"Nenhum arquivo encontrado",noArchivesSearch:"Nenhum arquivo corresponde à sua pesquisa",originalPrintNotVisible:"Impressão original não visível - tente limpar os filtros",noArchivesYet:"Ainda não há arquivos",prints:"impressões",pagination:{showing:"Mostrando",to:"a",of:"de",show:"Mostrar",page:"Página",all:"Todos"},loadingArchives:"Carregando arquivos...",releaseToUpload:"Solte para enviar",showAll:"Mostrar todos",showFavoritesOnly:"Mostrar apenas favoritos",gridView:"Visualização em grade",listView:"Visualização em lista",calendarView:"Visualização em calendário",logView:"Registro de impressão",manageTags:"Gerenciar etiquetas",showFailedPrints:"Mostrar impressões falhas",hideFailedPrints:"Ocultar impressões falhas",hideDuplicates:"Ocultar duplicados",viewOriginalPrint:"Clique para visualizar a impressão original (#{{id}})",printTime:"Tempo de impressão",filamentUsed:"Filamento usado",cost:"Custo",reprint:"Reimprimir",preview:"Pré-visualizar",deleteArchive:"Excluir arquivo",deleteConfirm:"Tem certeza de que deseja excluir este arquivo?",favorite:"Favorito",unfavorite:"Remover dos favoritos",viewDetails:"Ver detalhes",status:{completed:"Concluído",failed:"Falhou",stopped:"Parado"},toast:{source3mfAttached:"Arquivo de origem 3MF anexado: {{filename}}",failedUploadSource3mf:"Falha ao enviar arquivo de origem 3MF",source3mfRemoved:"Arquivo de origem 3MF removido",failedRemoveSource3mf:"Falha ao remover arquivo de origem 3MF",f3dAttached:"F3D anexado: {{filename}}",failedUploadF3d:"Falha ao enviar F3D",f3dRemoved:"F3D removido",failedRemoveF3d:"Falha ao remover F3D",timelapseAttached:"Timelapse anexado: {{filename}}",timelapseAlreadyAttached:"Timelapse já anexado",noMatchingTimelapse:"Nenhum timelapse correspondente encontrado",failedScanTimelapse:"Falha ao escanear timelapse",failedAttachTimelapse:"Falha ao anexar timelapse",timelapseRemoved:"Timelapse removido",failedRemoveTimelapse:"Falha ao remover timelapse",timelapseUploaded:"Timelapse enviado: {{filename}}",failedUploadTimelapse:"Falha ao enviar timelapse",archiveDeleted:"Arquivo excluído",failedDeleteArchive:"Falha ao excluir arquivo",addedToFavorites:"Adicionado aos favoritos",removedFromFavorites:"Removido dos favoritos",projectUpdated:"Projeto atualizado",failedUpdateProject:"Falha ao atualizar projeto",linkCopied:"Link copiado para a área de transferência",failedCopyLink:"Falha ao copiar link",photoDeleted:"Foto excluída",failedDeletePhoto:"Falha ao excluir foto",failedDeleteArchives:"Falha ao excluir arquivos",failedUpdateFavorites:"Falha ao atualizar favoritos",exportDownloaded:"Exportação baixada",exportFailed:"Falha na exportação"},menu:{print:"Imprimir",schedule:"Agendar",openInBambuStudio:"Abrir no Slicer",slice:"Fatiar",externalLink:"Link externo",viewOnMakerWorld:"Ver no MakerWorld",preview3d:"Pré-visualização 3D",viewTimelapse:"Ver Timelapse",scanForTimelapse:"Escanear Timelapse",uploadTimelapse:"Enviar Timelapse",removeTimelapse:"Remover Timelapse",downloadSource3mf:"Baixar Source 3MF",uploadSource3mf:"Enviar Source 3MF",replaceSource3mf:"Substituir Source 3MF",removeSource3mf:"Remover Source 3MF",uploadF3d:"Enviar F3D",replaceF3d:"Substituir F3D",downloadF3d:"Baixar F3D",removeF3d:"Remover F3D",download:"Baixar",copyDownloadLink:"Copiar link de download",qrCode:"Qr Code",viewPhotos:"Ver fotos",viewPhotosCount:"Ver fotos ({{count}})",projectPage:"Página do projeto",addToFavorites:"Adicionar aos favoritos",removeFromFavorites:"Remover dos favoritos",edit:"Editar",goToProject:"Ir para o projeto: {{name}}",addToProject:"Adicionar ao projeto",removeFromProject:"Remover do projeto",loading:"Carregando...",noProjectsAvailable:"Nenhum projeto disponível",select:"Selecionar",deselect:"Desmarcar",delete:"Excluir"},permission:{noReprint:"Você não tem permissão para reimprimir este arquivo",noAddToQueue:"Você não tem permissão para adicionar à fila",noUpdateArchives:"Você não tem permissão para atualizar arquivos",noUploadFiles:"Você não tem permissão para enviar arquivos",noDownload:"Você não tem permissão para baixar arquivos",noCopyLink:"Você não tem permissão para copiar links de download",noDelete:"Você não tem permissão para excluir este arquivo",noCreate:"Você não tem permissão para criar arquivos"},card:{previousPlate:"Placa anterior",nextPlate:"Próxima placa",plateNumber:"Placa {{index}}",moreOptions:"Clique com o botão direito para mais opções",addToFavorites:"Adicionar aos favoritos",removeFromFavorites:"Remover dos favoritos",cancelled:"cancelado",failed:"falha",duplicate:"duplicado",duplicateTitle:"Este modelo já foi impresso antes",openSource3mf:"Abrir source 3MF no Bambu Studio (clique com o botão direito para mais opções)",downloadF3d:"Baixar arquivo de design do Fusion 360",viewTimelapse:"Ver timelapse",viewPhoto:"Ver 1 foto",viewPhotos:"Ver {{count}} fotos",openFolder:"Abrir pasta: {{name}}",slicedFile:"Arquivo fatiado - pronto para imprimir",sourceFile:"Apenas arquivo fonte - nenhum mapeamento AMS disponível",gcode:"GCODE",source:"SOURCE",project:"Projeto: {{name}}",estimated:"Estimado: {{time}}",actual:"Real: {{time}}",accuracy:"Precisão: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} camada",layers:"{{count}} camadas",object:"{{count}} objeto",objects:"{{count}} objetos",slicedFor:"Fatiado para {{model}}",uploadedBy:"Enviado por",noPermissionReprint:"Você não tem permissão para reimprimir",noFileForReprint:"Nenhum arquivo 3MF disponível — o arquivo não pôde ser baixado da impressora quando a impressão foi registrada",noPermissionEdit:"Você não tem permissão para editar arquivos",noPermissionDelete:"Você não tem permissão para excluir arquivos",reprint:"Reimprimir",schedulePrint:"Agendar impressão",schedule:"Agendar",openInBambuStudio:"Abrir no Bambu Studio",openInBambuStudioToSlice:"Abrir no Bambu Studio para fatiar",slice:"Fatiar",externalLink:"Link externo",makerWorld:"MakerWorld: {{designer}}",viewProject:"Ver projeto",noExternalLink:"Nenhum link externo",preview3d:"Visualização 3D",download:"Baixar",edit:"Editar",delete:"Excluir"},modal:{deleteArchive:"Excluir Arquivo",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"? Esta ação não pode ser desfeita.',deleteButton:"Excluir",removeSource3mf:"Remover Source 3MF",removeSource3mfConfirm:'Tem certeza de que deseja remover o arquivo source 3MF de "{{name}}"? Isso excluirá o arquivo original do projeto do fatiador.',removeButton:"Remover",removeF3d:"Remover F3D",removeF3dConfirm:'Tem certeza de que deseja remover o arquivo de design do Fusion 360 de "{{name}}"?',removeTimelapse:"Remover Timelapse",removeTimelapseConfirm:'Tem certeza de que deseja remover o vídeo timelapse de "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Selecionar Timelapse",selectTimelapseDesc:"Nenhuma correspondência automática encontrada. Selecione o timelapse para esta impressão:",deleteArchives:"Excluir Arquivos",deleteArchivesConfirm:"Tem certeza de que deseja excluir {{count}} arquivo(s)? Esta ação não pode ser desfeita.",deleteCount:"Excluir {{count}}"},page:{title:"Arquivos",printsCount:"{{filtered}} de {{total}} impressões",dropFilesHere:"Solte arquivos .3mf aqui",releaseToUpload:"Solte para enviar",only3mfSupported:"Apenas arquivos .3mf são suportados",close:"Fechar",selected:"{{count}} selecionado(s)",selectAll:"Selecionar Todos",tags:"Tags",project:"Projeto",favorite:"Favorito",delete:"Excluir",toggledFavorites:"Favoritos alternados para {{count}} arquivo(s)",failedUpdateFavorites:"Falha ao atualizar favoritos",archivesDeleted:"{{count}} arquivo(s) excluído(s)",failedDeleteArchives:"Falha ao excluir arquivos",photoDeleted:"Foto excluída",failedDeletePhoto:"Falha ao excluir foto"},list:{name:"Nome",printer:"Impressora",date:"Data",size:"Tamanho",actions:"Ações",hasTimelapse:"Possui timelapse"},log:{date:"Data",printName:"Nome da Impressão",printer:"Impressora",user:"Usuário",status:"Status",duration:"Duração",filament:"Filamento",allPrinters:"Todas as Impressoras",allUsers:"Todos os Usuários",allStatuses:"Todos os Status",cancelled:"Cancelado",skipped:"Ignorado",dateFrom:"De",dateTo:"Até",noEntries:"Nenhuma entrada de registro de impressão encontrada",showing:"Mostrando {{count}} de {{total}} entradas",rowsPerPage:"Linhas",page:"Página",prev:"Anterior",next:"Próxima",clearLog:"Limpar Registro",clearLogTitle:"Limpar Registro de Impressão",clearLogConfirm:"Todas as entradas do registro de impressão serão permanentemente excluídas. Arquivos e itens da fila não serão afetados. Esta ação não pode ser desfeita. Tem certeza?",clearLogButton:"Limpar Tudo",cleared:"{{count}} entradas do registro de impressão limpas",clearFailed:"Falha ao limpar o registro de impressão"}},queue:{title:"Fila de Impressão",subtitle:"Agende e gerencie seus trabalhos de impressão",addToQueue:"Adicionar à Fila",print:"Imprimir",reprint:"Reimprimir",schedulePrint:"Agendar Impressão",editQueueItem:"Editar Item da Fila",printToPrinters:"Imprimir para {{count}} Impressoras",queueToPrinters:"Adicionar à Fila para {{count}} Impressoras",queueSelectedPlates:"Adicionar {{count}} placas à fila",selectAllPlates:"Selecionar todas as {{count}} placas",deselectAll:"Desmarcar tudo",printQueued:"Impressão adicionada à fila",itemsQueued:"{{count}} itens adicionados à fila",sending:"Enviando...",sendingProgress:"Enviando {{current}}/{{total}}...",adding:"Adicionando...",addingProgress:"Adicionando {{current}}/{{total}}...",savingProgress:"Salvando {{current}}/{{total}}...",clearQueue:"Limpar Fila",clearHistory:"Limpar Histórico",emptyQueue:"Fila vazia",position:"Posição",scheduledTime:"Hora Agendada",moveUp:"Mover para Cima",moveDown:"Mover para Baixo",startNow:"Iniciar Agora",printingInProgress:"Impressão em andamento...",viewArchive:"Ver Arquivo",viewInFileManager:"Ver no Gerenciador de Arquivos",itemCount:"{{count}} item",itemCount_plural:"{{count}} itens",dragToReorder:"Arraste para reordenar (apenas ASAP)",reorderHint:"A posição afeta apenas itens ASAP. Itens agendados são executados no horário definido.",sjf:{label:"SJF",tooltip:"Trabalho mais curto primeiro — o agendador prioriza impressões mais curtas"},addedBy:"Adicionado por {{name}}",nextInQueue:"Próximo na fila",clearPlate:"Limpar Placa e Iniciar Próximo",clearPlateSuccess:"Placa limpa — pronta para a próxima impressão",plateReady:"Placa limpa — pronta para a próxima impressão",plateNumber:"Placa {{index}}",quantity:"Quantidade",quantityHint:"Cria {{count}} itens na fila",activeBatches:"Lotes ativos",batchProgress:"{{completed}} de {{total}} concluídos",cancelBatch:"Cancelar restantes",batchCancelled:"Itens restantes do lote cancelados",cancelBatchConfirmTitle:"Cancelar lote",cancelBatchConfirmMessage:"Cancelar todos os itens pendentes restantes neste lote?",batch:"Lote",sections:{currentlyPrinting:"Imprimindo Atualmente",queued:"Na Fila",history:"Histórico"},status:{pending:"Pendente",waiting:"Aguardando",printing:"Imprimindo",paused:"Pausado",completed:"Concluído",failed:"Falhou",skipped:"Ignorado",cancelled:"Cancelado"},summary:{printing:"Imprimindo",queued:"Na Fila",totalTime:"Tempo Total da Fila",totalWeight:"Peso Total da Fila",history:"Histórico"},filter:{allPrinters:"Todas as Impressoras",unassigned:"Não Atribuído",allStatus:"Todos os Status",allLocations:"Todos os Locais",any:"Qualquer"},sort:{byPosition:"Ordenar por Posição",byName:"Ordenar por Nome",byPrinter:"Ordenar por Impressora",bySchedule:"Ordenar por Agendamento",byDate:"Ordenar por Data",ascendingOldest:"Crescente (mais antigo primeiro)",descendingNewest:"Decrescente (mais recente primeiro)"},badges:{staged:"Preparado (início manual)",requiresPrevious:"Requer sucesso anterior",autoPowerOff:"Desligamento automático",gcodeInjection:"G-code"},empty:{title:"Nenhuma impressão agendada",description:'Agende uma impressão a partir da página de Arquivos usando a opção "Agendar" no menu de contexto, ou arraste e solte arquivos para começar.'},time:{asap:"ASAP",overdue:"Atrasado",now:"Agora",lessThanMinute:"Em menos de um minuto",inMinutes:"Em {{count}} min",inHours:"Em {{count}} horas"},actions:{stopPrint:"Parar Impressão",startPrint:"Iniciar Impressão",requeue:"Reenfileirar"},bulkEdit:{title:"Editar {{count}} Item",title_plural:"Editar {{count}} Itens",description:"Apenas as configurações alteradas serão aplicadas aos itens selecionados.",printer:"Impressora",noChange:"— Sem alterações —",queueOptions:"Opções de Fila",staged:"Preparado (início manual)",autoPowerOff:"Desligamento automático após impressão",requirePrevious:"Requer sucesso anterior",printOptions:"Opções de Impressão",bedLevelling:"Nivelamento da Mesa",flowCalibration:"Calibração de Fluxo",vibrationCalibration:"Calibração de Vibração",layerInspection:"Inspeção da Primeira Camada",timelapse:"Timelapse",useAms:"Usar AMS",applyChanges:"Aplicar Alterações",selectAll:"Selecionar Todos",deselectAll:"Desmarcar Todos",selected:"{{count}} selecionado(s)",editSelected:"Editar Selecionados",cancelSelected:"Cancelar Selecionados"},confirm:{cancelTitle:"Cancelar Impressão Agendada",cancelMessage:'Tem certeza de que deseja cancelar "{{name}}"?',stopTitle:"Parar Impressão",stopMessage:'Tem certeza de que deseja parar a impressão atual "{{name}}"? Isso cancelará o trabalho de impressão na impressora.',removeTitle:"Remover do Histórico",removeMessage:'Tem certeza de que deseja remover "{{name}}" do histórico da fila?',clearHistoryTitle:"Limpar Histórico",clearHistoryMessage:"Tem certeza de que deseja remover todos os {{count}} itens do histórico?",cancelButton:"Cancelar Impressão",stopButton:"Parar Impressão",thisPrint:"esta impressão",thisItem:"este item"},toast:{cancelled:"Item da fila cancelado",cancelFailed:"Falha ao cancelar item",removed:"Item da fila removido",removeFailed:"Falha ao remover item",stopped:"Impressão parada",stopFailed:"Falha ao parar impressão",released:"Impressão liberada para a fila",startFailed:"Falha ao iniciar impressão",reorderFailed:"Falha ao reordenar fila",historyCleared:"Limpar {{count}} item(s) do histórico",clearHistoryFailed:"Falha ao limpar histórico",updateFailed:"Falha ao atualizar itens",bulkCancelled:"Cancelado {{count}} item(s)",bulkCancelFailed:"Falha ao cancelar itens"},timeline:{listView:"Lista",timelineView:"Linha do tempo",unassigned:"Não atribuído",noData:"Nenhuma impressão agendada para este dia",allDoneBy:"Todas as impressões concluídas até {{time}}",staged:"Preparado",filterAll:"Mostrar tudo",filterPrinting:"Imprimindo",filterQueued:"Na fila",time:{anyMoment:"a qualquer momento",minutesLeft:"{{minutes}}m restantes",hoursLeft:"{{hours}}h restantes",hoursMinutesLeft:"{{hours}}h {{minutes}}m restantes"},day:{previous:"Dia anterior",next:"Próximo dia",today:"Hoje"}},permissions:{noStopPrint:"Você não tem permissão para parar impressões",noStartPrint:"Você não tem permissão para iniciar impressões",noEdit:"Você não tem permissão para editar este item da fila",noCancel:"Você não tem permissão para cancelar este item da fila",noRequeue:"Você não tem permissão para reenfileirar itens",noRemove:"Você não tem permissão para remover este item da fila",noClearHistory:"Você não tem permissão para limpar todo o histórico",noEditItems:"Você não tem permissão para editar itens da fila",noCancelItems:"Você não tem permissão para cancelar itens da fila"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded",printStartedRemaining:"{{completed}} impressão(ões) iniciada(s), {{remaining}} enviando..."}},stats:{title:"Dashboard",subtitle:"Arraste os widgets para reorganizar. Clique no ícone de olho para ocultar.",overview:"Visão Geral",totalPrints:"Total de Impressões",successRate:"Taxa de Sucesso",totalPrintTime:"Tempo Total de Impressão",printTime:"Tempo de Impressão",totalFilament:"Filamento Total Utilizado",filamentUsed:"Filamento Utilizado",filamentCost:"Custo do Filamento",totalCost:"Custo Total",energyUsed:"Energia Utilizada",energyCost:"Custo da Energia",averagePrintTime:"Tempo Médio de Impressão",printsPerDay:"Impressões por Dia",byPrinter:"Por Impressora",printsByPrinter:"Impressões por Impressora",byMaterial:"Por Material",byMonth:"Por Mês",last7Days:"Últimos 7 Dias",last30Days:"Últimos 30 Dias",last90Days:"Últimos 90 Dias",allTime:"Todo o Tempo",quickStats:"Estatísticas Rápidas",printActivity:"Atividade de Impressão",filamentTypes:"Tipos de Filamento",filamentTrends:"Tendências de Filamento",failureAnalysis:"Análise de Falhas",timeAccuracy:"Precisão do Tempo",successful:"Bem-sucedido:",failed:"Falhou:",perfectEstimate:"100% = estimativa perfeita",noTimeAccuracyData:"Nenhum dado de precisão de tempo disponível",noFilamentData:"Nenhum dado de filamento disponível",noPrinterData:"Nenhum dado de impressora disponível",noPrintData:"Nenhum dado de impressão disponível",noPrintDataLast30Days:"Nenhum dado de impressão nos últimos 30 dias",failureReasons:"Razões de Falha",topFailureReasons:"Principais Razões de Falha",failedPrintsCount:"{{failed}} / {{total}} impressões falharam",lastWeekRate:"Última semana: {{rate}}%",resetLayout:"Redefinir Layout",recalculateCosts:"Recalcular Custos",recalculateCostsHint:"Recalcular todos os custos do arquivo usando os preços atuais do filamento",exportStats:"Exportar Estatísticas",exportAsCsv:"Exportar como CSV",exportAsExcel:"Exportar como Excel",hiddenCount:"{{count}} Oculto",exportDownloaded:"Exportação baixada",exportFailed:"Falha na exportação",layoutReset:"Layout redefinido",recalculatedCosts:"Custos recalculados para {{count}} arquivos",recalculateFailed:"Falha ao recalcular custos",loadingStats:"Carregando estatísticas...",noPermissionResetLayout:"Você não tem permissão para redefinir o layout",noPermissionRecalculate:"Você não tem permissão para recalcular custos",noPrintDataInRange:"Sem dados no período selecionado",periodFilament:"Filamento usado",periodCost:"Custo",avgPerPrint:"Média por impressão",usageOverTime:"Uso ao longo do tempo",filamentByWeight:"Peso",printDuration:"Duração da impressão",printerUtilization:"Utilização da impressora",filamentSuccess:"Sucesso por material",printHabits:"Hábitos de impressão",printTimeOfDay:"Horário de impressão",colorDistribution:"Distribuição de cores",noColorData:"Nenhum dado de cor disponível",records:"Recordes",longestPrint:"Impressão mais longa",heaviestPrint:"Impressão mais pesada",mostExpensivePrint:"Mais cara",busiestDay:"Dia mais movimentado",successStreak:"Sequência de sucesso",streakPrint:"impressão consecutiva",streakPrints:"{{count}} impressões consecutivas",printerStats:"Estatísticas da impressora",hours:"horas",avgPrints:"Méd. impressões",noArchiveData:"Nenhum dado de impressão disponível",filamentByTime:"Tempo",avgWeight:"Méd. peso",avgTime:"Méd. tempo",filamentByPrints:"Impressões",timeframe:{today:"Hoje","this-week":"Esta semana","this-month":"Este mês","last-7":"Últimos 7 dias","last-30":"Últimos 30 dias","last-90":"Últimos 90 dias","this-year":"Este ano","all-time":"Todo o período",custom:"Personalizado",from:"De",to:"Até"},allUsers:"Todos os Usuários",noUser:"Sem Usuário (Sistema)",filterByUser:"Filtrar por Usuário"},maintenance:{title:"Manutenção",overview:"Visão Geral",allOk:"Todas as manutenções estão em dia",dueCount:"{{count}} item pendente",dueCount_plural:"{{count}} itens pendentes",warningCount:"{{count}} aviso",warningCount_plural:"{{count}} avisos",totalPrintTime:"Tempo Total de Impressão",nextMaintenance:"Próxima Manutenção",nothingDue:"Nada pendente",tasks:"Tarefas",lastPerformed:"Última execução",interval:"Intervalo",hoursRemaining:"{{hours}}h restantes",hoursOverdue:"{{hours}}h atrasadas",markDone:"Marcar como Concluída",performMaintenance:"Realizar Manutenção",history:"Histórico",noHistory:"Nenhum histórico de manutenção",editPrintHours:"Editar Horas de Impressão",currentHours:"Horas Atuais",statusTab:"Status",settingsTab:"Configurações",overdueCount:"{{count}} atrasado",dueSoonCount:"{{count}} prestes a vencer",dueSoon:"Prestes a vencer",allGood:"Tudo certo",overdueBy:"Atrasado por {{duration}}",dueIn:"Vence em {{duration}}",timeLeft:"{{duration}} restantes",day:"1 dia",days:"{{count}} dias",week:"1 semana",weeks:"{{count}} semanas",month:"1 mês",months:"{{count}} meses",year:"1 ano",maintenanceTypes:"Tipos de Manutenção",maintenanceTypesDescription:"Tipos de sistema e suas tarefas de manutenção personalizadas",addCustomType:"Adicionar Tipo Personalizado",restoreDefaults:"Restaurar Tarefas Padrão",intervalType:"Tipo de Intervalo",intervalValue:"Intervalo ({{type}})",icon:"Icon",documentationLink:"Link da Documentação (opcional)",assignToPrinters:"Atribuir a Impressoras",selectAtLeastOnePrinter:"Selecione pelo menos uma impressora",addType:"Adicionar Tipo",custom:"Personalizado",printHours:"Horas de Impressão",calendarDays:"Dias de Calendário",exampleName:"ex., Substituir Filtro HEPA",viewDocumentation:"Ver documentação",timeBasedInterval:"Intervalo baseado em tempo",intervalOverrides:"Substituições de Intervalo",intervalOverridesDescription:"Personalize os intervalos para impressoras específicas",assignedToPrinters:"Atribuído a impressoras:",noPrintersAssigned:"Nenhuma impressora atribuída",addPrinterShort:"Adicionar:",printersAssignedClick:"{{count}} impressora(s) atribuída(s) - clique para gerenciar",removeFromPrinter:"Remover desta impressora",types:{lubricateCarbonRods:"Lubricar Barras de Carbono",lubricateRails:"Lubricar Trilhos Lineares",cleanNozzle:"Limpar Bico/Hotend",checkBelts:"Verificar Tensão das Correias",cleanBuildPlate:"Limpar Plataforma de Impressão",checkExtruder:"Verificar Engrenagens do Extrusor",checkCooling:"Verificar Ventiladores de Resfriamento",generalInspection:"Inspeção Geral",cleanCarbonRods:"Limpar Barras de Carbono",lubricateSteelRods:"Lubrificar Barras de Aço",cleanSteelRods:"Limpar Barras de Aço",cleanLinearRails:"Limpar Trilhos Lineares",checkPtfeTube:"Verificar Tubo PTFE",replaceHepaFilter:"Substituir Filtro HEPA",replaceCarbonFilter:"Substituir Filtro de Carbono",lubricateLeftNozzleRail:"Lubrificar Trilho do Bico Esquerdo"},maintenanceComplete:"Manutenção marcada como concluída",typeUpdated:"Tipo de manutenção atualizado",typeDeleted:"Tipo de manutenção excluído",defaultsRestored:"Restauradas {{count}} tarefa(s) padrão",printHoursUpdated:"Horas de impressão atualizadas",printerAssigned:"Impressora atribuída",printerRemoved:"Impressora removida",deleteTypeConfirm:'Excluir "{{name}}"?',deleteSystemTypeTitle:"Excluir tarefa de manutenção padrão?",deleteSystemTypeMessage:'Tem certeza de que deseja excluir a tarefa de manutenção padrão "{{name}}"?',noPermissionUpdate:"Você não tem permissão para atualizar itens de manutenção",noPermissionPerform:"Você não tem permissão para realizar manutenção",noPermissionEditTypes:"Você não tem permissão para editar tipos de manutenção",noPermissionDeleteTypes:"Você não tem permissão para excluir tipos de manutenção",noPermissionEditHours:"Você não tem permissão para editar horas de impressão",noPermissionRemovePrinter:"Você não tem permissão para remover atribuições de impressora",noPermissionAssignPrinter:"Você não tem permissão para atribuir impressoras",noPermissionEditIntervals:"Você não tem permissão para editar intervalos",configureSettings:"Configure tipos de manutenção e intervalos"},settings:{title:"Configurações",general:"Geral",tabs:{general:"Geral",smartPlugs:"Tomadas Inteligentes",notifications:"Notificações",queue:"Workflow",filament:"Filamento",network:"Rede",apiKeys:"Chaves API",virtualPrinter:"Impressora Virtual",users:"Autenticação",backup:"Backup",emailAuth:"Autenticação por Email",ldap:"LDAP"},ldap:{title:"Autenticação LDAP",enabledDesc:"A autenticação LDAP está ativada",disabledDesc:"A autenticação LDAP está desativada",disabledHint:"Configure e salve as configurações LDAP abaixo, depois ative.",enabled:"Autenticação LDAP ativada",disabled:"Autenticação LDAP desativada",feature1:"Usuários podem fazer login com credenciais LDAP",feature2:"A conta de administrador local permanece como fallback",feature3:"Grupos LDAP são mapeados para grupos BamBuddy no login",serverConfig:"Configuração do Servidor LDAP",serverUrl:"URL do servidor",serverUrlHint:"Use ldap:// para padrão ou ldaps:// para conexões SSL",security:"Segurança",securityHint:"StartTLS atualiza uma conexão simples para TLS. LDAPS usa TLS desde o início.",bindDn:"Bind DN (conta de serviço)",bindPassword:"Senha Bind",searchBase:"Base DN de pesquisa",userFilter:"Filtro de pesquisa de usuário",userFilterHint:"{username} é substituído pelo nome de usuário. Use (uid={username}) para OpenLDAP.",autoProvision:"Provisionamento automático de usuários",autoProvisionHint:"Criar automaticamente uma conta BamBuddy no primeiro login LDAP",defaultGroup:"Grupo padrão",defaultGroupNone:"— Nenhum (sem fallback) —",defaultGroupHint:"Grupo de fallback atribuído quando um usuário LDAP se autentica mas não está em nenhum grupo LDAP mapeado. Deixe vazio para manter usuários não mapeados sem permissões.",groupMapping:"Mapeamento de grupos (JSON)",groupMappingHint:"Mapear DNs de grupos LDAP para grupos BamBuddy. Grupos disponíveis: ",testConnection:"Testar conexão",settingsSaved:"Configurações LDAP salvas",errors:{serverRequired:"URL do servidor LDAP é obrigatória",searchBaseRequired:"Base DN de pesquisa é obrigatória",enableAuthFirst:"Ative a autenticação primeiro",configureLdapFirst:"Salve as configurações LDAP primeiro"}},email:{smtpSettings:"Configuração SMTP",smtpHost:"Servidor SMTP",smtpPort:"Porta SMTP",security:"Segurança",authentication:"Autenticação",username:"Nome de Usuário",password:"Senha",fromEmail:"Email de Remetente",fromName:"Nome de Remetente",testConnection:"Testar Conexão SMTP",testRecipient:"Email de Teste",sendTest:"Enviar Email de Teste",sending:"Enviando...",save:"Salvar Configurações",saving:"Salvando...",advancedAuth:"Autenticação Avançada",advancedAuthEnabled:"Autenticação Avançada está habilitada",advancedAuthEnabledDesc:"Recursos de gerenciamento de usuários baseados em email estão ativos. Novos usuários receberão senhas geradas automaticamente por email, e os usuários podem redefinir suas senhas através do recurso de esqueci minha senha.",advancedAuthDisabled:"Autenticação Avançada está desabilitada",advancedAuthDisabledDesc:"Habilite a autenticação avançada para ativar recursos baseados em email para gerenciamento de usuários.",enable:"Habilitar",disable:"Desabilitar",feature1:"Senhas são geradas automaticamente e enviadas por email para novos usuários",feature2:"Usuários podem fazer login com nome de usuário ou email",feature3:"Recurso de esqueci minha senha está disponível",feature4:"Administradores podem redefinir senhas de usuários via email",errors:{requiredFields:"Por favor, preencha todos os campos obrigatórios",usernameRequired:"Nome de usuário é obrigatório quando a autenticação está habilitada",enterTestEmail:"Por favor, insira um endereço de email de teste",smtpServerAndEmail:"Por favor, preencha o servidor SMTP e o email de remetente antes de testar",usernamePasswordRequired:"Nome de usuário e senha são obrigatórios quando a autenticação está habilitada",configureSmtpFirst:"Por favor, configure e teste as configurações SMTP primeiro",enableAuthFirst:"Por favor, habilite a autenticação primeiro para usar os recursos baseados em e-mail."},success:{settingsSaved:"Configurações SMTP salvas com sucesso"},securityOptions:{starttls:"STARTTLS (Porta 587)",ssl:"SSL/TLS (Porta 465)",none:"Nenhuma (Porta 25)"},authOptions:{enabled:"Habilitado",disabled:"Desabilitado"}},appearance:"Aparência",notifications:"Notificações",smartPlugs:"Tomadas Inteligentes",spoolman:"Spoolman",updates:"Atualizações",language:"Idioma",languageDescription:"Selecione seu idioma preferido",theme:"Tema",themeLight:"Claro",themeDark:"Escuro",themeSystem:"Sistema",defaultView:"Visualização Padrão",defaultViewDescription:"Página a ser exibida ao abrir o aplicativo",checkForUpdates:"Verificar Atualizações",autoUpdate:"Atualização Automática",currentVersion:"Versão Atual",latestVersion:"Última Versão",upToDate:"Você está atualizado",updateAvailable:"Atualização disponível",notificationLanguage:"Idioma das Notificações",notificationLanguageDescription:"Idioma para notificações push",bedCooledThreshold:"Limite de Resfriamento da Cama",bedCooledThresholdDescription:"Temperatura abaixo da qual a cama é considerada resfriada após uma impressão",userNotificationsEnabled:"Notificações do Usuário",userNotificationsEnabledDescription:"Ativa o menu de notificações do usuário e notificações por e-mail para eventos de impressão. Requer Autenticação Avançada.",userNotificationsDisabledHint:"Ative a Autenticação Avançada para usar as notificações do usuário.",notificationProviders:"Provedores de Notificação",addProvider:"Adicionar Provedor",editProvider:"Editar Provedor",providerType:"Tipo de Provedor",testNotification:"Testar Notificação",testSuccess:"Notificação de teste enviada com sucesso",testFailed:"Falha ao enviar notificação de teste",quietHours:"Horas de Silêncio",quietHoursDescription:"Não perturbe durante essas horas",quietHoursStart:"Início",quietHoursEnd:"Fim",events:{title:"Eventos de Notificação",printStart:"Impressão Iniciada",printComplete:"Impressão Concluída",printFailed:"Falha na Impressão",printStopped:"Impressão Interrompida",printProgress:"Marcos de Progresso",printProgressDescription:"Notificar em 25%, 50%, 75%",printerOffline:"Impressora Offline",printerError:"Erro na Impressora",filamentLow:"Filamento Baixo",maintenanceDue:"Manutenção Pendente",maintenanceDueDescription:"Notificar quando a manutenção for necessária"},smartPlug:{title:"Tomadas Inteligentes",add:"Adicionar Tomada Inteligente",edit:"Editar Tomada Inteligente",name:"Nome",ipAddress:"Endereço IP",linkedPrinter:"Impressora Vinculada",autoOn:"Ligar Automaticamente",autoOnDescription:"Ligar quando a impressão começar",autoOff:"Desligar Automaticamente",autoOffDescription:"Desligar após a conclusão da impressão",offDelay:"Atraso para Desligar",offDelayMinutes:"Minutos após a impressão",offDelayTemp:"Quando o bico estiver abaixo da temperatura",currentState:"Estado Atual",turnOn:"Ligar",turnOff:"Desligar"},filamentTracking:"Rastreamento de Filamento",filamentTrackingDesc:"Escolha como rastrear seus rolos de filamento. Você pode usar o inventário interno ou conectar a um servidor Spoolman externo.",filamentChecks:"Verificações de filamento",disableFilamentWarnings:"Desativar avisos de filamento",disableFilamentWarningsDesc:"Não mostrar avisos sobre filamento insuficiente ao imprimir ou adicionar à fila",preferLowestFilament:"Preferir filamento com menor resto",preferLowestFilamentDesc:"Quando vários carretéis correspondem, usar o com menos filamento restante",trackingModeBuiltIn:"Inventário Interno",trackingModeBuiltInDesc:"Correspondência automática de RFID e rastreamento de uso incluídos",trackingModeSpoolmanDesc:"Servidor de gerenciamento de filamento externo",builtInFeatureRfid:"Detecta automaticamente rolos RFID da Bambu Lab no AMS",builtInFeatureUsage:"Rastreia o consumo de filamento por impressão",builtInFeatureCatalog:"Gerencia rolos, cores e perfis de fator K",builtInFeatureThirdParty:"Rolos de terceiros podem ser atribuídos aos rolos do inventário",amsSyncButton:"Sincronizar Pesos do AMS",amsSyncTitle:"Sincronizar Pesos dos Rolos do AMS",amsSyncMessage:"Isso substituirá todos os pesos dos rolos do inventário pelos valores atuais de % restante do AMS das impressoras conectadas. Use isso para recuperar dados de peso corrompidos. As impressoras devem estar online.",amsSyncing:"Sincronizando...",amsSyncSuccess:"{{synced}} rolo(s) sincronizado(s), {{skipped}} ignorado(s)",amsSyncError:"Falha ao sincronizar pesos do AMS",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL do seu servidor Spoolman (por exemplo, http://localhost:7912)",spoolmanConnected:"Conectado",spoolmanDisconnected:"Desconectado",status:"Status",connect:"Conectar",disconnect:"Desconectar",howSyncWorks:"Como a Sincronização Funciona",syncInfoRfidOnly:"Apenas rolos oficiais da Bambu Lab com RFID são sincronizados",syncInfoAutoCreate:"Novos rolos são criados automaticamente no Spoolman na primeira sincronização",syncInfoThirdPartySkipped:"Rolos não oficiais da Bambu Lab (terceiros, reabastecidos) são ignorados",linkingExistingSpools:"Vinculando Rolos Existentes",linkingExistingSpoolsDesc:'Para vincular rolos existentes do Spoolman ao seu AMS, passe o mouse sobre um slot do AMS e clique em "Vincular ao Spoolman".',syncMode:"Modo de Sincronização",syncModeAuto:"Automático",syncModeManual:"Apenas Manual",syncModeAutoDesc:"Os dados do AMS são sincronizados automaticamente quando alterações são detectadas",syncModeManualDesc:"Somente sincronize quando acionado manualmente",syncAmsData:"Sincronizar Dados do AMS",syncAmsDataDesc:"Sincronize manualmente os dados do AMS da impressora com o Spoolman",allPrinters:"Todas as Impressoras",noDefaultPrinter:"Sem padrão (perguntar a cada vez)",sidebarOrder:"Ordem da barra lateral",saveThumbnails:"Salvar miniaturas",captureFinishPhoto:"Capturar foto de conclusão",noPrintersConfigured:"Nenhuma impressora configurada",archiveMode:{always:"Sempre criar entrada de arquivo",never:"Nunca criar entrada de arquivo",ask:"Perguntar a cada vez"},checkForUpdatesLabel:"Verificar atualizações",checkPrinterFirmware:"Verificar firmware da impressora",includeBetaUpdates:"Incluir versões beta",includeBetaUpdatesDesc:"Notificar sobre versões beta e pré-lançamento ao verificar atualizações",enableRetry:"Habilitar tentativa",homeAssistantDescription:"Controlar tomadas inteligentes via Home Assistant",environmentManagedLabel:"(Gerenciado pelo Ambiente)",autoEnabledViaEnv:"Habilitado automaticamente via variáveis de ambiente",urlFromEnvReadOnly:"Valor definido pela variável de ambiente HA_URL (somente leitura)",tokenFromEnvReadOnly:"Valor definido pela variável de ambiente HA_TOKEN (somente leitura)",mqttConnectedTo:"Conectado a",prometheusDescription:"Expor dados da impressora no formato Prometheus",noSmartPlugsTitle:"Nenhuma tomada inteligente configurada",noSmartPlugsDescription:"Adicione uma tomada inteligente baseada em Tasmota para monitorar o consumo de energia e automatizar o controle de energia.",noProvidersTitle:"Nenhum provedor configurado",noProvidersDescription:"Adicione um provedor para receber alertas.",noTemplatesAvailable:"Nenhum modelo disponível. Reinicie o backend para gerar os modelos padrão.",apiPermissionView:"Visualizar status da impressora e fila",apiPermissionEdit:"Adicionar e remover itens da fila de impressão",apiKeysEmptyTitle:"Nenhuma chave API",apiKeysEmptyDescription:"Crie uma chave API para integrar com serviços externos.",noUsersFound:"Nenhum usuário encontrado",noGroupsFound:"Nenhum grupo encontrado",noGroupsAvailable:"Nenhum grupo disponível",passwordsDoNotMatch:"As senhas não coincidem",systemGroupWarning:"Os nomes dos grupos do sistema não podem ser alterados",authDisabledTitle:"Autenticação Desativada",authDisabledFeature1:"Exigir login para acessar o sistema",authDisabledFeature2:"Criar múltiplos usuários com permissões baseadas em grupos",authDisabledFeature3:"Controlar acesso com mais de 50 permissões granulares",userHasCreated:"Este usuário criou:",userItemsQuestion:"O que você gostaria de fazer com esses itens?",deleteUserConfirm:"Tem certeza de que deseja excluir este usuário?",actionCannotBeUndone:"Esta ação não pode ser desfeita.",addFirstSmartPlug:"Adicione sua primeira tomada inteligente",providers:"Provedores",log:"Registro",testAll:"Testar tudo",testResults:"Resultados do teste",testPassedCount:"{{count}} aprovado",testFailedCount:"{{count}} falhou",messageTemplates:"Modelos de mensagem",messageTemplatesDescription:"Personalize as mensagens de notificação para cada evento.",apiKeys:"Chaves API",apiKeysDescription:"Crie chaves API para integrações externas e webhooks.",createKey:"Criar Chave",apiKeyCreated:"Chave API criada com sucesso",apiKeyCopyWarning:"Copie esta chave agora - ela não será exibida novamente!",useInApiBrowser:"Usar no Navegador API",createNewApiKey:"Criar Nova Chave API",keyName:"Nome da Chave",keyNamePlaceholder:"e.g., Home Assistant, OctoPrint",readStatus:"Status de Leitura",readStatusDescription:"Visualizar status da impressora e fila",manageQueue:"Gerenciar Fila",manageQueueDescription:"Adicionar e remover itens da fila de impressão",controlPrinter:"Controlar Impressora",controlPrinterDescription:"Pausar, retomar e parar impressões",unnamedKey:"Chave Sem Nome",lastUsed:"Último uso",read:"Ler",control:"Controlar",createFirstKey:"Crie sua primeira chave",webhookEndpoints:"Endpoints de Webhook",webhookApiKeyHint:"Use sua chave API no cabeçalho X-API-Key.",webhook:{getAllStatus:"Obter status de todas as impressoras",getSpecificStatus:"Obter status de uma impressora específica",addToQueue:"Adicionar à fila de impressão",pausePrint:"Pausar impressão",resumePrint:"Retomar impressão",stopPrint:"Parar impressão"},apiBrowser:"Navegador API",apiBrowserDescription:"Explore e teste todos os endpoints de API disponíveis.",apiKeyForTesting:"Chave API para Teste",apiKeyPlaceholder:"Cole sua chave API aqui para testar endpoints autenticados...",apiKeyHint:"Esta chave será enviada como cabeçalho X-API-Key nas solicitações.",deleteApiKeyTitle:"Excluir Chave API",deleteApiKeyMessage:"Tem certeza de que deseja excluir esta chave API? Quaisquer integrações usando esta chave deixarão de funcionar.",deleteKey:"Excluir Chave",amsDisplayThresholds:"Limiares de Exibição AMS",amsThresholdsDescription:"Configure os limiares de cores para os indicadores de umidade e temperatura do AMS.",humidity:"Umidade",goodGreen:"Bom (verde)",fairOrange:"Razoável (laranja)",aboveFairBad:"Acima do limiar razoável mostra como vermelho (ruim)",fairAlsoDryingThreshold:"Este limiar também é usado para acionar a secagem automática",temperature:"Temperatura",goodBlue:"Bom (azul)",aboveFairHot:"Acima do limiar razoável mostra como vermelho (quente)",historyRetention:"Retenção de Histórico",keepSensorHistory:"Manter histórico do sensor por",historyRetentionDescription:"Dados antigos de umidade e temperatura serão automaticamente excluídos",defaultPrintOptions:"Opções de impressão padrão",defaultPrintOptionsDescription:"Defina valores padrão para opções de impressão. Podem ser alterados no diálogo de impressão.",defaultBedLevelling:"Nivelamento da mesa",defaultBedLevellingDesc:"Nivelar automaticamente a mesa antes da impressão",defaultFlowCali:"Calibração de fluxo",defaultFlowCaliDesc:"Calibrar fluxo de extrusão",defaultVibrationCali:"Calibração de vibração",defaultVibrationCaliDesc:"Reduzir artefatos de ringing",defaultLayerInspect:"Inspeção da primeira camada",defaultLayerInspectDesc:"Inspeção IA da primeira camada",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Gravar vídeo timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Confirmação de placa livre",requirePlateClear:"Exigir confirmação de placa livre",requirePlateClearDescription:"Quando ativado, o agendador aguarda a confirmação de placa livre por impressora antes de iniciar impressões na fila em impressoras com trabalhos concluídos. Desative para fluxos de trabalho de fazenda onde as placas são verificadas fisicamente.",gcodeInjection:"Injeção de G-code",gcodeInjectionDescription:'Configure G-code personalizado para injetar no início e/ou no final das impressões para sistemas de impressão automática como Farmloop, SwapMod, AutoClear e Printflow 3D. Os snippets são configurados por modelo de impressora e aplicados quando "Injetar G-code" está ativado em um item da fila.',gcodeInjectionNoPrinters:"Nenhuma impressora encontrada. Adicione impressoras para configurar snippets de G-code.",gcodeStartLabel:"G-code inicial",gcodeEndLabel:"G-code final",gcodeStartPlaceholder:"G-code inserido antes do início da impressão...",gcodeEndPlaceholder:"G-code adicionado após o término da impressão...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Secagem Automática",queueDryingDescription:"Secar automaticamente o filamento AMS quando a impressora estiver ociosa entre impressões na fila. Usa o limite de umidade acima.",queueDryingEnabled:"Ativar secagem automática",queueDryingEnabledDescription:"Iniciar secagem AMS automaticamente quando a impressora estiver ociosa e a umidade estiver acima do limite",queueDryingBlock:"Aguardar conclusão da secagem",queueDryingBlockDescription:"Bloquear a fila de impressão até a secagem terminar. Quando desativado, impressões têm prioridade.",ambientDryingEnabled:"Secagem ambiente",ambientDryingEnabledDescription:"Secar automaticamente o filamento em impressoras ociosas quando a umidade exceder o limite, mesmo sem impressões na fila.",dryingPresets:"Predefinições de secagem",dryingPresetsDescription:"Temperatura e duração por tipo de filamento. AMS 2 Pro usa temperaturas mais baixas, AMS-HT suporta temperaturas mais altas.",dryingFilament:"Filamento",printModal:"Modal de Impressão",expandCustomMapping:"Expandir mapeamento personalizado por padrão",expandCustomMappingDescription:"Ao imprimir em várias impressoras, mostrar o mapeamento AMS por impressora expandido",authentication:"Autenticação",authEnabledDescription:"Sua instância está protegida com autenticação de usuário",authDisabledDescription:"Ative para exigir login e gerenciar o acesso dos usuários",authDisabledMessage:"Ative a autenticação para criar contas de usuário, gerenciar permissões e proteger sua instância do Bambuddy.",enableAuthentication:"Ativar Autenticação",currentUser:"Usuário Atual",changePassword:"Alterar Senha",admin:"Administrador",users:"Usuários",addUser:"Adicionar Usuário",groups:"Grupos",addGroup:"Adicionar Grupo",system:"Sistema",noDescription:"Sem descrição",userCount:"{{count}} usuários",permissionCount:"{{count}} permissões",createUser:"Criar Usuário",username:"Nome de Usuário",enterUsername:"Digite o nome de usuário",password:"Senha",enterPassword:"Digite a senha (mínimo 6 caracteres)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha",viewReleaseOnGitHub:"Ver lançamento no GitHub",turnAllPlugsOn:"Ligar todas as tomadas",turnAllPlugsOff:"Desligar todas as tomadas",clearNotificationLogs:"Limpar Logs de Notificação",clearLogsMessage:"Isso excluirá permanentemente todos os logs de notificação com mais de 30 dias. Esta ação não pode ser desfeita.",clearLogs:"Limpar Logs",resetUiPreferences:"Redefinir Preferências de UI",resetUiPreferencesMessage:"Isso redefinirá todas as preferências de UI para os padrões: ordem da barra lateral, tema, layout do painel, modos de exibição e preferências de classificação. Suas impressoras, arquivos e configurações do servidor NÃO serão afetados. A página será recarregada após a limpeza.",resetPreferences:"Redefinir Preferências",deleteGroupTitle:"Excluir Grupo",deleteGroupMessage:"Tem certeza de que deseja excluir este grupo? Usuários neste grupo perderão essas permissões.",deleteGroup:"Excluir Grupo",disableAuthenticationTitle:"Desativar Autenticação",disableAuthenticationMessage:"Tem certeza de que deseja desativar a autenticação? Isso tornará sua instância do Bambuddy acessível sem login. Todos os usuários permanecerão no banco de dados, mas a autenticação será desativada.",disableAuthentication:"Desativar Autenticação",configureBambuddy:"Configurar Bambuddy",systemDefault:"Padrão do Sistema",archiveSettings:"Configurações de Arquivo",newWindow:"Nova Janela",embeddedOverlay:"Sobreposição Incorporada",preferredSlicer:"Fatiador Preferido",preferredSlicerDescription:"Escolha qual aplicativo de fatiamento abrirá os arquivos",externalCameras:"Câmeras Externas",costTracking:"Rastreamento de Custos",printsOnly:"Apenas Impressões",totalConsumption:"Consumo Total",dataManagement:"Gerenciamento de Dados",storageUsage:"Uso de Armazenamento",storageUsageDescription:"Detalhamento do uso de dados por categoria",storageUsageTotal:"Total",storageUsageErrors:"Erros",storageUsageOtherBreakdown:"Outros (inclui ativos estáticos, scripts e arquivos de configuração)",storageUsageSystem:"Sistema",storageUsageData:"Dados",storageUsageUnavailable:"Informações de uso de armazenamento indisponíveis",clearNotificationLogsDescription:"Excluir logs de notificação com mais de 30 dias",resetUiPreferencesDescription:"Redefinir ordem da barra lateral, tema, modos de exibição e preferências de layout. Impressoras, arquivos e configurações não são afetados.",enableHomeAssistant:"Ativar Home Assistant",enableMqtt:"Ativar MQTT",useTls:"Usar TLS",enableMetricsEndpoint:"Ativar Endpoint de Métricas",availableMetrics:"Métricas Disponíveis",editUser:"Editar Usuário",deleteUserTitle:"Excluir Usuário",groupName:"Nome do Grupo",leaveEmptyForAnonymous:"Deixe vazio para anônimo",leaveEmptyForNoAuth:"Deixe vazio para sem autenticação",enterNewPassword:"Digite a nova senha",confirmNewPassword:"Confirme a nova senha",enterGroupName:"Digite o nome do grupo",enterDescriptionOptional:"Digite a descrição (opcional)",enterCurrentPassword:"Digite a senha atual",enterNewPasswordMin6:"Digite a nova senha (mínimo 6 caracteres)",toast:{keyCopied:"Chave copiada para a área de transferência",copyFailed:"Falha ao copiar a chave",keyAddedToBrowser:"Chave adicionada ao Navegador de API",clearLogsFailed:"Falha ao limpar logs",uiPreferencesReset:"Preferências de UI redefinidas. Atualizando...",authDisabled:"Autenticação desativada com sucesso",authDisableFailed:"Falha ao desativar a autenticação",apiKeyCreated:"Chave de API criada",apiKeyDeleted:"Chave de API excluída",userCreated:"Usuário criado com sucesso",userUpdated:"Usuário atualizado com sucesso",userDeleted:"Usuário excluído com sucesso",groupCreated:"Grupo criado com sucesso",groupUpdated:"Grupo atualizado com sucesso",groupDeleted:"Grupo excluído com sucesso",fillRequiredFields:"Por favor, preencha todos os campos obrigatórios",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres",enterGroupName:"Por favor, insira um nome de grupo",settingsSaved:"Configurações salvas",cameraSettingsSaved:"Configurações da câmera salvas",enterCameraUrl:"Por favor, insira a URL da câmera",passwordChanged:"Senha alterada com sucesso",connectionFailed:"Falha na conexão",testFailed:"Falha no teste",cameraConnected:"Câmera conectada{{resolution}}"},testConnection:"Testar Conexão",catalog:{spoolCatalog:"Catálogo de Carretéis",spoolCatalogDescription:"Pesos de carretéis vazios por marca/tipo. Usado para pesquisa automática de peso ao adicionar carretéis.",searchCatalog:"Pesquisar no catálogo...",addNewEntry:"Adicionar Nova Entrada",namePlaceholder:"Nome (ex.: Bambu Lab - Plástico)",weight:"Peso",type:"Tipo",default:"Padrão",custom:"Personalizado",noMatch:"Nenhuma entrada corresponde à sua pesquisa",empty:"Nenhuma entrada no catálogo",deleteEntry:"Excluir Entrada",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',resetCatalog:"Redefinir Catálogo",resetConfirm:"Redefinir catálogo para os padrões? Isso removerá todas as entradas personalizadas.",loadFailed:"Falha ao carregar o catálogo de carretéis",nameWeightRequired:"Nome e peso são obrigatórios",entryAdded:"Entrada adicionada",addFailed:"Falha ao adicionar entrada",entryUpdated:"Entrada atualizada",updateFailed:"Falha ao atualizar entrada",entryDeleted:"Entrada excluída",deleteFailed:"Falha ao excluir entrada",resetSuccess:"Catálogo redefinido para os padrões",resetFailed:"Falha ao redefinir catálogo",exported:"Exportadas {{count}} entradas",imported:"Importadas {{added}} entradas ({{skipped}} ignoradas)",importFailed:"Falha ao importar: formato JSON inválido",exportTooltip:"Exportar catálogo para JSON",importTooltip:"Importar catálogo de JSON",resetTooltip:"Redefinir para os padrões",selectedCount:"{{count}} selecionados",deleteSelected:"Excluir Selecionados",bulkDeleteConfirm:"Tem certeza de que deseja excluir {{count}} entradas?",bulkDeleted:"{{count}} entradas excluídas",bulkDeleteFailed:"Falha ao excluir entradas"},colorCatalog:{title:"Catálogo de Cores",description:"Cores de filamento por fabricante/material. Usado para pesquisa automática de cores ao adicionar carretéis.",searchColors:"Pesquisar cores...",allManufacturers:"Todos os fabricantes",addNewColor:"Adicionar Nova Cor",manufacturer:"Fabricante",colorName:"Nome da Cor",hex:"Hex",materialOptional:"Material (opcional)",showing:"Mostrando {{filtered}} de {{total}} cores",noMatch:"Nenhuma cor corresponde à sua pesquisa",empty:"Nenhuma cor no catálogo",deleteColor:"Excluir Cor",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',resetCatalog:"Redefinir Catálogo de Cores",resetConfirm:"Redefinir catálogo para os padrões? Isso removerá todas as cores personalizadas.",sync:"Sincronizar",starting:"Iniciando...",syncTooltip:"Sincronizar do FilamentColors.xyz (2000+ cores, pode levar um minuto)",loadFailed:"Falha ao carregar o catálogo de cores",fieldsRequired:"Fabricante, nome da cor e cor hex são obrigatórios",colorAdded:"Cor adicionada",addFailed:"Falha ao adicionar cor",colorUpdated:"Cor atualizada",updateFailed:"Falha ao atualizar cor",colorDeleted:"Cor excluída",deleteFailed:"Falha ao excluir cor",resetSuccess:"Catálogo de cores redefinido para os padrões",resetFailed:"Falha ao redefinir catálogo",syncUpToDate:"Já está atualizado ({{count}} cores verificadas)",syncComplete:"Adicionadas {{added}} novas cores ({{skipped}} já existiam)",syncError:"Erro de sincronização",syncFailed:"Falha ao sincronizar do FilamentColors.xyz",exported:"Exportadas {{count}} cores",imported:"Importadas {{added}} cores ({{skipped}} ignoradas)",importFailed:"Falha ao importar: formato JSON inválido",selectedCount:"{{count}} selecionados",deleteSelected:"Excluir Selecionados",bulkDeleteConfirm:"Tem certeza de que deseja excluir {{count}} cores?",bulkDeleted:"{{count}} cores excluídas",bulkDeleteFailed:"Falha ao excluir cores"},dateFormat:"Formato de data",dateFormatUs:"US (MM/DD/AAAA)",dateFormatEu:"EU (DD/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-DD)",timeFormat:"Formato de hora",timeFormat12:"12 horas (3:30 PM)",timeFormat24:"24 horas (15:30)",defaultPrinter:"Impressora padrão",defaultPrinterDescription:"Pré-selecionar esta impressora para uploads, reimpressões e outras operações.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Arraste itens na barra lateral para reordenar. Restaurar ordem padrão aqui.",setDefault:"Definir padrão",sidebarOrderSetDefaultHint:"Definir padrão aplica a ordem atual do menu aos usuários que ainda não personalizaram o seu.",sidebarDefaultSet:"Ordem padrão do menu foi definida.",sidebarDefaultCleared:"Ordem padrão do menu removida.",sidebarDefaultFailed:"Falha ao definir a ordem padrão do menu.",reset:"Redefinir",darkMode:"Modo escuro",lightMode:"Modo claro",active:"(ativo)",background:"Fundo",accent:"Destaque",style:"Estilo",bgNeutral:"Neutro",bgWarm:"Quente",bgCool:"Frio",bgOled:"OLED Preto",bgSlate:"Azul ardósia",bgForest:"Verde floresta",accentGreen:"Verde",accentTeal:"Azul-petróleo",accentBlue:"Azul",accentOrange:"Laranja",accentPurple:"Roxo",accentRed:"Vermelho",styleClassic:"Clássico",styleGlow:"Brilhante",styleVibrant:"Vibrante",themeToggleHint:"Alternar entre modo escuro e claro usando o ícone de sol/lua na barra lateral.",autoArchivePrints:"Arquivar impressões automaticamente",autoArchiveDescription:"Salvar automaticamente arquivos 3MF quando impressões forem concluídas",saveThumbnailsDescription:"Extrair e salvar imagens de pré-visualização dos arquivos 3MF",captureFinishPhotoDescription:"Tirar foto da câmera da impressora quando a impressão for concluída",ffmpegNotInstalled:"ffmpeg não instalado",ffmpegRequired:"A captura de câmera requer ffmpeg. Instale via <brew>brew install ffmpeg</brew> (macOS) ou <apt>apt install ffmpeg</apt> (Linux).",camera:"Câmera",cameraViewMode:"Modo de visualização da câmera",cameraOverlayDescription:"A câmera abre em uma sobreposição redimensionável na tela principal",cameraWindowDescription:"A câmera abre em uma janela separada do navegador",externalCamerasDescription:"Configure câmeras externas para substituir a câmera integrada da impressora. Suporta streams MJPEG, RTSP, snapshots HTTP e câmeras USB (V4L2). Quando habilitada, a câmera externa é usada para visualização ao vivo e fotos de conclusão.",cameraPlaceholderUsb:"Caminho do dispositivo (/dev/video0)",cameraPlaceholderUrl:"URL da câmera (rtsp://... ou http://...)",cameraTypeMjpeg:"Stream MJPEG",cameraTypeRtsp:"Stream RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Câmera USB (V4L2)",cameraRotation:"Rotação",test:"Testar",connected:"Conectado",disconnected:"Desconectado",currency:"Moeda",defaultFilamentCost:"Custo padrão do filamento (por kg)",electricityCost:"Custo da eletricidade por kWh",energyDisplayMode:"Modo de exibição de energia",energyModePrintDescription:"O painel mostra a soma da energia usada durante as impressões",energyModeTotalDescription:"O painel mostra a energia total dos plugues inteligentes",fileManager:"Gerenciador de arquivos",createArchiveEntry:"Criar entrada de arquivo ao imprimir",createArchiveEntryDescription:"Ao imprimir pelo gerenciador de arquivos, criar opcionalmente uma entrada de arquivo",lowDiskSpaceWarning:"Aviso de pouco espaço em disco",lowDiskSpaceDescription:"Mostrar aviso quando o espaço livre em disco ficar abaixo deste limite",printerFirmware:"Firmware da impressora",checkFirmwareDescription:"Verificar atualizações de firmware da Bambu Lab",bambuddySoftware:"Software Bambuddy",autoCheckDescription:"Verificar automaticamente novas versões ao iniciar",checkNow:"Verificar agora",updateAvailableVersion:"Atualização disponível: v{{version}}",releaseNotes:"Notas da versão",updateViaDocker:"Atualizar via Docker Compose:",installUpdate:"Instalar atualização",latestVersionRunning:"Você está usando a versão mais recente",failedToCheckUpdates:"Falha ao verificar atualizações: {{error}}",backupRestore:"Backup e Restauração",backupRestoreDescription:"Exportar/importar configurações e configurar backup do GitHub",goToBackup:"Ir para backup",externalUrl:"URL externa",externalUrlDescription:"A URL externa onde o Bambuddy está acessível. Usada para imagens de notificação e integrações externas.",bambuddyUrl:"URL do Bambuddy",externalUrlHint:"Inclua protocolo e porta (ex: http://192.168.1.100:8000)",ftpRetry:"Tentativa FTP",ftpRetryDescription:"Tentar novamente operações FTP quando o WiFi da impressora é instável. Aplica-se a downloads 3MF, uploads de impressão, downloads de timelapse e atualizações de firmware.",autoRetryDescription:"Tentar novamente automaticamente operações FTP que falharam",retryAttempts:"Tentativas de reenvio",retryDelay:"Atraso entre tentativas",connectionTimeout:"Tempo limite de conexão",time_one:"{{count}} vez",time_other:"{{count}} vezes",second_one:"{{count}} segundo",second_other:"{{count}} segundos",nSeconds:"{{count}} segundos",increaseForWeakWifi:"Aumente para impressoras com WiFi fraco",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Conecte ao Home Assistant para controlar plugues inteligentes via API REST do HA. Suporta entidades switch, light, input_boolean e script.",homeAssistantUrl:"URL do Home Assistant",longLivedAccessToken:"Token de acesso de longa duração",haTokenHint:"Crie um token no HA: Perfil → Tokens de acesso de longa duração → Criar token",connectionSuccessful:"Conexão bem-sucedida",connectionFailed:"Falha na conexão",haConnectionSuccess:"Conectado com sucesso ao Home Assistant.",haConnectionFailed:"Falha ao conectar ao Home Assistant.",mqttPublishing:"Publicação MQTT",mqttDescription:"Publique eventos do BamBuddy para um broker MQTT externo para integração com Node-RED, Home Assistant e outros sistemas de automação.",mqttEnableDescription:"Publicar eventos no broker MQTT externo",brokerHostname:"Hostname do broker",port:"Porta",usernameOptional:"Usuário (opcional)",passwordOptional:"Senha (opcional)",topicPrefix:"Prefixo do tópico",topicPrefixHint:"Os tópicos serão: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Métricas Prometheus",prometheusEndpointDescription:"Expor métricas da impressora em <code>/api/v1/metrics</code> para monitoramento Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (opcional)",bearerTokenHint:"Se definido, as requisições devem incluir <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Status da conexão",metricsPrinterState:"Estado da impressora (idle/printing/etc)",metricsPrintProgress:"Progresso da impressão 0-100%",metricsBedTemp:"Temperatura da mesa",metricsNozzleTemp:"Temperatura do bico",metricsPrintsTotal:"Total de impressões por resultado",metricsMore:"...e mais (camadas, ventoinhas, fila, uso de filamento)",smartPlugsDescription:"Conecte plugues inteligentes (Tasmota ou Home Assistant) para automatizar o controle de energia e rastrear o consumo energético das suas impressoras.",allOn:"Ligar todos",allOff:"Desligar todos",addSmartPlug:"Adicionar plugue inteligente",energySummary:"Resumo de energia",currentPower:"Potência atual",plugsOnline:"{{reachable}}/{{total}} plugues online",today:"Hoje",yesterday:"Ontem",total:"Total",enablePlugsForSummary:"Habilite os plugues para ver o resumo de energia",addNotificationProvider:"Adicionar",systemBadge:"(Sistema)",creating:"Criando...",changing:"Alterando...",deleteUserAndItems:"Excluir usuário E seus itens",deleteUserKeepItems:"Excluir usuário, manter itens (ficarão sem dono)",ok:"OK"},notification:{printStarted:{title:"Impressão Iniciada",body:"{{printer}}: {{filename}} iniciou a impressão"},printCompleted:{title:"Impressão Concluída",body:"{{printer}}: {{filename}} foi concluída com sucesso"},printFailed:{title:"Falha na Impressão",body:"{{printer}}: {{filename}} falhou"},printStopped:{title:"Impressão Interrompida",body:"{{printer}}: {{filename}} foi interrompida"},printProgress:{title:"Progresso da Impressão",body:"{{printer}}: {{filename}} está {{percent}}% concluída"},printerOffline:{title:"Impressora Offline",body:"{{printer}} está offline"},printerError:{title:"Erro na Impressora",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filamento Baixo",body:"{{printer}}: O filamento está acabando"},maintenanceDue:{title:"Manutenção Pendente",body:"{{printer}}: {{items}} precisam de atenção"}},errors:{generic:"Algo deu errado",networkError:"Erro de rede. Por favor, verifique sua conexão.",notFound:"Não encontrado",unauthorized:"Não autorizado",serverError:"Erro no servidor",validationError:"Por favor, verifique sua entrada",printerConnectionFailed:"Falha ao conectar à impressora",saveFailed:"Falha ao salvar alterações",deleteFailed:"Falha ao excluir",loadFailed:"Falha ao carregar dados"},hmsErrors:{title:"Erros - {{name}}",noErrors:"Nenhum erro",viewOnWiki:"Ver no Bambu Lab Wiki",clearInstructions:"Limpe os erros na impressora para descartá-los aqui.",clearErrors:"Limpar Erros",clearSuccess:"Erros HMS limpos",clearFailed:"Falha ao limpar erros HMS"},mqttDebug:{title:"MQTT Log de Depuração",searchPlaceholder:"Pesquisar tópico ou payload...",noMessages:"Nenhuma mensagem registrada ainda",startLoggingHint:'Clique em "Iniciar Registro" para começar a capturar mensagens MQTT',noMessagesMatch:"Nenhuma mensagem corresponde ao seu filtro",adjustFilterHint:"Tente ajustar seus critérios de pesquisa ou filtro",incoming:"Entrada",outgoing:"Saída",loggingStopped:"Registro interrompido",loggingActive:"Registro ativo - as mensagens serão atualizadas automaticamente",startLogging:"Iniciar Registro",stopLogging:"Parar Registro",clearLog:"Limpar Registro",topic:"ópico",timestamp:"Carimbo de Data/Hora",direction:"Direção",all:"Todos"},printerFiles:{title:"Gerenciador de Arquivos",storageUsed:"Usado:",storageFree:"Livre:",filterPlaceholder:"Filtrar arquivos...",deleteButton:"Excluir",deleteFiles:"Excluir {{count}} arquivos",deleteFileConfirm:'Excluir "{{name}}"? Isso não pode ser desfeito.',deleteFilesConfirm:"Excluir {{count}} arquivos selecionados? Isso não pode ser desfeito.",noFiles:"Nenhum arquivo na impressora",loadingFiles:"Carregando arquivos...",failedToLoad:"Falha ao carregar arquivos",toast:{filesDeleted:"Arquivos excluídos: {{count}}",deleteFailed:"Falha ao excluir: {{error}}"}},confirm:{delete:"Tem certeza de que deseja excluir isso?",unsavedChanges:"Você tem alterações não salvas. Tem certeza de que deseja sair?",clearQueue:"Tem certeza de que deseja limpar a fila?"},login:{title:"Bambuddy Login",subtitle:"Faça login na sua conta",username:"Nome de usuário",usernamePlaceholder:"Digite seu nome de usuário",usernameOrEmail:"Nome de usuário ou Email",usernameOrEmailPlaceholder:"Nome de usuário ou Email",password:"Senha",passwordPlaceholder:"Digite sua senha",signIn:"Entrar",signingIn:"Entrando...",forgotPassword:"Esqueceu sua senha?",loginSuccess:"Login realizado com sucesso",loginFailed:"Falha no login",enterCredentials:"Por favor, insira nome de usuário e senha",forgotPasswordTitle:"Esqueceu a Senha",forgotPasswordMessage:"Se você esqueceu sua senha, entre em contato com o administrador do sistema para redefini-la.",forgotPasswordEmailMessage:"Digite seu endereço de email e enviaremos uma nova senha.",emailAddress:"Endereço de Email",emailPlaceholder:"seu.email@exemplo.com",cancel:"Cancelar",sending:"Enviando...",sendResetEmail:"Enviar Email de Redefinição",howToReset:"Como redefinir sua senha:",resetStep1:"Entre em contato com o administrador do Bambuddy",resetStep2:"Peça para redefinir sua senha na Gestão de Usuários",resetStep3:"Eles podem definir uma nova senha temporária para você",resetStep4:"Faça login com a nova senha e altere-a nas Configurações",gotIt:"Entendi"},setup:{title:"Bambuddy Configuração",subtitle:"Configure a autenticação para sua instância do Bambuddy",enableAuth:"Ativar Autenticação",adminAccount:"Conta de Administrador",adminAccountDesc:"Se usuários administradores já existirem, a autenticação será ativada usando as contas de administrador existentes. Deixe os campos abaixo vazios para usar os administradores existentes ou insira novas credenciais para criar um novo usuário administrador.",adminUsername:"Nome de usuário do administrador",adminPassword:"Senha do administrador",optionalIfAdminExists:"(opcional se usuários administradores existirem)",adminUsernamePlaceholder:"Digite o nome de usuário do administrador (opcional)",adminPasswordPlaceholder:"Digite a senha do administrador (opcional)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha do administrador",settingUp:"Configurando...",completeSetup:"Concluir Configuração",toast:{authEnabledAdminCreated:"Autenticação ativada e usuário administrador criado",authEnabledExistingAdmins:"Autenticação ativada usando usuários administradores existentes",setupCompleted:"Configuração concluída",enterBothCredentials:"Por favor, insira o nome de usuário e a senha do administrador, ou deixe ambos vazios para usar os usuários administradores existentes",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres"}},changePassword:{title:"Alterar Senha",currentPassword:"Senha Atual",currentPasswordPlaceholder:"Digite a senha atual",newPassword:"Nova Senha",newPasswordPlaceholder:"Digite a nova senha (mínimo 6 caracteres)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a nova senha",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres",changing:"Alterando...",success:"Senha alterada com sucesso",failed:"Falha ao alterar a senha"},plateAlert:{title:"Impressão Pausada!",message:"Objetos detectados na mesa de impressão. A impressão foi automaticamente pausada. Por favor, limpe a mesa e retome a impressão.",understand:"Entendi"},camera:{title:"Visualização da Câmera",invalidPrinterId:"ID da impressora inválido",live:"Ao Vivo",snapshot:"Captura",restartStream:"Reiniciar transmissão",refreshSnapshot:"Atualizar captura",fullscreen:"Tela Cheia",exitFullscreen:"Sair da Tela Cheia",connectingToCamera:"Conectando à câmera...",capturingSnapshot:"Capturando imagem...",connectionLost:"Conexão perdida",connectionFailed:"Falha na conexão com a câmera",reconnecting:"Reconectando em {{countdown}}s... (tentativa {{attempt}}/{{max}})",reconnectNow:"Reconectar agora",cameraUnavailable:"Câmera indisponível",cameraUnavailableDesc:"Certifique-se de que a impressora está ligada e conectada.",noCamera:"Nenhuma câmera disponível",retry:"Tentar novamente",cameraStream:"Transmissão da câmera",zoomOut:"Reduzir zoom",zoomIn:"Aumentar zoom",resetZoom:"Redefinir zoom",recording:"Gravando",startRecording:"Iniciar gravação",stopRecording:"Parar gravação",chamberLight:"Alternar luz da câmara"},groups:{title:"Gerenciamento de Grupos",subtitle:"Gerenciar grupos de permissão para controle de acesso",backToSettings:"Voltar para Configurações",createGroup:"Criar Grupo",noPermission:"Você não tem permissão para acessar esta página.",system:"Sistema",noDescription:"Sem descrição",usersCount:"{{count}} usuários",permissionsCount:"{{count}} permissões",edit:"Editar",delete:"Excluir",toast:{created:"Grupo criado com sucesso",updated:"Grupo atualizado com sucesso",deleted:"Grupo excluído com sucesso",enterGroupName:"Por favor, insira um nome para o grupo"},modal:{editGroup:"Editar Grupo",createGroup:"Criar Grupo",cancel:"Cancelar",saving:"Salvando...",creating:"Criando...",saveChanges:"Salvar Alterações"},form:{groupName:"Nome do Grupo",groupNamePlaceholder:"Insira o nome do grupo",systemGroupWarning:"Os nomes dos grupos do sistema não podem ser alterados",description:"Descrição",descriptionPlaceholder:"Insira a descrição (opcional)",permissions:"Permissões ({{count}} selecionadas)"},deleteModal:{title:"Excluir Grupo",message:"Tem certeza de que deseja excluir este grupo? Os usuários deste grupo perderão essas permissões.",confirm:"Excluir Grupo"},editor:{title:"Editar Grupo",createTitle:"Criar Grupo",search:"Pesquisar permissões...",selectAll:"Selecionar Tudo",clearAll:"Limpar Tudo",permissionsSelected:"{{count}} selecionada(s)",noResults:"Nenhuma permissão corresponde à sua pesquisa"}},users:{title:"Gerenciamento de Usuários",subtitle:"Gerenciar usuários e seu acesso à sua instância do Bambuddy",backToSettings:"Voltar para Configurações",createUser:"Criar Usuário",noPermission:"Você não tem permissão para acessar esta página.",admin:"Admin",noGroups:"Sem grupos",active:"Ativo",inactive:"Inativo",edit:"Editar",delete:"Excluir",system:"Sistema",noGroupsAvailable:"Nenhum grupo disponível",table:{username:"Nome de Usuário",groups:"Grupos",status:"Status",actions:"Ações"},toast:{created:"Usuário criado com sucesso",updated:"Usuário atualizado com sucesso",deleted:"Usuário excluído com sucesso",fillRequired:"Por favor, preencha todos os campos obrigatórios",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres"},modal:{createUser:"Criar Usuário",editUser:"Editar Usuário",cancel:"Cancelar",creating:"Criando...",saving:"Salvando...",saveChanges:"Salvar Alterações",advancedAuthSubtitle:"com Autenticação Avançada"},form:{username:"Nome de Usuário",usernamePlaceholder:"Insira o nome de usuário",email:"Email",emailPlaceholder:"user@example.com",password:"Senha",passwordPlaceholder:"Insira a senha",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha",newPasswordPlaceholder:"Insira a nova senha",confirmNewPasswordPlaceholder:"Confirme a nova senha",leaveBlankToKeep:"deixe em branco para manter a atual",groups:"Grupos",optional:"opcional",autoGeneratedPassword:"Uma senha segura será gerada automaticamente e enviada por e-mail ao usuário.",passwordManagedByAdvancedAuth:'A senha é gerenciada pela Autenticação Avançada. Use "Redefinir Senha" para enviar uma nova senha ao usuário por e-mail.',resetPassword:"Redefinir Senha",resettingPassword:"Redefinindo Senha..."},deleteModal:{title:"Excluir Usuário",message:"Tem certeza de que deseja excluir este usuário? Esta ação não pode ser desfeita.",confirm:"Excluir Usuário"}},streamOverlay:{title:"Stream Overlay",invalidPrinterId:"ID da impressora inválido",cameraStream:"Transmissão da câmera",progress:"Progresso da impressão",eta:"ETA",printerIdle:"Impressora ociosa",printerOffline:"Impressora offline",status:{printing:"Imprimindo",paused:"Pausado",finished:"Concluído",failed:"Falhou",idle:"Ocioso",unknown:"Desconhecido"}},profiles:{title:"Perfis",subtitle:"Gerencie seus presets de fatiador e calibrações de avanço de pressão",tabs:{cloud:"Perfis na Nuvem",local:"Perfis Locais",kprofiles:"K-Perfis"},localProfiles:{title:"Perfis Locais",subtitle:"Importe e gerencie presets de fatiador do OrcaSlicer",import:"Importar Perfis",importDesc:"Solte arquivos .bbscfg, .bbsflmt, .orca_filament, .zip ou .json aqui",importing:"Importando...",search:"Pesquisar presets locais...",noPresets:"Nenhum preset local ainda",badge:"Local",edit:"Editar",delete:"Excluir",cancel:"Cancelar",deleteConfirmTitle:"Excluir Preset",deleteConfirm:"Tem certeza de que deseja excluir este preset? Esta ação não pode ser desfeita.",source:"Fonte",inheritsFrom:"Herdado de",filamentType:"Tipo",vendor:"Fornecedor",compatiblePrinters:"Impressoras Compatíveis",nozzleTemp:"Temperatura do Bico",cost:"Custo",density:"Densidade",pressureAdvance:"Avanço de Pressão",filament:"Filamento",process:"Processo",printer:"Impressora",toast:{importSuccess:"{{count}} preset(s) importada(s)",importSkipped:"{{count}} preset(s) ignorada(s) (duplicadas)",importError:"{{count}} erro(s) durante a importação",deleted:"Preset excluído",updated:"Preset atualizado"}},connectedAs:"Conectado como",logout:"Sair",noLogoutPermission:"Você não tem permissão para sair",failedToLoad:"Falha ao carregar perfis",retry:"Tentar novamente",time:{justNow:"Agora mesmo",minsAgo:"há {{count}} minutos",hoursAgo:"há {{count}} horas",daysAgo:"há {{count}} dias"},toast:{loggedOut:"Desconectado"},login:{title:"Conectar ao Bambu Cloud",subtitle:"Sincronize seus presets de fatiador entre dispositivos",email:"Email",password:"Senha",region:"Região",regionGlobal:"Global",regionChina:"China",verificationCode:"Código de Verificação",totpCode:"Código do Autenticador",checkEmail:"Verifique seu email ({{email}}) para um código de 6 dígitos",enterTotpHint:"Digite o código de 6 dígitos do seu aplicativo autenticador",accessToken:"Token de Acesso",accessTokenHint:"Cole seu token de acesso Bambu Lab (do Bambu Studio)",back:"Voltar",loginButton:"Entrar",verifyButton:"Verificar",setTokenButton:"Definir Token",useToken:"Usar token de acesso em vez disso",useEmail:"Entrar com email em vez disso",toast:{loggedIn:"Conectado com sucesso",codeSent:"Código de verificação enviado para seu email",enterTotp:"Digite o código do seu aplicativo autenticador",tokenSet:"Token definido com sucesso"}},presets:{myPreset:"Meu preset (editável)",duplicate:"Duplicar",editable:"Editável",failedToLoadDetails:"Falha ao carregar detalhes do preset",deleteConfirm:"Excluir este preset?",deleteWarning:'Isso excluirá permanentemente "{{name}}" do Bambu Cloud. Esta ação não pode ser desfeita.',noDuplicatePermission:"Você não tem permissão para duplicar presets",noEditPermission:"Você não tem permissão para editar presets",noDeletePermission:"Você não tem permissão para excluir presets",types:{filament:"Preset de filamento",printer:"Preset de impressora",process:"Preset de processo"},toast:{deleted:"Preset excluído",created:"Preset criado",updated:"Preset atualizado",duplicated:"Preset duplicado",fieldAdded:'Campo "{{key}}" adicionado',exported:"Preset exportado"},baseLabel:"Base: {{name}}",currentLabel:"Atual: {{name}}",newPreset:"Novo Preset",editPreset:"Editar Preset",duplicatePreset:"Duplicar Preset",createNewPreset:"Criar Novo Preset",customizeSettings:"Personalizar configurações para seu novo preset",compareWithBase:"Comparar com o preset base",compare:"Comparar",basePreset:"Preset Base",selectBasePreset:"Selecionar preset base...",presetName:"Nome do Preset",myCustomPreset:"Meu preset personalizado",inheritsFrom:"Herdado de",dropJsonToImport:"Solte o arquivo JSON para importar",tabs:{common:"Comum",allFields:"Todos os Campos"},availableFields:"Campos Disponíveis",searchFieldsPlaceholder:"Pesquisar campos...",noMatchingFields:"Nenhum campo correspondente",allFieldsAdded:"Todos os campos adicionados",addCustomField:"Adicionar campo personalizado",yourOverrides:"Suas Substituições",noOverridesYet:"Nenhuma substituição ainda",clickFieldsToAdd:"Clique nos campos à esquerda para adicioná-los",saveAsTemplate:"Salvar como modelo",jsonTip:"Dica: Arraste e solte um arquivo .json em qualquer lugar deste modal para importar configurações"},cloudView:{searchPlaceholder:"Pesquisar presets...",templates:"Modelos",refresh:"Atualizar",newPreset:"Novo Preset",clearFilters:"Limpar filtros",compareMode:"Modo de Comparação",selectAnotherPreset:"Selecionar outro preset {{type}}",clickTwoPresets:"Clique em dois presets do mesmo tipo para comparar",selectFirst:"1. Selecionar primeiro",selectSecond:"2. Selecionar segundo",compareNow:"Comparar Agora",lastSynced:"Última sincronização:",showingCount:"Mostrando {{showing}} de {{total}} presets",noPresetsFound:"Nenhum preset encontrado",columns:{filament:"Filamento",process:"Processo",printer:"Impressora"},noFilamentPresets:"Nenhum preset de filamento",noProcessPresets:"Nenhum preset de processo",noPrinterPresets:"Nenhum preset de impressora",filters:{type:"Tipo",owner:"Proprietário",printer:"Impressora",nozzle:"Bico",filament:"Filamento",layer:"Camada",all:"Todos",myPresets:"Meus Presets",builtIn:"Integrado",process:"Processo"},noTemplatesPermission:"Você não tem permissão para gerenciar modelos",noRefreshPermission:"Você não tem permissão para atualizar perfis",noCreatePermission:"Você não tem permissão para criar presets"},templates:{title:"Modelos Rápidos",noTemplates:"Nenhum modelo ainda",createFirst:"Crie modelos a partir do editor de presets",typeFilter:"Tipo:",deleteTitle:"Excluir Modelo",deleteWarning:"Esta ação não pode ser desfeita",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',namePlaceholder:"Nome do modelo",descriptionPlaceholder:"Descrição",settingsJson:"Configurações (JSON)",fieldsCount:"{{count}} campos",shownInModals:"Exibido em modais",hiddenInModals:"Oculto em modais",apply:"Aplicar",toast:{deleted:"Modelo excluído",updated:"Modelo atualizado",created:"Modelo criado",applied:"Modelo aplicado"}}},support:{debugLoggingActive:"Registro de depuração ativo",manageLogs:"Gerenciar",collectItem7:"Conectividade da impressora e versões de firmware",collectItem8:"Status de integração (Spoolman, MQTT, HA)",collectItem9:"Interfaces de rede (somente sub-redes)",collectItem10:"Versões de pacotes Python",collectItem11:"Verificações de integridade do banco de dados",collectItem12:"Detalhes do ambiente Docker"},fileManager:{title:"Gerenciador de Arquivos",subtitle:"Organize e gerencie seus arquivos de impressão",uploadFiles:"Enviar Arquivos",newFolder:"Nova Pasta",folderName:"Nome da Pasta",folderNamePlaceholder:"ex.: Peças Funcionais",renameFile:"Renomear Arquivo",renameFolder:"Renomear Pasta",moveFiles:"Mover {{count}} Arquivo(s)",rootNoFolder:"Raiz (Sem Pasta)",current:"Atual",linkFolder:"Vincular Pasta",linkFolderDescription:'Vincular "{{name}}" a um projeto ou arquivo para acesso rápido.',project:"Projeto",archive:"Arquivo",noProjectsFound:"Nenhum projeto encontrado",noArchivesFound:"Nenhum arquivo encontrado",unlink:"Desvincular",link:"Vincular",dragDropFiles:"Arraste e solte os arquivos aqui",dropFilesHere:"Solte os arquivos aqui",orClickToBrowse:"ou clique para procurar",allFileTypesSupported:"Todos os tipos de arquivos são suportados. Arquivos ZIP serão extraídos.",zipFilesDetected:"Arquivos ZIP detectados",zipExtractOptions:"Arquivos ZIP serão extraídos. Escolha como lidar com a estrutura de pastas:",preserveZipStructure:"Preservar estrutura de pastas do ZIP",createFolderFromZip:"Criar pasta a partir do nome do arquivo ZIP",stlThumbnailGeneration:"Geração de miniaturas STL",zipMayContainStl:"Arquivos ZIP podem conter arquivos STL. Miniaturas podem ser geradas durante a extração.",thumbnailsCanBeGenerated:"Miniaturas podem ser geradas para arquivos STL. Modelos grandes podem levar mais tempo para processar.",generateThumbnailsForStl:"Gerar miniaturas para arquivos STL",threemfDetected:"Arquivos 3MF detectados",threemfExtractionInfo:"Modelo da impressora, material, cor e configurações de impressão serão extraídos automaticamente dos arquivos 3MF.",willBeExtracted:"Será extraído",filesExtracted:"{{count}} arquivos extraídos",uploadComplete:"Upload concluído: {{succeeded}} bem-sucedidos",uploadFailed:"Falha no envio",zipFilesFailed:"{{count}} arquivos falharam",uploading:"Enviando...",changeLink:"Alterar link...",linkTo:"Vincular a...",linkToProjectOrArchive:"Vincular a projeto ou arquivo",addToQueue:"Adicionar à fila",schedulePrint:"Agendar impressão",generateThumbnail:"Gerar miniatura",generateThumbnails:"Gerar miniaturas",generateThumbnailsForMissing:"Gerar miniaturas para arquivos STL que não possuem",gridView:"Visualização em grade",listView:"Visualização em lista",lowDiskSpaceWarning:"Aviso de pouco espaço em disco",lowDiskSpaceDetails:"Apenas {{free}} livres de {{total}} no total. O limite está definido para {{threshold}} GB nas configurações.",files:"Arquivos",folders:"Pastas",size:"Tamanho",free:"Livre",allFiles:"Todos os arquivos",wrap:"Quebrar texto",enableTextWrapping:"Ativar quebra de texto",disableTextWrapping:"Desativar quebra de texto",dragToResizeTooltip:"Arraste para redimensionar, clique duas vezes para redefinir",searchFiles:"Pesquisar arquivos...",allTypes:"Todos os tipos",prints:"Impressões",ascending:"Crescente",descending:"Decrescente",resultsCount:"{{showing}} de {{total}} arquivos",selectAll:"Selecionar tudo",deselectAll:"Desmarcar tudo",selected:"{{count}} selecionado(s)",adding:"Adicionando...",loadingFiles:"Carregando arquivos...",folderIsEmpty:"A pasta está vazia",noFilesYet:"Nenhum arquivo ainda",folderEmptyDescription:"Envie arquivos ou mova arquivos para esta pasta para começar.",noFilesDescription:"Envie arquivos para começar a organizar seus arquivos relacionados à impressão.",noMatchingFiles:"Nenhum arquivo correspondente",noMatchingFilesDescription:"Nenhum arquivo corresponde aos seus critérios de pesquisa ou filtro.",clearFilters:"Limpar filtros",printedCount:"Impresso {{count}}x",uploadedBy:"Enviado por",deleteFolder:"Excluir pasta",deleteFile:"Excluir arquivo",deleteFilesCount:"Excluir {{count}} arquivos",deleteFolderConfirm:"Tem certeza de que deseja excluir esta pasta? Todos os arquivos dentro também serão excluídos.",deleteFileConfirm:"Tem certeza de que deseja excluir este arquivo?",deleteFilesConfirm:"Tem certeza de que deseja excluir {{count}} arquivos selecionados? Esta ação não pode ser desfeita.",deleting:"Excluindo...",noPermissionRenameFolder:"Você não tem permissão para renomear pastas",noPermissionLinkFolder:"Você não tem permissão para vincular pastas",noPermissionDeleteFolder:"Você não tem permissão para excluir pastas",noPermissionPrint:"Você não tem permissão para imprimir",noPermissionAddToQueue:"Você não tem permissão para adicionar à fila",noPermissionDownload:"Você não tem permissão para baixar arquivos",noPermissionRenameFile:"Você não tem permissão para renomear este arquivo",noPermissionGenerateThumbnail:"Você não tem permissão para gerar miniaturas",noPermissionDeleteFile:"Você não tem permissão para excluir este arquivo",noPermissionCreateFolder:"Você não tem permissão para criar pastas",noPermissionUpload:"Você não tem permissão para enviar arquivos",noPermissionMoveFiles:"Você não tem permissão para mover arquivos",noPermissionDeleteFiles:"Você não tem permissão para excluir arquivos",linkExternal:"Vincular externo",linkExternalFolder:"Vincular pasta externa",linkExternalFolderDescription:"Montar um diretório do host (NAS, USB, compartilhamento de rede) no Gerenciador de Arquivos. Os arquivos não são copiados — são acessados diretamente do caminho original.",externalFolderNamePlaceholder:"ex. Impressões NAS",externalPath:"Caminho do host",externalPathHelp:"Caminho absoluto do diretório no host Docker. Deve estar montado como bind no contêiner.",readOnly:"Somente leitura",readOnlyHelp:"impede uploads e exclusões",showHiddenFiles:"Mostrar arquivos ocultos (arquivos ponto)",externalFolder:"Pasta externa",scanFolder:"Escanear",toast:{folderCreated:"Pasta criada",folderDeleted:"Pasta excluída",fileDeleted:"Arquivo excluído",filesDeleted:"Excluídos {{count}} arquivos",filesMoved:"Arquivos movidos",folderLinked:"Pasta vinculada",folderUnlinked:"Pasta desvinculada",externalFolderLinked:"Pasta externa vinculada e escaneada",folderScanned:"Escaneamento concluído: {{added}} adicionados, {{removed}} removidos",addedToQueue:"Adicionado {{count}} arquivo(s) à fila",addedToQueuePartial:"Adicionado {{added}} arquivo(s), {{failed}} falharam",failedToAddToQueue:"Falha ao adicionar arquivos: {{error}}",fileRenamed:"Arquivo renomeado",folderRenamed:"Pasta renomeada",thumbnailsGenerated:"Geradas {{count}} miniatura(s)",thumbnailsGeneratedPartial:"Geradas {{succeeded}} miniatura(s), {{failed}} falharam",noStlMissingThumbnails:"Nenhum arquivo STL sem miniatura",failedToGenerateThumbnails:"Falha ao gerar miniaturas: {{error}}",thumbnailGenerated:"Miniatura gerada",failedToGenerateThumbnail:"Falha ao gerar miniatura: {{error}}"}},projects:{title:"Projetos",subtitle:"Organize e acompanhe seus projetos de impressão 3D",newProject:"Novo Projeto",editProject:"Editar Projeto",deleteProject:"Excluir Projeto",projectName:"Nome do Projeto",description:"Descrição",noProjects:"Nenhum projeto ainda",noProjectsFiltered:"Nenhum projeto {{status}}",noProjectsFilteredHelp:"Você não tem nenhum projeto {{status}}. Os projetos aparecerão aqui quando seu status mudar.",createFirst:"Crie seu primeiro projeto para começar a organizar impressões relacionadas, acompanhar o progresso e gerenciar suas construções.",createFirstButton:"Crie Seu Primeiro Projeto",create:"Criar",files:"Arquivos",prints:"Impressões",plates:"Placas",parts:"Peças",lastModified:"Última Modificação",deleteConfirm:"Tem certeza de que deseja excluir este projeto? Arquivos e itens da fila serão desvinculados, mas não excluídos.",addFiles:"Adicionar Arquivos",removeFile:"Remover Arquivo",viewDetails:"Ver Detalhes",namePlaceholder:"ex., Voron 2.4 Build",descriptionPlaceholder:"Descrição opcional...",color:"Cor",targetPlates:"Placas Alvo",targetPlatesPlaceholder:"ex., 25",targetPlatesHelp:"Número de trabalhos de impressão",targetParts:"Peças Alvo",targetPartsPlaceholder:"ex., 150",targetPartsHelp:"Total de objetos necessários",tagsLabel:"Tags (separadas por vírgula)",tagsPlaceholder:"ex., voron, funcional, presente",dueDate:"Data de Vencimento",priority:"Prioridade",priorityLow:"Baixa",priorityNormal:"Normal",priorityHigh:"Alta",priorityUrgent:"Urgente",statusActive:"Ativo",statusCompleted:"Concluído",statusArchived:"Arquivado",done:"Concluído",completed:"Concluído",failed:"Falhou",inQueue:"Na fila",noPrintsYet:"Nenhuma impressão ainda",printJobs:"Trabalhos de impressão (placas)",partsPrinted:"Peças impressas",failedParts:"Peças falhadas",import:"Importar",export:"Exportar",importProject:"Importar projeto",exportAll:"Exportar todos os projetos",loading:"Carregando projetos...",noEditPermission:"Você não tem permissão para editar projetos",noDeletePermission:"Você não tem permissão para excluir projetos",noCreatePermission:"Você não tem permissão para criar projetos",noImportPermission:"Você não tem permissão para importar projetos",noExportPermission:"Você não tem permissão para exportar projetos",toast:{created:"Projeto criado",updated:"Projeto atualizado",deleted:"Projeto excluído",imported:"Projeto importado",multipleImported:"{{count}} projetos importados",importFailed:"Falha na importação",exported:"Projetos exportados (apenas metadados)"}},projectDetail:{notFound:"Projeto não encontrado",backToProjects:"Voltar para Projetos",export:"Exportar",exportProject:"Exportar projeto",noExportPermission:"Você não tem permissão para exportar projetos",noEditPermission:"Você não tem permissão para editar projetos",partOf:"Parte de:",priorityLabel:"Prioridade:",noPrints:"Nenhuma impressão neste projeto ainda",status:{active:"Ativo",completed:"Concluído",archived:"Arquivado"},priority:{low:"Baixa",normal:"Normal",high:"Alta",urgent:"Urgente"},dueDate:{overdue:"Atrasado",today:"Vence hoje",daysLeft:"{{count}} dias restantes"},progress:{platesProgress:"Progresso das Placas",partsProgress:"Progresso das Peças",printJobs:"Trabalhos de Impressão",parts:"Peças",percentComplete:"{{percent}}% concluído",remaining:"{{count}} restantes"},stats:{printJobs:"Trabalhos de Impressão",total:"total",failed:"{{count}} falhou",partsPrinted:"{{count}} peças impressas",printTime:"Tempo de Impressão",filamentUsed:"Filamento Usado"},cost:{title:"Rastreamento de Custos",filamentCost:"Custo do Filamento",energy:"Energia",totalCost:"Custo Total",total:"Total",includesBom:"incl. lista de materiais",budget:"Orçamento",remaining:"Restante"},subProjects:{title:"Sub-projetos ({{count}})"},notes:{title:"Notas",noEditPermission:"Você não tem permissão para editar notas",placeholder:"Adicione notas sobre este projeto...",empty:"Nenhuma nota ainda. Clique em Editar para adicionar notas."},files:{title:"Arquivos",linkFolders:"Vincular pastas do Gerenciador de Arquivos",forQuickAccess:"a este projeto para acesso rápido.",fileCount:"{{count}} arquivo(s)",empty:"Nenhuma pasta vinculada. Vá para o Gerenciador de Arquivos e vincule uma pasta a este projeto."},bom:{title:"Lista de Materiais",acquired:"{{completed}}/{{total}} adquiridos",showAll:"Mostrar todos",hideDone:"Ocultar concluídos",addPart:"Adicionar Peça",noAddPermission:"Você não tem permissão para adicionar peças",partNamePlaceholder:"Nome da peça (ex.: parafusos M3x8)",partName:"Nome da peça",qty:"Quantidade",price:"Preço ({{currency}})",sourcingUrlPlaceholder:"URL de fornecimento (opcional)",remarksPlaceholder:"Observações (opcional)",deletePart:"Excluir Peça",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',noUpdatePermission:"Você não tem permissão para atualizar peças",noEditPermission:"Você não tem permissão para editar peças",noDeletePermission:"Você não tem permissão para excluir peças",totalCost:"Custo total:",empty:"Nenhuma peça na lista de materiais. Adicione hardware, eletrônicos ou outros componentes para rastrear o que precisa ser adquirido."},timeline:{title:"Linha do Tempo de Atividades",empty:"Nenhuma atividade ainda."},template:{saveAsTemplate:"Salvar como Modelo",noCreatePermission:"Você não tem permissão para criar modelos"},queue:{title:"Fila",viewAll:"Ver todos",printing:"{{count}} imprimindo",queued:"{{count}} na fila"},prints:{title:"Impressões ({{count}})"},toast:{projectUpdated:"Projeto atualizado",partAdded:"Peça adicionada",partRemoved:"Peça removida",exportFailed:"Falha na exportação",projectExported:"Projeto exportado",templateCreated:"Modelo criado"}},system:{title:"Informações do Sistema",version:"Versão",uptime:"Tempo de Atividade",cpuUsage:"Uso da CPU",memoryUsage:"Uso da Memória",diskUsage:"Uso do Disco",networkInfo:"Informações de Rede",logs:"Logs",debugMode:"Modo de Depuração",enableDebug:"Ativar Registro de Depuração",disableDebug:"Desativar Registro de Depuração",downloadLogs:"Baixar Logs",clearLogs:"Limpar Logs",dockerInfo:"Informações do Docker",containerName:"Nome do Contêiner",imageName:"Nome da Imagem",platform:"Plataforma",architecture:"Arquitetura"},library:{title:"Biblioteca de Filamentos",addFilament:"Adicionar Filamento",editFilament:"Editar Filamento",deleteFilament:"Excluir Filamento",vendor:"Fornecedor",material:"Material",color:"Cor",kFactor:"Fator K",temperature:"Temperatura",noFilaments:"Nenhum filamento na biblioteca",deleteConfirm:"Tem certeza de que deseja excluir este filamento?",importFromPrinter:"Importar da Impressora",exportToFile:"Exportar para Arquivo"},spoolman:{title:"Integração com Spoolman",enabled:"Spoolman Ativado",url:"URL do Spoolman",connected:"Conectado",disconnected:"Não Conectado",testConnection:"Testar Conexão",sync:"Sincronizar",syncing:"Sincronizando...",lastSync:"Última Sincronização",linkToSpoolman:"Vincular ao Spoolman",openInSpoolman:"Abrir no Spoolman",unlinkSpool:"Desvincular Carretel",unlinkConfirmTitle:"Desvincular carretel?",unlinkConfirmMessage:"Isso desconectará o carretel do Spoolman. Os dados do carretel no Spoolman permanecerão inalterados.",selectSpool:"Selecionar Carretel",noUnlinkedSpools:"Nenhum carretel desvinculado disponível",linkSuccess:"Carretel vinculado ao Spoolman com sucesso",linkFailed:"Falha ao vincular carretel",unlinkSuccess:"Carretel desvinculado do Spoolman com sucesso",unlinkFailed:"Falha ao desvincular carretel",spoolId:"Carretel ID (Spool ID)",fillSourceLabel:"(Spoolman)",weight:"Peso",remaining:"Restante",disableWeightSync:"Desativar Sincronização de Peso Estimado do AMS",disableWeightSyncDesc:"Não atualize a capacidade restante a partir das estimativas do AMS. Use isso se preferir o rastreamento de uso do Spoolman em vez das estimativas baseadas em porcentagem do AMS. Novos carretéis ainda usarão a estimativa do AMS como seu peso inicial.",reportPartialUsage:"Relatar Uso Parcial para Impressões Falhadas",reportPartialUsageDesc:"Quando uma impressão falha ou é cancelada, relate o filamento estimado usado até aquele ponto com base no progresso das camadas."},inventory:{title:"Inventário de Carretéis",addSpool:"Adicionar Carretel",editSpool:"Editar Carretel",material:"Material",selectMaterial:"Selecionar material...",subtype:"Subtipo",brand:"Marca",searchBrand:"Pesquisar marca...",useCustomBrand:'Usar "{{brand}}"',useCustomMaterial:"Usar material personalizado: {{material}}",colorName:"Nome da Cor",colorNamePlaceholder:"Jade White, Fire Red...",color:"Cor",hexColor:"Cor Hexadecimal",pickColor:"Escolher cor personalizada",labelWeight:"Peso da Etiqueta",coreWeight:"Peso do Carretel Vazio",searchSpoolWeight:"Pesquisar peso do carretel...",weightUsed:"Usado",currentWeight:"Peso Restante",measuredWeight:"Peso Medido",spoolName:"Bobina",costPerKg:"Custo por kg",measuredWeightError:"O peso medido deve estar entre {{min}}g e {{max}}g.",slicerFilament:"Filamento do Fatiador",slicerFilamentName:"Nome do Predefinido do Fatiador",slicerPreset:"Predefinido do Fatiador",searchPresets:"Pesquisar predefinições de filamento...",selectedPreset:"Selecionado",noPresetsFound:"Nenhuma predefinição encontrada",tempOverrides:"Substituições de Temperatura",note:"Nota",notePlaceholder:"Quaisquer notas adicionais sobre este spool...",archive:"Arquivar",restore:"Restaurar",noSpools:"Nenhum carretel ainda. Adicione seu primeiro carretel para começar.",noManualSpools:"Nenhum carretel adicionado manualmente disponível. Adicione um carretel ao seu inventário primeiro.",kProfiles:"K-Perfis",addKProfile:"Adicionar K-Perfil",assignSpool:"Atribuir Carretel",unassignSpool:"Desatribuir",assignSuccess:"Carretel atribuído e slot AMS configurado",assignFailed:"Falha ao atribuir carretel",selectSpool:"Selecione um carretel para atribuir a este slot",assigned:"Atribuído",assigning:"Atribuindo...",searchSpools:"Pesquisar carretéis...",showAllSpools:"Mostrar todos os carretéis",allMaterials:"Todos os Materiais",filterByBrand:"Filtrar por marca...",showArchived:"Mostrar arquivados",quickAdd:"Adição rápida (Estoque)",quantity:"Quantidade",stock:"Estoque",configured:"Configurado",spoolsCreated:"{{count}} carretéis criados",spoolCreated:"Carretel criado",spoolUpdated:"Carretel atualizado",spoolDeleted:"Carretel excluído",spoolArchived:"Carretel arquivado",spoolRestored:"Carretel restaurado",deleteConfirm:"Tem certeza de que deseja excluir este carretel? Esta ação não pode ser desfeita.",archiveConfirm:"Tem certeza de que deseja arquivar este carretel?",advancedSettings:"Configurações Avançadas",filamentInfoTab:"Informações do Filamento",paProfileTab:"Perfil PA",filamentInfo:"Filamento",additional:"Adicional",loadingPresets:"Carregando predefinições da nuvem...",cloudConnected:"Nuvem conectada",cloudNotConnected:"Nuvem não conectada (usando padrões)",recentColors:"Recentes",searchColors:"Pesquisar cores...",searchResults:"Resultados da pesquisa",allColors:"Todas as cores",commonColors:"Cores comuns",showLess:"Mostrar menos",showAll:"Mostrar tudo",noColorsFound:"Nenhuma cor corresponde à sua pesquisa",noResults:"Nenhum resultado encontrado",selectMaterialFirst:"Por favor, selecione um material primeiro na aba Informações do Filamento.",noPrintersConfigured:"Nenhuma impressora configurada. Adicione impressoras para usar perfis PA.",matchingFilter:"Correspondente",anyBrand:"Qualquer marca",anyVariant:"Qualquer variante",autoSelect:"Seleção automática",matches:"correspondências",match:"correspondência",noMatches:"Nenhuma correspondência",connected:"Conectado",offline:"Offline",printerOffline:"A impressora está offline. Conecte-se para visualizar os perfis de calibração.",noKProfilesMatch:"Nenhum K-perfil corresponde ao filamento selecionado.",leftNozzle:"Bico Esquerdo",rightNozzle:"Bico Direito",profilesSelected:"perfil(is) de calibração selecionado(s)",totalInventory:"Inventário Total",totalConsumed:"Total Consumido",byMaterial:"Por Material",inPrinter:"Na Impressora",lowStock:"Estoque Baixo",sinceTracking:"Desde o início do rastreamento",loadedInAms:"Carregado no AMS/Ext",remaining:"Restante",weightCheck:"Verificação de Peso",lastWeighed:"Última pesagem",neverWeighed:"Nunca pesado",search:"Pesquisar carretéis...",showing:"Mostrando",to:"até",of:"de",show:"Mostrar",spools:"carretéis",spool:"carretel",page:"Página",noSpoolsMatch:"Nenhum resultado encontrado",noSpoolsMatchDesc:"Tente ajustar sua pesquisa ou filtros para encontrar o que você está procurando.",active:"Ativo",archived:"Arquivado",all:"Todos",used:"Usado",new:"Novo",clearFilters:"Limpar filtros",table:"Tabela",cards:"Cartões",net:"Líquido",groupSimilar:"Agrupar",groupedSpools:"{{count}} carretéis idênticos",groupedRows:"linhas",columns:"Colunas",configureColumns:"Configurar Colunas",configureColumnsDesc:"Arraste para reordenar as colunas ou use as setas. Alterne a visibilidade com o ícone de olho.",visible:"Visível",reset:"Redefinir",cancel:"Cancelar",applyChanges:"Aplicar Alterações",moveUp:"Mover para cima",moveDown:"Mover para baixo",hideColumn:"Ocultar coluna",showColumn:"Mostrar coluna",linkToSpool:"Vincular ao Carretel",tagLinked:"Tag vinculada ao carretel",tagLinkFailed:"Falha ao vincular tag",tagAlreadyLinked:"Tag já vinculada a outro carretel",unknownTag:"Tag RFID desconhecida detectada",usageHistory:"Histórico de Uso",noUsageHistory:"Nenhum uso registrado ainda",printName:"Nome da Impressão",weightConsumed:"Peso Consumido",clearHistory:"Limpar",historyCleared:"Histórico de uso limpo",fillSourceLabel:"(Inv)",lowStockThresholdError:"O limite deve estar entre 0.1 e 99.9",assignMismatchTitle:"Incompatibilidade de material",assignMismatchMessage:'O material do carretel selecionado "{{spoolMaterial}}" não corresponde ao material da bandeja "{{trayMaterial}}" para {{location}}. Atribuir mesmo assim?',assignMismatchConfirm:"Atribuir mesmo assim",assignPartialMismatchMessage:'O material do carretel "{{spoolMaterial}}" é semelhante, mas não corresponde exatamente a "{{trayMaterial}}" em {{location}}. Deseja prosseguir?',assignProfileMismatchMessage:'O perfil do carretel "{{spoolProfile}}" não corresponde ao perfil da bandeja "{{trayProfile}}" em {{location}}. Deseja prosseguir?'},timelapse:{title:"Timelapse",create:"Criar Timelapse",download:"Baixar",delete:"Excluir",preview:"Visualizar",frameRate:"Taxa de Quadros",quality:"Qualidade",processing:"Processando...",noTimelapses:"Nenhum timelapse disponível"},ams:{title:"AMS",slot:"Slot",empty:"Vazio",emptySlot:"Slot vazio",unknown:"Desconhecido",humidity:"Umidade",temperature:"Temperatura",filamentType:"Tipo de Filamento",filamentColor:"Cor",remaining:"Restante",history:"Histórico do AMS",noHistory:"Nenhum histórico disponível",configureSlot:"Configurar Slot",externalSpool:"Carretel Externo",profile:"Perfil",kFactor:"Fator K",fill:"Preencher",configure:"Configurar",used:"usado",remainingUnit:"restante"},printModal:{title:"Iniciar Impressão",selectPrinter:"Selecionar Impressora",selectPlate:"Selecionar Placa",filamentMapping:"Mapeamento de Filamento",totalCost:"Custo total:",slotRemainingShort:" - {{grams}}g rest.",printSettings:"Configurações de Impressão",bedLeveling:"Nivelamento da Mesa",flowCalibration:"Calibração de Fluxo",vibrationCalibration:"Calibração de Vibração",layerInspection:"Inspeção da Primeira Camada",timelapse:"Timelapse",startPrint:"Iniciar Impressão",addToQueue:"Adicionar à Fila",cancel:"Cancelar",noPrintersAvailable:"Nenhuma impressora disponível",printerBusy:"Impressora ocupada",printerOffline:"Impressora offline",sameTypeDifferentColor:"Mesmo tipo, cor diferente",filamentTypeNotLoaded:"Tipo de filamento não carregado",openCalendar:"Abrir calendário",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Bico esquerdo",rightNozzleTooltip:"Bico direito",filamentOverride:"Substituição de Filamento",filamentOverrideHint:"Substitua opcionalmente os filamentos para atribuição baseada em modelo. O agendador usará os filamentos selecionados em vez dos valores originais do 3MF.",originalFilament:"Original",overrideWith:"Substituir por",resetToOriginal:"Restaurar original",insufficientFilamentTitle:"Filamento insuficiente",insufficientFilamentMessage:"Alguns dos carretéis atribuídos têm menos filamento restante do que o necessário para esta impressão:",insufficientFilamentLine:"{{printer}} - {{slot}}: necessário {{required}}g, restante {{remaining}}g",printAnyway:"Imprimir mesmo assim",forceColorMatch:"Forçar correspondência de cor",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Escalonar para {{count}} impressoras",gcodeInjection:"Injetar G-code de auto-impressão"},backup:{title:"Bakup e Restauração",createBackup:"Criar Backup",restoreBackup:"Restaurar Backup",restoreDescription:"Substituir todos os dados a partir de um arquivo de backup",downloadBackup:"Baixar Backup",uploadBackup:"Enviar Backup",lastBackup:"Último Backup",autoBackup:"Auto Backup",backupNow:"Fazer Backup Agora",restoreWarning:"Aviso: Restaurar um backup substituirá todos os dados atuais.",includeArchives:"Incluir Arquivos",includeSettings:"Incluir Configurações",includeProfiles:"Incluir Perfis",backupSuccess:"Backup criado com sucesso",restoreSuccess:"Backup restaurado com sucesso",backupFailed:"Falha ao criar backup",restoreFailed:"Falha ao restaurar backup",restoreNote:"A impressora virtual será parada durante a restauração",githubBackup:"Backup GitHub",enabled:"Ativado",cloudLoginRequired:"Login no Bambu Cloud necessário. Entre em Perfis → Perfis Cloud para ativar o backup GitHub.",cloudLoginRequiredShort:"Login Cloud necessário",githubDescription:"Sincronize automaticamente seus perfis com um repositório GitHub privado para backup e histórico de versões.",repositoryUrl:"URL do repositório",personalAccessToken:"Token de acesso pessoal",tokenSaved:"(salvo)",enterNewToken:"Digite um novo token para atualizar",tokenHint:"Token de granularidade fina com permissão de leitura/escrita de conteúdo",branch:"Branch",manualOnly:"Apenas manual",hourly:"A cada hora",daily:"Diário",weekly:"Semanal",includeInBackup:"Incluir no backup",kProfiles:"K-Perfis",kProfilesDescription:"Calibração de avanço de pressão das impressoras conectadas",noPrintersConnected:"Nenhuma impressora conectada",printersConnected:"{{connected}}/{{total}} conectadas",cloudProfiles:"Perfis Cloud",cloudProfilesDescription:"Predefinições de filamento, impressora e processo do Bambu Cloud",appSettings:"Configurações do App",appSettingsDescription:"Configuração do Bambuddy (banco de dados completo)",spoolInventory:"Inventário de bobinas",spoolInventoryDescription:"Bobinas de filamento, histórico de uso e rastreamento de custos",printArchives:"Arquivos de impressão",printArchivesDescription:"Metadados do histórico de impressão (sem arquivos gcode/3MF)",lastBackupAt:"Último backup:",noBackupsYet:"Nenhum backup ainda",next:"Próximo:",startingBackup:"Iniciando backup...",test:"Testar",enableBackup:"Ativar backup",testConnection:"Testar conexão",enterRepoUrl:"Digite a URL do repositório",enterRepoAndToken:"Digite a URL do repositório e o token de acesso",repoRequired:"A URL do repositório é obrigatória",tokenRequired:"O token de acesso é obrigatório",githubBackupEnabled:"Backup GitHub ativado",tokenUpdated:"Token atualizado",settingsSaved:"Configurações salvas",failedToSave:"Falha ao salvar: {{message}}",backupCompleteFiles:"Backup concluído - {{count}} arquivos atualizados",backupSkippedNoChanges:"Backup ignorado - sem alterações",backupFailed2:"Falha no backup: {{message}}",clearedLogs:"{{count}} logs removidos",failedToClearLogs:"Falha ao limpar logs: {{message}}",history:"Histórico",clear:"Limpar",date:"Data",status:"Status",commit:"Commit",localBackup:"Backup local",localBackupDescription:"Crie um backup completo dos seus dados do Bambuddy incluindo banco de dados, arquivos, uploads e todos os ficheiros.",downloadBackupLabel:"Baixar backup",completeBackupZip:"Backup completo: banco de dados + todos os arquivos (ZIP)",download:"Baixar",preparingBackup:"Preparando backup...",creatingArchive:"Criando arquivo de backup... Isso pode demorar para backups grandes.",downloadingFile:"Baixando arquivo de backup...",backupDownloaded:"Backup baixado com sucesso",failedToCreateBackup:"Falha ao criar backup: {{message}}",restore:"Restaurar",restoreReplacesAll:"A restauração substitui todos os dados.",restoreReplacesAllDetail:"Seu banco de dados e arquivos atuais serão completamente substituídos. É necessário reiniciar após a restauração.",restoreConfirmTitle:"Restaurar backup",restoreConfirmMessage:'Tem certeza de que deseja restaurar de "{{filename}}"? Isso substituirá completamente seu banco de dados e todos os arquivos. O aplicativo precisará ser reiniciado após a restauração.',restoreConfirmButton:"Restaurar backup",uploadingFile:"Enviando arquivo de backup...",backupRestoredRestart:"Backup restaurado. Por favor, reinicie o Bambuddy.",failedToRestore:"Falha ao restaurar backup. Verifique o formato do arquivo.",reloadNow:"Recarregar agora",creatingBackup:"Criando backup",restoringBackup:"Restaurando backup",preparing:"Preparando...",processing:"Processando...",doNotClosePage:"Por favor, não feche esta página nem navegue para outro lugar. Esta operação pode levar vários minutos para backups grandes.",restoring:"Restaurando...",restoreComplete:"Restauração concluída",restoreFailed2:"Falha na restauração",importSettings:"Importar configurações de um arquivo de backup",pleaseWaitRestoring:"Aguarde enquanto seus dados estão sendo restaurados",selectBackupFile:"Clique para selecionar um arquivo de backup (.json ou .zip)",duplicateHandling:"Como funciona o tratamento de duplicatas:",matchPrinters:"Impressoras",matchPrintersBy:"correspondência por número de série",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"correspondência por endereço IP",matchNotificationProviders:"Provedores de notificação",matchNotificationProvidersBy:"correspondência por nome",matchFilaments:"Filamentos",matchFilamentsBy:"correspondência por nome + tipo + marca",matchArchives:"Arquivos",matchArchivesBy:"correspondência por hash de conteúdo (sempre ignorado)",matchPendingUploads:"Uploads pendentes",matchPendingUploadsBy:"correspondência por nome do arquivo",matchSettingsTemplates:"Configurações e modelos",matchSettingsTemplatesBy:"sempre sobrescritos",replaceExisting:"Substituir dados existentes",keepExisting:"Manter dados existentes",overwriteDescription:"Sobrescrever itens que já existem com dados do backup",keepDescription:"Restaurar apenas itens que ainda não existem",overwriteCaution:"Cuidado:",overwriteWarning:"A sobrescrita substituirá suas configurações atuais pelos dados do backup. Códigos de acesso das impressoras nunca são sobrescritos por segurança.",cancel:"Cancelar",processingBackup:"Processando arquivo de backup...",itemsRestored:"Itens restaurados",itemsSkipped:"Itens ignorados",restored:"Restaurados",skippedAlreadyExist:"Ignorados (já existem)",filesCategory:"Arquivos (3MF, miniaturas, etc.)",andMore:"...e mais {{count}}",newApiKeysGenerated:"Novas chaves API geradas",keysShownOnce:"Estas chaves são exibidas apenas uma vez. Copie-as agora!",copy:"Copiar",noDataFound:"Nenhum dado para restaurar foi encontrado no arquivo de backup.",close:"Fechar",categories:{settings:"Configurações",notification_providers:"Provedores de notificação",notification_templates:"Modelos de notificação",smart_plugs:"Smart Plugs",printers:"Impressoras",filaments:"Filamentos",maintenance_types:"Tipos de manutenção",archives:"Arquivos",projects:"Projetos",pending_uploads:"Uploads pendentes",external_links:"Links externos",api_keys:"Chaves API"}},tags:{title:"Tags",addTag:"Adicionar Tag",editTag:"Editar Tag",deleteTag:"Excluir Tag",tagName:"Nome da Tag",tagColor:"Cor da Tag",noTags:"Nenhuma tag",deleteConfirm:"Tem certeza de que deseja excluir esta tag?",manageTags:"Gerenciar Tags"},uploadModal:{title:"Upload Arquivos 3MF",dragDrop:"Arraste e solte arquivos .3mf aqui",or:"ou",browseFiles:"Procurar Arquivos",extractionInfo:"O modelo da impressora será extraído automaticamente dos metadados do arquivo 3MF.",uploaded:"enviado",failed:"falhou",uploading:"Enviando...",upload:"Enviar",uploadFailed:"Falha no envio"},editArchive:{title:"Editar Arquivo",name:"Nome",namePlaceholder:"Nome da impressão",printer:"Impressora",noPrinter:"Nenhuma impressora",project:"Projeto",noProject:"Nenhum projeto",itemsPrinted:"Itens Impressos",itemsPrintedHelp:"Número de itens produzidos neste trabalho de impressão",notes:"Notas",notesPlaceholder:"Adicione notas sobre esta impressão...",externalLink:"Link Externo",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link para Printables, Thingiverse ou outra fonte",tags:"Tags",tagsPlaceholder:"Adicionar tags...",addMoreTags:"Adicionar mais tags...",matchingTags:'Correspondendo "{{query}}"',existingTags:"Tags existentes",clickToAdd:"(clique para adicionar)",status:"Status",failureReason:"Motivo da Falha",selectReason:"Selecione o motivo...",photos:"Fotos do Resultado da Impressão",photosHelp:"Clique em + para adicionar fotos do seu resultado impresso",printResult:"Resultado da Impressão",saving:"Salvando...",failureReasons:{adhesionFailure:"Falha de adesão",spaghettiDetached:"Spaghetti / Destacado",layerShift:"Deslocamento de camada",cloggedNozzle:"Bico entupido",filamentRunout:"Fim do filamento",warping:"Warping",stringing:"Stringing",underExtrusion:"Under-extrusion",powerFailure:"Falha de energia",userCancelled:"Cancelado pelo usuário",other:"Outro"},statuses:{completed:"Concluído",failed:"Falhou",aborted:"Cancelado",printing:"Imprimindo"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Nenhuma impressora configurada",addPrinterInSettings:"Adicione uma impressora nas Configurações para gerenciar K-profiles",noActivePrinters:"Nenhuma impressora ativa",enablePrinterConnection:"Ative a conexão da impressora para visualizar seus K-profiles",loadingProfiles:"Carregando K-Profiles...",printerOffline:"Impressora Offline",printerOfflineDesc:"A impressora selecionada não está conectada. Ligue-a para visualizar os K-profiles.",noMatchingProfiles:"Nenhum Perfil Correspondente",noMatchingProfilesDesc:"Nenhum perfil corresponde aos seus critérios de pesquisa",noKProfiles:"Nenhum K-Profile",noKProfilesDesc:"Nenhum perfil de avanço de pressão encontrado para bico de {{diameter}}mm",createFirstProfile:"Criar Primeiro Perfil",printer:"Impressora",nozzle:"Bico",refresh:"Atualizar",addProfile:"Adicionar Perfil",export:"Exportar",import:"Importar",select:"Selecionar",selectAll:"Selecionar Todos",delete:"Excluir",searchPlaceholder:"Pesquisar por nome ou filamento...",allExtruders:"Todos os Extrusores",leftOnly:"Apenas Esquerdo",rightOnly:"Apenas Direito",allFlow:"Todo Fluxo",hfOnly:"Apenas HF",sOnly:"Apenas S",sortName:"Ordenar: Nome",sortKValue:"Ordenar: Valor K",sortFilament:"Ordenar: Filamento",leftExtruder:"Extrusor Esquerdo",rightExtruder:"Extrusor Direito",modal:{addTitle:"Adicionar K-Profile",editTitle:"Editar K-Profile",profileName:"Nome do Perfil",profileNamePlaceholder:"Meu Perfil PLA",kValue:"Valor K",kValuePlaceholder:"0.020",kValueHelp:"Faixa típica: 0.01 - 0.06 para PLA, 0.02 - 0.10 para PETG",filament:"Filamento",selectFilament:"Selecionar filamento...",noFilamentsHelp:"Nenhum filamento encontrado. Crie um K-profile no Bambu Studio primeiro.",flowType:"Tipo de Fluxo",highFlow:"Alto Fluxo",standard:"Padrão",nozzleSize:"Tamanho do Bico",extruder:"Extrusor",extruders:"Extrusores",left:"Esquerdo",right:"Direito",notes:"Notas (armazenadas localmente)",notesPlaceholder:"Adicione notas sobre este perfil...",notesHelp:"As notas são salvas no Bambuddy, não na impressora",syncing:"Sincronizando com a impressora...",savingExtruder:"Salvando no extrusor {{current}}/{{total}}...",pleaseWait:"Por favor, aguarde"},deleteConfirm:{title:"Excluir Perfil",cannotUndo:"Isso não pode ser desfeito",message:'Tem certeza de que deseja excluir "{{name}}" da impressora?'},bulkDelete:{title:"Excluir Perfis",cannotUndo:"Isso não pode ser desfeito",message:"Tem certeza de que deseja excluir {{count}} perfis selecionados da impressora?"},toast:{profileSaved:"K-profile salvo",profilesSaved:"K-profile salvo em {{count}} extrusores",selectAtLeastOneExtruder:"Por favor, selecione pelo menos um extrusor",profileDeleted:"K-profile excluído",profilesDeleted:"{{count}} perfis excluídos",exportedProfiles:"{{count}} perfis exportados",importedProfiles:"{{count}} de {{total}} perfis importados",noProfilesToExport:"Nenhum perfil para exportar",invalidFileFormat:"Formato de arquivo inválido",failedToParseImport:"Falha ao analisar o arquivo de importação",failedToSaveBatch:"Falha ao salvar K-profiles",noteSaved:"Nota salva",failedToSaveNote:"Falha ao salvar nota"},permission:{noRead:"Você não tem permissão para atualizar perfis",noCreate:"Você não tem permissão para adicionar perfis",noUpdate:"Você não tem permissão para atualizar K-profiles",noDelete:"Você não tem permissão para excluir K-profiles",noExport:"Você não tem permissão para exportar perfis",noImport:"Você não tem permissão para importar perfis"}},virtualPrinter:{title:"Impressora Virtual",running:"Em execução",stopped:"Parada",description:{default:"Ative uma impressora virtual que aparece no Bambu Studio e no OrcaSlicer. Os arquivos enviados para esta impressora serão arquivados diretamente sem impressão.",proxy:"Ative um proxy que retransmite o tráfego do slicer para uma impressora real, permitindo impressão remota em qualquer rede."},enable:{title:"Ativar Impressora Virtual",visibleInSlicer:'Visível como "Bambuddy" na descoberta do slicer',proxyingTo:"Proxy para {{name}}",notActive:"Não ativo"},model:{title:"Modelo da Impressora",description:"Selecione qual modelo de impressora emular.",restartWarning:"Alterar o modelo reiniciará a impressora virtual"},accessCode:{title:"Código de acesso",isSet:"O código de acesso está definido",notSet:"Nenhum código de acesso definido — necessário para ativar.",placeholder:"Digite um código de 8 caracteres",placeholderChange:"Digite um novo código para alterar",hint:"Deve ter exatamente 8 caracteres. Usado pelos slicers para autenticação.",charCount:"({{count}}/8)"},targetPrinter:{title:"Impressora Alvo",configured:"Proxy alvo configurado",notConfigured:"Nenhuma impressora alvo selecionada - necessário para o modo proxy",placeholder:"Selecione uma impressora...",hint:"Selecione a impressora para a qual o tráfego do slicer será enviado. A impressora deve estar no modo LAN.",noPrinters:"Nenhuma impressora configurada. Adicione uma impressora primeiro para usar o modo proxy."},remoteInterface:{title:"Substituição da Interface de Rede",configured:"Substituição da interface ativa",optional:"Opcional - use se o IP detectado automaticamente estiver errado (por exemplo, várias NICs, Docker, VPN)",placeholder:"Detecção automática (padrão)...",hint:"Substitua o endereço IP anunciado via SSDP e usado no certificado TLS. Útil quando o Bambuddy possui várias interfaces de rede."},mode:{title:"Modo",archive:"Arquivar",archiveDesc:"Arquivar arquivos imediatamente",review:"Revisar",reviewDesc:"Revisar antes de arquivar",queue:"Fila",queueDesc:"Arquivar e adicionar à fila",proxy:"Proxy",proxyDesc:"Retransmitir para impressora real"},autoDispatch:{title:"Envio automático",description:"Iniciar impressões automaticamente quando adicionadas à fila. Quando desativado, as impressões aguardam envio manual."},setupRequired:{title:"Configuração Necessária",description:"O recurso de impressora virtual requer configuração adicional do sistema antes de funcionar. Isso inclui encaminhamento de portas, regras de firewall e configurações específicas da plataforma.",readGuide:"Leia o guia de configuração antes de ativar"},howItWorks:{title:"Como funciona",step1:"Complete o guia de configuração para sua plataforma",step2:"Ative a impressora virtual e defina um código de acesso",step3:'No Bambu Studio ou OrcaSlicer, vá para "Adicionar Impressora"'},status:{title:"Detalhes do Status",printerName:"Nome da Impressora",model:"Modelo",serialNumber:"Número de Série",mode:"Modo",pendingFiles:"Arquivos Pendentes",targetPrinter:"Impressora Alvo",ftpPort:"Porta FTP",mqttPort:"Porta MQTT",ftpConnections:"Conexões FTP",mqttConnections:"Conexões MQTT"},toast:{updated:"Configurações da impressora virtual atualizadas",failedToUpdate:"Falha ao atualizar as configurações",accessCodeRequired:"Defina um código de acesso primeiro",targetPrinterRequired:"Selecione uma impressora alvo primeiro",bindIpRequired:"Defina um IP de ligação primeiro",accessCodeEmpty:"O código de acesso não pode estar vazio",accessCodeLength:"O código de acesso deve ter exatamente 8 caracteres",created:"Impressora virtual criada",failedToCreate:"Falha ao criar impressora virtual",deleted:"Impressora virtual excluída",failedToDelete:"Falha ao excluir impressora virtual"},list:{title:"Impressoras Virtuais",add:"Adicionar",addFirst:"Adicionar Impressora Virtual",empty:"Nenhuma impressora virtual configurada. Adicione uma para começar."},bindIp:{title:"Interface de Rede",placeholder:"Selecionar interface...",hint:"Interface de rede para esta impressora virtual. Deve ser única por impressora."},proxy:{accessCodeHint:"No modo proxy, use o código de acesso da impressora alvo no slicer. A conexão é encaminhada de forma transparente para a impressora real."},addDialog:{title:"Adicionar Impressora Virtual",name:"Nome",hint:"Você pode configurar o código de acesso, impressora alvo e outras configurações após a criação.",create:"Criar"},deleteConfirm:{title:"Excluir Impressora Virtual",message:'Tem certeza que deseja excluir "{{name}}"? Isso irá parar todos os serviços desta impressora.'}},modelViewer:{openInSlicer:"Abrir no Slicer",tabs:{model:"Modelo 3D",gcode:"Pré-visualização G-code"},notAvailable:"Não disponível",notSliced:"Não fatiado",plates:"Placas",allPlates:"Todas as Placas",plateNumber:"Placa {{number}}",plateCount:"{{count}} placa",plateCount_other:"{{count}} placas",objectCount:"{{count}} objeto",objectCount_other:"{{count}} objetos",filamentCount:"{{count}} filamento",filamentCount_other:"{{count}} filamentos",eta:"ETA {{minutes}} min",noPreview:"Pré-visualização não disponível para este arquivo",pagination:{pageOf:"Página {{current}} de {{total}}",prev:"Anterior",next:"Próximo"},errors:{failedToLoad:"Falha ao carregar o arquivo",noMeshes:"Nenhuma malha encontrada no arquivo 3MF",unsupportedFormat:"Formato de arquivo não suportado"}},maintenanceDescriptions:{lubricateCarbonRods:"Aplique lubrificante nos eixos de carbono para um movimento suave",lubricateRails:"Aplique lubrificante nos trilhos lineares para um movimento suave",cleanNozzle:"Limpe o hotend e o bico para evitar entupimentos",checkBelts:"Verifique a tensão das correias para impressões precisas",cleanBuildPlate:"Limpe a placa de construção para melhor adesão",checkExtruder:"Verifique as engrenagens do extrusor quanto ao desgaste",checkCooling:"Verifique se os ventiladores de resfriamento estão funcionando corretamente",generalInspection:"Inspeção geral da impressora",cleanCarbonRods:"Limpe os eixos de carbono para reduzir o atrito",lubricateSteelRods:"Aplique lubrificante nas barras de aço para um movimento suave",cleanSteelRods:"Limpe as barras de aço para reduzir o atrito",cleanLinearRails:"Limpe os trilhos lineares para remover poeira e detritos",checkPtfeTube:"Verifique o tubo PTFE quanto ao desgaste ou danos",replaceHepaFilter:"Substitua o filtro HEPA para qualidade do ar",replaceCarbonFilter:"Substitua o filtro de carbono ativado",lubricateLeftNozzleRail:"Lubrifique o trilho do bico esquerdo (série H2)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Abrir o painel de administração da tomada inteligente",deleteSmartPlug:"Excluir Tomada Inteligente",turnOnSmartPlug:"Ligar Tomada Inteligente",turnOffSmartPlug:"Desligar Tomada Inteligente",turnOn:"Ligar",turnOff:"Desligar",addSmartPlug:{scanningNetwork:"Procurando na rede...",chooseEntity:"Escolha uma entidade...",connectionFailed:"Falha na conexão",searchEntities:"Pesquisar entidades...",searchPowerSensors:"Pesquisar sensores de energia...",searchEnergySensors:"Pesquisar sensores de energia...",placeholders:{plugName:"Tomada da Sala",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Mesmo que o tópico de energia, ou diferente"}},linkedTo:"Vinculado a:",monitorOnly:"Apenas monitoramento",alerts:"Alertas",scheduleOn:"Ligar {{time}}",scheduleOff:"Desligar {{time}}",on:"Ligado",off:"Desligado",power:"Potência",kwhToday:"kWh Hoje",settings:"Configurações",automationSettings:"Configurações de automação",showInSwitchbar:"Mostrar na barra de interruptores",quickAccessSidebar:"Acesso rápido pela barra lateral",enabled:"Ativado",enableAutomation:"Ativar automação para este plugue",autoOn:"Auto Ligar",autoOnDescription:"Ligar quando a impressão iniciar",autoOff:"Auto Desligar",autoOffDescription:"Desligar quando a impressão terminar (única vez)",autoOffPersistent:"Manter ativado",autoOffPersistentDescription:"Permanecer ativado entre impressões em vez de única vez",turnOffDelayMode:"Modo de atraso para desligar",time:"Tempo",temp:"Temp",delayMinutes:"Atraso (minutos)",tempThreshold:"Limite de temperatura (°C)",tempThresholdDescription:"Desliga quando o bico esfria abaixo desta temperatura",edit:"Editar",deleteConfirm:'Tem certeza que deseja excluir "{{name}}"? Esta ação não pode ser desfeita.',turnOnConfirm:'Tem certeza que deseja ligar "{{name}}"?',turnOffConfirm:'Tem certeza que deseja desligar "{{name}}"? Isso cortará a energia do dispositivo conectado.',failedToTurn:'Falha ao {{action}} "{{name}}"',unknown:"Desconhecido",addTitle:"Adicionar plugue inteligente",editTitle:"Editar plugue inteligente",stopScanning:"Parar varredura",discoverTasmota:"Descobrir dispositivos Tasmota",foundDevices:"{{count}} dispositivo(s) encontrado(s) - clique para selecionar:",noDevicesFound:"Nenhum dispositivo Tasmota encontrado na sua rede",haNotConfigured:"Home Assistant não está configurado. Configure em",haSettingsPath:"Configurações → Rede → Home Assistant",selectEntity:"Selecionar entidade *",ipAddress:"Endereço IP *",nameLabel:"Nome *",username:"Usuário",password:"Senha",authHint:"Deixe vazio se seu dispositivo Tasmota não requer autenticação",linkToPrinter:"Vincular à impressora",noPrinter:"Sem impressora (apenas controle manual)",linkingDescription:"A vinculação permite ligar/desligar automaticamente ao iniciar/terminar impressão",powerAlerts:"Alertas de potência",alertAbove:"Alertar se acima (W)",alertBelow:"Alertar se abaixo (W)",alertDescription:"Receba notificações quando o consumo de energia ultrapassar estes limites. Deixe vazio para desativar essa direção.",dailySchedule:"Programação diária",turnOnAt:"Ligar às",turnOffAt:"Desligar às",scheduleDescription:"Ligar/desligar automaticamente o plugue nestes horários diariamente. Deixe vazio para pular essa ação.",showOnPrinterCard:"Mostrar no cartão da impressora",displayOnPrinterCard:"Exibir botão no cartão da impressora",connectedResult:"Conectado!",deviceLabel:"Dispositivo: {{name}} - ",stateLabel:"Estado: {{state}}",test:"Testar",delete:"Excluir",save:"Salvar",add:"Adicionar",cancel:"Cancelar",failedToStartScan:"Falha ao iniciar varredura",nameRequired:"Nome é obrigatório",entityRequired:"Entidade é obrigatória para plugues Home Assistant",mqttTopicRequired:"Pelo menos um tópico MQTT deve ser configurado para potência, energia ou monitoramento de estado",loadingEntities:"Carregando entidades...",loading:"Carregando...",failedToLoadEntities:"Falha ao carregar entidades: {{error}}",noEntitiesMatching:'Nenhuma entidade encontrada correspondente a "{{search}}"',noEntitiesAvailable:"Nenhuma entidade disponível",searchingEntities:"Buscando todas as entidades ({{count}} encontradas)",showingEntities:"Mostrando switch, light, input_boolean ({{count}} disponíveis)",energyMonitoringOptional:"Monitoramento de energia (Opcional)",energyMonitoringHint:"Pesquise e selecione sensores que fornecem dados de potência/energia.",powerSensorW:"Sensor de potência (W)",energyTodayKwh:"Energia hoje (kWh)",totalEnergyKwh:"Energia total (kWh)",noMatchingSensors:"Nenhum sensor correspondente",none:"Nenhum",mqttNotConfigured:"Broker MQTT não configurado. Defina o endereço do broker em",mqttSettingsPath:"Configurações → Rede → Publicação MQTT",mqttNotConfiguredSuffix:"(você não precisa ativar a publicação, apenas preencha os detalhes do broker).",mqttMonitorOnlyDescription:"Plugues MQTT recebem dados de potência/energia via assinatura MQTT. O controle liga/desliga não está disponível - use seu broker MQTT ou sistema de automação residencial.",powerMonitoring:"Monitoramento de potência",energyMonitoring:"Monitoramento de energia",stateMonitoring:"Monitoramento de estado",optional:"opcional",topic:"Tópico",jsonPath:"Caminho JSON",multiplier:"Multiplicador",onValue:"Valor ON",mqttPowerHint:`O caminho JSON extrai o valor do payload JSON (ex: "power_l1"). Deixe vazio se o tópico publica valores numéricos brutos.
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL de potência",restPowerPath:"Power JSON Path",restPowerMultiplier:"Multiplicador de potência",restEnergyUrl:"URL de energia",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Multiplicador de energia",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL separada para dados de potência (usa a URL de status se vazio)",restEnergyUrlHint:"URL separada para dados de energia (usa a URL de status se vazio)",restEnergyHint:"Cada valor pode usar sua própria URL ou recorrer à URL de status. Use multiplicadores para conversão de unidades (ex: 0.001 para converter Wh em kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Nenhum interruptor na barra",enableSwitchbarHint:'Ative "Mostrar na barra de interruptores" em Configurações > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notificações por e-mail SMTP",telegram:"Notificações via bot do Telegram",discord:"Enviar para canal do Discord via webhook",ntfy:"Notificações push gratuitas e auto-hospedáveis",pushover:"Notificações push simples e confiáveis",callmebot:"Notificações gratuitas via WhatsApp pelo CallMeBot",webhook:"POST HTTP genérico para qualquer URL",homeassistant:"Notificações persistentes no painel do Home Assistant"},lastSuccess:"Último: {{date}}",error:"Erro",printer:"Impressora:",allPrinters:"Todas as impressoras",sendTestNotification:"Enviar Notificação de Teste",eventSettings:"Configurações de Eventos",enabled:"Ativado",sendFromProvider:"Enviar notificações deste provedor",printEvents:"Eventos de Impressão",printerStatus:"Status da Impressora",amsAlarms:"Alarmes do AMS",amsHtAlarms:"Alarmes do AMS-HT",printQueue:"Fila de Impressão",start:"Início",plateCheck:"Verificação da Mesa",complete:"Concluído",failed:"Falhou",stopped:"Parado",progress:"Progresso",offline:"Offline",lowFilament:"Filamento Baixo",maintenance:"Manutenção",amsHumidity:"Umidade do AMS",amsTemp:"Temp. do AMS",amsHtHumidity:"Umidade do AMS-HT",amsHtTemp:"Temp. do AMS-HT",bedCooled:"Mesa Resfriada",firstLayer:"Primeira camada",quiet:"Silencioso",digest:"Resumo {{time}}",printStarted:"Impressão Iniciada",plateNotEmpty:"Mesa Não Vazia",plateNotEmptyDescription:"Objetos detectados antes da impressão",printCompleted:"Impressão Concluída",bedCooledLabel:"Mesa Resfriada",bedCooledDescription:"Mesa resfriou abaixo do limite após a impressão",firstLayerCompleteLabel:"Primeira camada concluída",firstLayerCompleteDescription:"Notificar com foto quando a primeira camada terminar",missingSpoolAssignmentLabel:"Atribuição de bobina ausente",missingSpoolAssignmentDescription:"Notificar quando a impressão iniciar e bandejas necessárias não tiverem bobina atribuída",printFailed:"Impressão Falhou",printStopped:"Impressão Parada",progressMilestones:"Marcos de Progresso",progressMilestonesDescription:"Notificar em 25%, 50%, 75%",printerOffline:"Impressora Offline",printerError:"Erro da Impressora",lowFilamentLabel:"Filamento Baixo",maintenanceDue:"Manutenção Necessária",maintenanceDueDescription:"Notificar quando manutenção for necessária",amsHumidityHigh:"Umidade Alta do AMS",amsHumidityHighDescription:"Umidade do AMS regular excede o limite",amsTemperatureHigh:"Temperatura Alta do AMS",amsTemperatureHighDescription:"Temperatura do AMS regular excede o limite",amsHtHumidityHigh:"Umidade Alta do AMS-HT",amsHtHumidityHighDescription:"Umidade do AMS-HT excede o limite",amsHtTemperatureHigh:"Temperatura Alta do AMS-HT",amsHtTemperatureHighDescription:"Temperatura do AMS-HT excede o limite",jobAdded:"Trabalho Adicionado",jobAddedDescription:"Trabalho adicionado à fila",jobAssigned:"Trabalho Atribuído",jobAssignedDescription:"Trabalho baseado em modelo atribuído à impressora",jobStarted:"Trabalho Iniciado",jobStartedDescription:"Trabalho da fila começou a imprimir",jobWaiting:"Trabalho Aguardando",jobWaitingDescription:"Trabalho aguardando filamento ou impressora",jobSkipped:"Trabalho Pulado",jobSkippedDescription:"Trabalho pulado (anterior falhou)",jobFailed:"Trabalho Falhou",jobFailedDescription:"Trabalho falhou ao iniciar",queueComplete:"Fila Concluída",queueCompleteDescription:"Todos os trabalhos da fila finalizados",quietHours:"Horário de Silêncio",noNotificationsDuring:"Sem notificações durante essas horas",editProviderToChangeQuietHours:"Edite o provedor para alterar o horário de silêncio",dailyDigest:"Resumo Diário",batchNotifications:"Agrupar notificações em um único resumo diário",sendAt:"Enviar às {{time}}",editProviderToChangeDigestTime:"Edite o provedor para alterar o horário do resumo",edit:"Editar",deleteProvider:"Excluir Provedor de Notificação",deleteConfirm:'Tem certeza que deseja excluir "{{name}}"? Isso não pode ser desfeito.',delete:"Excluir",addTitle:"Adicionar Provedor de Notificação",editTitle:"Editar Provedor de Notificação",nameLabel:"Nome *",namePlaceholder:"Minhas Notificações",providerTypeLabel:"Tipo de Provedor *",configuration:"Configuração",testConfiguration:"Testar Configuração",printerFilter:"Filtro de Impressora",onlyFromPrinter:"Enviar notificações apenas para eventos desta impressora",quietHoursDnd:"Horário de Silêncio (Não Perturbe)",quietStart:"Início",quietEnd:"Fim",dailyDigestLabel:"Resumo Diário",sendDigestAt:"Enviar resumo às",digestCollected:"Os eventos serão coletados e enviados como um único resumo neste horário",notificationEvents:"Eventos de Notificação",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(após conclusão da impressão)",cancel:"Cancelar",save:"Salvar",add:"Adicionar",nameRequired:"Nome é obrigatório",fieldRequired:"{{field}} é obrigatório",phoneNumber:"Número de Telefone",apiKey:"Chave da API",serverUrl:"URL do Servidor",topic:"Tópico",authToken:"Token de Autenticação",userKey:"Chave do Usuário",appToken:"Token do Aplicativo",priority:"Prioridade",botToken:"Token do Bot",chatId:"ID do Chat",smtpServer:"Servidor SMTP",smtpPort:"Porta SMTP",security:"Segurança",authentication:"Autenticação",username:"Usuário",password:"Senha",fromEmail:"E-mail de Origem",toEmail:"E-mail de Destino",webhookUrl:"URL do Webhook",payloadFormat:"Formato do Payload",authorization:"Autorização",titleFieldName:"Nome do Campo de Título",messageFieldName:"Nome do Campo de Mensagem",editTemplate:"Editar Modelo: {{name}}",titleLabel:"Título",bodyLabel:"Corpo",titlePlaceholder:"Título da notificação...",bodyPlaceholder:"Corpo da notificação...",availableVariables:"Variáveis Disponíveis",clickToInsert:"Clique para inserir na posição do cursor no corpo",livePreview:"Pré-visualização ao Vivo",hide:"Ocultar",show:"Mostrar",loadingPreview:"Carregando pré-visualização...",enterTemplateContent:"Insira o conteúdo do modelo para ver a pré-visualização",titlePreview:"Título:",bodyPreview:"Corpo:",resetToDefault:"Restaurar Padrão",titleRequired:"Título é obrigatório",bodyRequired:"Corpo é obrigatório",notificationLog:"Registro de Notificações",showFailedOnly:"Apenas falhas",last24Hours:"Últimas 24 horas",last7Days:"Últimos 7 dias",last30Days:"Últimos 30 dias",last90Days:"Últimos 90 dias",justNow:"Agora mesmo",noFailedNotifications:"Nenhuma notificação com falha",noNotificationsLogged:"Nenhuma notificação registrada",unknownProvider:"Provedor Desconhecido",logTitle:"Título",logMessage:"Mensagem",logError:"Erro",logProvider:"Provedor: {{type}}",logTime:"Hora: {{time}}",refresh:"Atualizar",clearOld:"Limpar Antigos",statsSummary:"Últimos {{days}} dias:",statsNotifications:"notificações",statsSent:"{{count}} enviadas",statsFailed:"{{count}} com falha",eventTypes:{print_start:"Impressão Iniciada",print_complete:"Impressão Concluída",print_failed:"Impressão Falhou",print_stopped:"Impressão Parada",print_progress:"Progresso",printer_offline:"Impressora Offline",printer_error:"Erro da Impressora",filament_low:"Filamento Baixo",maintenance_due:"Manutenção Necessária",test:"Teste"},userEmail:{title:"Notificações",emailNotifications:"Notificações por E-mail",emailNotificationsDesc:"Receba notificações por e-mail para seus próprios trabalhos de impressão. Os e-mails são enviados usando as configurações SMTP definidas na Autenticação Avançada.",sendingTo:"As notificações serão enviadas para",noEmailWarning:"Sua conta não tem um endereço de e-mail. Entre em contato com um administrador para adicionar um.",printJobNotifications:"Notificações de Trabalhos de Impressão",printJobNotificationsDesc:"Escolha quais eventos acionam notificações por e-mail para os trabalhos de impressão que você envia.",printJobStarts:"Início do Trabalho de Impressão",printJobStartsDesc:"Ser notificado quando seu trabalho de impressão começar.",printJobFinishes:"Conclusão do Trabalho de Impressão",printJobFinishesDesc:"Ser notificado quando seu trabalho de impressão concluir com sucesso.",printErrors:"Erros de Impressão",printErrorsDesc:"Ser notificado quando seu trabalho de impressão falhar ou encontrar um erro.",printJobStops:"Trabalho de Impressão Parado",printJobStopsDesc:"Ser notificado quando seu trabalho de impressão for cancelado ou parado.",saveSuccess:"Preferências de notificação salvas.",saveError:"Falha ao salvar preferências de notificação."}},richTextEditor:{bold:"Negrito",italic:"Itálico",underline:"Sublinhado",bulletList:"Lista com marcadores",numberedList:"Lista numerada",alignLeft:"Alinhar à esquerda",alignCenter:"Centralizar",alignRight:"Alinhar à direita",addLink:"Adicionar link",removeLink:"Remover link"},externalLinks:{noLinksConfigured:"Nenhum link externo configurado",deleteLink:"Excluir link",removeCustomIcon:"Remover ícone personalizado",openInNewTab:"Abrir em nova aba",placeholders:{linkName:"Meu Link"}},keyboardShortcuts:{title:"Atalhos de Teclado",navigation:"Navegação",archivesSection:"Arquivos",kProfilesSection:"K-Profiles",generalSection:"Geral",shortcuts:{goToPrinters:"Ir para Impressoras",goToArchives:"Ir para Arquivos",goToQueue:"Ir para Fila",goToStats:"Ir para Estatísticas",goToProfiles:"Ir para Perfis na Nuvem",goToSettings:"Ir para Configurações",focusSearch:"Focar na pesquisa",openUploadModal:"Abrir modal de upload",clearSelection:"Limpar seleção / desfocar input",contextMenu:"Menu de contexto nos cartões",refreshProfiles:"Atualizar perfis",newProfile:"Novo perfil",exitSelectionMode:"Sair do modo de seleção",showHelp:"Mostrar esta ajuda"},footer:"Pressione Esc ou clique fora para fechar"},notificationLog:{title:"Registro de Notificações",events:{printStarted:"Impressão Iniciada",printComplete:"Impressão Concluída",printFailed:"Impressão Falhou",printStopped:"Impressão Interrompida",progress:"Progresso",printerOffline:"Impressora Offline",printerError:"Erro na Impressora",lowFilament:"Filamento Baixo",maintenanceDue:"Manutenção Pendente",test:"Teste"},timeAgo:{justNow:"Agora mesmo",minutesAgo:"há {{minutes}} minutos",hoursAgo:"há {{hours}} horas"}},restoreBackup:{title:"Restaurar Backup",restoring:"Restaurando...",restoreComplete:"Restauração Concluída",restoreFailed:"Falha na Restauração",importSettings:"Importar configurações de um arquivo de backup",pleaseWait:"Aguarde enquanto seus dados estão sendo restaurados",clickToSelect:"Clique para selecionar o arquivo de backup (.json ou .zip)",howDuplicateHandling:"Como funciona o tratamento de duplicatas:",categories:{printers:"Impressoras",smartPlugs:"Tomadas Inteligentes",notificationProviders:"Provedores de Notificação",filaments:"Filamentos",archives:"Arquivos",pendingUploads:"Uploads Pendentes",settingsTemplates:"Configurações e Modelos"},matchingInfo:{printers:"correspondem pelo número de série",smartPlugs:"correspondem pelo endereço IP",notificationProviders:"correspondem pelo nome",filaments:"correspondem pelo nome + tipo + marca",archives:"correspondem pelo hash do conteúdo",pendingUploads:"correspondem pelo nome do arquivo",settingsTemplates:"sempre sobrescrito"},replaceExisting:"Substituir dados existentes",keepExisting:"Manter dados existentes",replaceDescription:"Substituir itens que já existem com os dados do backup",keepDescription:"Restaurar apenas itens que não existem",caution:"Atenção:",cautionText:"Sobrescrever substituirá suas configurações atuais pelos dados do backup. Os códigos de acesso da impressora nunca são sobrescritos por segurança.",itemsRestored:"Itens Restaurados",itemsSkipped:"Itens Ignorados",restored:"Restaurado",skipped:"Ignorado (já existe)",filesLabel:"Arquivos (3MF, miniaturas, etc.)",newApiKeysGenerated:"Novas Chaves API Geradas",newApiKeysWarning:"Essas chaves são exibidas apenas uma vez. Copie-as agora!",processingBackup:"Processando arquivo de backup...",noDataFound:"Nenhum dado foi encontrado para restaurar no arquivo de backup.",failedToRestore:"Falha ao restaurar o backup. Verifique o formato do arquivo."},backupExport:{title:"Exportar Backup",selectData:"Selecione os dados a incluir",selectAll:"Selecionar Todos",selectNone:"Selecionar Nenhum",categoryDescriptions:{settings:"Idioma, tema, preferências de atualização",notifications:"ntfy, Pushover, Discord, etc.",templates:"Modelos de mensagens personalizadas",smartPlugs:"Configurações de tomadas Tasmota",externalLinks:"Links da barra lateral para serviços externos",printers:"Informações da impressora (códigos de acesso excluídos)",plateDetection:"Imagens de referência de placa vazia",filaments:"Tipos e custos de filamento",maintenance:"Cronogramas de manutenção personalizados",archives:"Todos os dados de impressão + arquivos (3MF, miniaturas, fotos)",projects:"Projetos, itens de BOM e anexos",pendingUploads:"Uploads de impressora virtual aguardando revisão",apiKeys:"Chaves API de webhook (novas chaves geradas na importação)"},requiresPrinters:"Requer que as impressoras sejam selecionadas",zipFileWarning:"Um arquivo ZIP será criado.",zipFileDescription:"Inclui todos os arquivos 3MF, miniaturas, timelapses e fotos. Isso pode levar algum tempo e resultar em um arquivo grande.",includeAccessCodes:"Incluir Códigos de Acesso",includeAccessCodesDescription:"Para transferir para outra máquina",includeAccessCodesWarning:"Os códigos de acesso serão incluídos em texto simples. Mantenha este arquivo de backup seguro!",categoriesSelected:"{{selectedCount}} categorias selecionadas"},pendingUploads:{placeholders:{notes:"Adicione notas sobre esta impressão..."},discardUpload:"Descartar Upload",archiveAllUploads:"Arquivar Todos os Uploads",discardAllUploads:"Descartar Todos os Uploads",archive:"Arquivar",timeAgo:{justNow:"Agora mesmo",minutesAgo:"há {{minutes}} minutos",hoursAgo:"há {{hours}} horas",daysAgo:"há {{days}} dias"}},apiBrowser:{placeholders:{requestBody:"Corpo da requisição JSON...",searchEndpoints:"Pesquisar endpoints..."}},configureAmsSlot:{title:"Configurar Slot AMS",slotConfigured:"Slot Configurado!",configuringSlot:"Configurando slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Pesquisar predefinições...",colorPlaceholder:"Nome da cor ou hex (ex.: marrom, FF8800)",clearCustomColor:"Limpar cor personalizada",noCloudPresets:"Nenhuma predefinição na nuvem. Faça login no Bambu Cloud para sincronizar.",noPresetsAvailable:"Nenhuma predefinição disponível. Faça login no Bambu Cloud ou importe perfis locais.",noMatchingPresets:"Nenhuma predefinição correspondente encontrada.",custom:"Personalizado",builtin:"Integrado",settingsSentToPrinter:"Configurações enviadas para a impressora",filamentProfile:"Perfil de Filamento",kProfileLabel:"Perfil K (Avanço de Pressão)",filteringFor:"Filtrando por: {{material}}",noKProfile:"Nenhum perfil K (usar padrão 0.020)",noMatchingKProfiles:"Nenhum perfil K correspondente encontrado. O K padrão=0.020 será usado.",selectFilamentFirst:"Selecione um perfil de filamento primeiro",kFromCalibration:"K={{value}} da calibração da impressora",customColorLabel:"Cor Personalizada (opcional)",presetColors:"Cores de {{name}}:",showLessColors:"Mostrar menos cores",showMoreColors:"Mostrar mais cores",clear:"Limpar",hexLabel:"Hex: #{{hex}}",resetting:"Redefinindo...",resetSlot:"Redefinir Slot",cancel:"Cancelar",configuring:"Configurando...",configureSlot:"Configurar Slot"},githubBackup:{title:"Backup do GitHub",history:"Histórico",downloadBackup:"Baixar Backup",restoreBackup:"Restaurar Backup",noBackupsYet:"Nenhum backup ainda"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Pesquisar tags...",renameTag:"Renomear tag",deleteTag:"Excluir tag"},notificationTemplates:{placeholders:{title:"Título da notificação...",body:"Corpo da notificação..."}},batchTag:{placeholders:{newTag:"Digite uma nova tag..."}},photoGallery:{deletePhoto:"Excluir foto"},filamentHoverCard:{copySpoolUuid:"Copiar UUID do carretel"},kProfilesView:{hasNote:"Possui nota",copyProfile:"Copiar perfil"},layout:{openMenu:"Abrir menu",noPermissionSystemInfo:"Você não tem permissão para visualizar informações do sistema"},dashboard:{dragToReorder:"Arrastar para reordenar",hideWidget:"Ocultar widget"},notificationProviderCard:{deleteNotificationProvider:"Excluir provedor de notificação"},fileManagerModal:{closeFileManager:"Fechar gerenciador de arquivos",sortFiles:"Ordenar arquivos",goToParentFolder:"Ir para a pasta pai",threeView:"Visualização 3D"},embeddedCameraViewer:{refreshStream:"Atualizar stream",close:"Fechar",zoomOut:"Reduzir zoom",resetZoom:"Redefinir zoom",zoomIn:"Aumentar zoom",dragToResize:"Arrastar para redimensionar"},timelapseViewer:{skipBack5s:"Voltar 5s",skipForward5s:"Avançar 5s"},notificationProviders:{descriptions:{email:"Notificações por email SMTP",telegram:"Notificações via bot do Telegram",discord:"Enviar para canal do Discord via webhook",ntfy:"Notificações push gratuitas e auto-hospedáveis",pushover:"Notificações push simples e confiáveis",callmebot:"Notificações gratuitas via WhatsApp pelo CallMeBot",webhook:"POST HTTP genérico para qualquer URL"}},logViewer:{searchPlaceholder:"Pesquisar mensagem ou nome do logger...",noLogEntries:"Nenhuma entrada de log encontrada"},switchbarPopover:{noSwitchesInSwitchbar:"Nenhum switch na barra de switches"},projectPageModal:{placeholders:{title:"Título",designer:"Designer",license:"Licença",description:"Digite a descrição...",profileTitle:"Título do perfil",profileDescription:"Descrição do perfil..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"Aguardando",justNow:"Agora mesmo",now:"Agora",minsAgo:"{{count}}min atrás",inMins:"em {{count}}min",hoursAgo:"{{count}}h atrás",inHours:"em {{count}}h",daysAgo:"{{count}}d atrás",inDays:"em {{count}}d"},spoolbuddy:{nav:{dashboard:"Painel",ams:"AMS",inventory:"Inventário",writeTag:"Escrever",settings:"Configurações"},status:{nfcReady:"NFC pronto",nfcOff:"NFC desligado",offline:"Offline",online:"Online",noPrinters:"Sem impressoras",deviceOffline:"Dispositivo offline",waitingConnection:"Aguardando conexão do dispositivo...",systemReady:"Sistema pronto",status:"Status"},dashboard:{readyToScan:"Pronto para escanear",idleMessage:"Coloque um carretel na balança para identificá-lo",nfcHint:"A tag NFC será lida automaticamente",device:"Dispositivo",syncWeight:"Sincronizar peso",weightSynced:"Sincronizado!",unknownTag:"Tag desconhecida",newTag:"Nova tag detectada",onScale:"na balança",linkSpool:"Vincular ao carretel",linkTagTitle:"Vincular tag ao carretel",linkTag:"Vincular tag",selectSpool:"Selecione um carretel para vincular a esta tag:",noUntagged:"Nenhum carretel sem tag encontrado",tagDetected:"Tag detectada",noTag:"Sem tag",tagId:"Tag",grossWeight:"Peso bruto",spoolSize:"Tamanho do carretel",close:"Fechar",currentSpool:"Carretel Atual"},modal:{spoolDetected:"Carretel Detectado",assignToAms:"Atribuir ao AMS",syncWeight:"Sincronizar Peso",weightSynced:"Sincronizado!",syncing:"Sincronizando...",newTagDetected:"Nova Tag Detectada",addToInventory:"Adicionar ao Inventário",assignToAmsTitle:"Atribuir ao AMS",selectSlot:"Selecionar um slot",assign:"Atribuir",assigning:"Atribuindo...",assignSuccess:"Atribuído!",assignError:"Falha ao atribuir carretel. Tente novamente.",noPrinterSelected:"Selecionar uma impressora...",noAmsDetected:"Nenhum AMS detectado nesta impressora",slot:"Slot"},weight:{noReading:"Sem leitura",stable:"Estável",measuring:"Medindo...",tare:"Tarar",calibrate:"Calibrar"},spool:{remaining:"Restante",material:"Material",brand:"Marca",color:"Cor",coreWeight:"Núcleo",labelWeight:"Rótulo",scaleWeight:"Balança",netWeight:"Líquido",lastUsed:"Último uso"},ams:{noData:"Nenhum AMS detectado",connectAms:"Conecte um AMS para ver os slots",noPrinter:"Nenhuma impressora selecionada",selectPrinter:"Selecione uma impressora na barra superior",printerDisconnected:"Impressora desconectada",humidity:"Umidade",level:"Nível",active:"Ativo",slot:"Slot",empty:"Vazio"},inventory:{search:"Buscar carretéis...",empty:"Nenhum carretel no inventário",noResults:"Nenhum carretel correspondente",spools:"carretéis",addSpool:"Adicionar carretel"},settings:{tabDevice:"Dispositivo",tabDisplay:"Tela",tabScale:"Balança",tabUpdates:"Atualizações",nfcReader:"Leitor NFC",type:"Tipo",connection:"Conexão",notConnected:"N/A",deviceInfo:"Info do dispositivo",hostname:"Host",uptime:"Tempo de atividade",brightness:"Brilho",saved:"Salvo",noBacklight:"Nenhuma retroiluminação DSI detectada. O controle de brilho requer uma tela DSI.",screenBlank:"Tempo para desligar tela",screenBlankDesc:"A tela desliga após inatividade. Toque para despertar.",displayNote:"O brilho é aplicado como filtro de software.",scaleCalibration:"Calibração da balança",currentWeight:"Peso atual",tareOffset:"Tara",calFactor:"Fator",knownWeight:"Peso conhecido",calStep1:"Remova todos os itens da balança e pressione Definir zero.",calStep2:"Coloque o peso conhecido na balança.",setZero:"Definir zero",calibrateNow:"Calibrar",calibrated:"Calibrado",tareSet:"Comando de tara enviado. Aguardando dispositivo...",tareFailed:"Falha ao enviar comando de tara",zeroSet:"Ponto zero definido. Coloque o peso conhecido na balança.",calibrationDone:"Calibração concluída!",calibrationFailed:"Falha na calibração",lastCalibrated:"Última calibração",stable:"Estável",settling:"Estabilizando...",firmware:"Firmware",scale:"Balança",noDevice:"Nenhum dispositivo SpoolBuddy encontrado",daemonVersion:"Versão do daemon",currentVersion:"Atual",versionPending:"Aguardando daemon...",checking:"Verificando...",checkUpdates:"Verificar atualizações",updateAvailable:"Atualização disponível",updateInstructions:"Atualize via SSH: execute o script de instalação do SpoolBuddy.",upToDate:"Atualizado",includeBeta:"Incluir versões beta"},writeTag:{tabExisting:"Bobina existente",tabNew:"Nova bobina",tabReplace:"Substituir tag",searchPlaceholder:"Buscar por material, cor, marca...",noUntaggedSpools:"Nenhuma bobina sem tag",noTaggedSpools:"Nenhuma bobina com tag",selectSpool:"Selecione uma bobina e coloque um NTAG no leitor",placeTag:"Coloque um NTAG no leitor",tagReady:"Tag detectado — pronto para gravar",writeTag:"Gravar Tag",replaceTag:"Substituir Tag",writing:"Gravando tag...",waiting:"Aguardando SpoolBuddy...",writeSuccess:"Tag gravado com sucesso!",writeFailed:"Falha na gravação",queueFailed:"Falha ao enfileirar comando de gravação",tryAgain:"Tentar novamente",cancel:"Cancelar",replaceWarning:"O tag antigo será desvinculado. O novo tag o substituirá.",deviceOffline:"SpoolBuddy está offline",material:"Material",colorName:"Nome da cor",color:"Cor",brand:"Marca",weight:"Peso (g)",createSpool:"Criar bobina",creating:"Criando...",spoolCreated:"Bobina criada! Pronto para gravar.",createFailed:"Falha ao criar bobina"},quickMenu:{printerPower:"Energia da impressora",systemControls:"Sistema",restartDaemon:"Reiniciar daemon",restartBrowser:"Reiniciar navegador",reboot:"Reiniciar",shutdown:"Desligar",swipeToClose:"Deslize para baixo para fechar",confirmTitle:"Confirmar",confirmShutdown:"Tem certeza de que deseja desligar o SpoolBuddy? Você precisará de acesso físico para ligá-lo novamente.",confirmReboot:"Tem certeza de que deseja reiniciar o SpoolBuddy?",confirmRestartDaemon:"Reiniciar o daemon do SpoolBuddy? NFC e balança ficarão temporariamente indisponíveis.",confirmRestartBrowser:"Reiniciar o navegador kiosk? A tela ficará brevemente preta.",confirm:"Confirmar",confirmPlugOn:"Ligar {{name}}?",confirmPlugOff:"Desligar {{name}}?",turnOn:"Ligar",turnOff:"Desligar"}},bugReport:{title:"Reportar um bug",description:"Descrição",descriptionPlaceholder:"O que deu errado? Por favor, descreva o problema...",email:"Email (opcional)",emailPlaceholder:"seu@email.com.br",emailPrivacy:"Se fornecido, seu email será incluído em uma seção recolhida da issue no GitHub para que o mantenedor possa entrar em contato.",screenshot:"Captura de tela",uploadOrPaste:"Enviar, colar ou arrastar uma imagem",dataCollectedSummary:"Quais dados são incluídos no relatório?",dataIncluded:"Incluídos:",dataIncludedList:"Versão do app, SO, arquitetura, versão Python, estatísticas do banco de dados (apenas contagens), modelos de impressora, quantidade de bicos, versões de firmware, status de conexão, status de integrações (Spoolman, MQTT, HA), configurações não sensíveis, contagem de interfaces de rede, detalhes Docker, versões de dependências.",dataNeverIncluded:"Nunca incluídos:",dataNeverIncludedList:"Nomes de impressoras, números de série, códigos de acesso, senhas, endereços IP, endereços de email, chaves de API, tokens, URLs de webhook, nomes de host ou nomes de usuário.",submit:"Enviar",startLogging:"Iniciar log de depuração",stepEnableLogging:"Log de depuração ativado",stepReproduce:"Reproduza o problema agora",stepStopLogging:"Parar & enviar relatório",stopAndSubmit:"Parar & Enviar",maxDuration:"Para automaticamente após {{minutes}} min",stoppingLogs:"Coletando logs & enviando...",submitting:"Enviando relatório de bug...",submitSuccess:"Relatório de bug enviado com sucesso!",submitFailed:"Falha ao enviar relatório de bug",thankYou:"Obrigado!",submitted:"Seu relatório de bug foi enviado.",viewIssue:"Ver issue",unexpectedError:"Ocorreu um erro inesperado"}},Tue={nav:{printers:"打印机",archives:"归档",queue:"队列",stats:"统计",profiles:"配置文件",maintenance:"维护",projects:"项目",inventory:"耗材",files:"文件管理器",notifications:"通知",settings:"设置",system:"系统",collapseSidebar:"收起侧边栏",expandSidebar:"展开侧边栏",update:"更新",updateAvailable:"有可用更新:v{{version}}",updateAvailableBanner:"版本 {{version}} 已发布!",viewUpdate:"查看更新",viewOnGithub:"在 GitHub 上查看",keyboardShortcuts:"键盘快捷键 (?)",switchToLight:"切换到浅色模式",switchToDark:"切换到深色模式",smartSwitches:"智能开关",logout:"退出登录"},common:{save:"保存",saving:"保存中...",cancel:"取消",delete:"删除",edit:"编辑",add:"添加",close:"关闭",confirm:"确认",loading:"加载中...",error:"错误",success:"成功",warning:"警告",enabled:"已启用",disabled:"已禁用",yes:"是",no:"否",on:"开",off:"关",all:"全部",none:"无",search:"搜索",filter:"筛选",sort:"排序",refresh:"刷新",download:"下载",upload:"上传",uploading:"上传中...",uploadFailed:"上传失败",actions:"操作",status:"状态",name:"名称",description:"描述",date:"日期",time:"时间",hours:"小时",minutes:"分钟",seconds:"秒",days:"天",enable:"启用",disable:"禁用",permissions:"权限",noPrinters:"未配置打印机",noData:"暂无数据",linkNotFound:"未找到链接",required:"必填",optional:"可选",dismiss:"关闭",apply:"应用",reset:"重置",export:"导出",import:"导入",clear:"清除",selectAll:"全选",deselectAll:"取消全选",noChange:"— 不更改 —",unchanged:"未更改",unassigned:"未分配",unknown:"未知",unknownError:"未知错误",today:"今天",tomorrow:"明天",asap:"尽快",overdue:"已逾期",now:"现在",collapse:"收起",expand:"展开",viewArchive:"查看归档",viewInFileManager:"在文件管理器中查看",addedBy:"由 {{username}} 添加",prints:"次打印",more:"还有 {{count}} 个",ascending:"升序",descending:"降序",printer:"打印机",remove:"移除",type:"类型",print:"打印",rename:"重命名",move:"移动",create:"创建",duplicate:"复制",left:"左",right:"右"},printers:{title:"打印机",addPrinter:"添加打印机",editPrinter:"编辑打印机",deletePrinter:"删除打印机",printerName:"打印机名称",serialNumber:"序列号",ipAddress:"IP 地址 / 主机名",accessCode:"访问码",model:"型号",nozzleCount:"喷嘴数量",autoArchive:"自动归档",status:{available:"可用",idle:"空闲",printing:"打印中",paused:"已暂停",offline:"离线",problem:"故障",error:"错误",finished:"已完成",unknown:"未知"},temperatures:{nozzle:"喷嘴",bed:"热床",chamber:"腔室"},progress:"{{percent}}% 完成",timeRemaining:"剩余 {{time}}",deleteConfirm:'确定要删除"{{name}}"吗?',maintenanceOk:"维护正常",maintenanceWarning:"{{count}} 个警告",maintenanceWarning_plural:"{{count}} 个警告",maintenanceDue:"{{count}} 个到期",maintenanceDue_plural:"{{count}} 个到期",sort:{name:"名称",status:"状态",model:"型号",location:"位置",ascending:"升序排列",descending:"降序排列"},cardSize:{small:"小卡片",medium:"中卡片",large:"大卡片",extraLarge:"超大卡片"},hideOffline:"隐藏离线",nextAvailable:"下一个可用",powerOn:"开机",offlinePrintersWithPlugs:"带智能插座的离线打印机",noPrintersConfigured:"尚未配置打印机",search:"搜索打印机...",noSearchResults:"没有打印机符合您的搜索或筛选条件",filter:{allStatuses:"所有状态",allLocations:"所有位置"},readyToPrint:"准备打印",external:"外部",extL:"外置左",extR:"外置右",deleteArchives:"删除打印归档",noLabel:"无标签",printPreview:"打印预览",width:"宽度",height:"高度",noObjectsFound:"未找到对象",objectsLoadedOnPrintStart:"对象在打印开始时加载",willBeSkipped:"将被跳过",name:"名称",serialCannotBeChanged:"序列号无法更改",locationHelp:"用于分组打印机和筛选队列任务",wifiSignal:{veryWeak:"非常弱",weak:"弱",fair:"一般",good:"良好",excellent:"优秀"},maintenanceUpToDate:"所有维护均已完成 - 点击查看",chamberLightOn:"打开腔室灯",chamberLightOff:"关闭腔室灯",files:"文件",browseFiles:"浏览打印机文件",autoOffAfterPrint:"打印后自动关机",autoOffExecuted:"已执行自动关机 - 开启打印机以重置",hmsErrors:"HMS 错误",viewHmsErrors:"查看 {{count}} 个 HMS 错误",resume:"继续",pause:"暂停",stop:"停止",camera:"摄像头",skipObject:"跳过对象",reconnect:"重新连接",mqttDebug:"MQTT 调试",printerInformation:"打印机信息",copyToClipboard:"复制",copied:"已复制!",state:"状态",wifiSignalLabel:"WiFi 信号",developerMode:"开发者模式",enabled:"已启用",disabled:"已禁用",addedOn:"添加日期",sdCard:"SD 卡",inserted:"已插入",notInserted:"未插入",totalPrintHours:"打印时长",activeNozzle:"当前:{{nozzle}} 喷嘴",nozzleRack:"喷嘴架",nozzleDocked:"已停靠",nozzleMounted:"已安装",nozzleActive:"使用中",nozzleIdle:"空闲",nozzleDiameter:"直径",nozzleType:"类型",nozzleStatus:"状态",nozzleFilament:"耗材",nozzleWear:"磨损",nozzleMaxTemp:"最高温度",nozzleSerial:"序列号",nozzleHardenedSteel:"硬化钢",nozzleStainlessSteel:"不锈钢",nozzleTungstenCarbide:"碳化钨",nozzleFlow:"流量",nozzleHighFlow:"高流量",nozzleStandardFlow:"标准",firmwareUpdate:"固件更新",firmwareInstructions:"在打印机触摸屏上,前往",firmwareNav:"导航到",settings:"设置",firmware:"固件",discoverPrinters:"发现打印机",searching:"搜索中...",manualEntry:"手动输入",addFromCloud:"从云端添加",toast:{printerDeleted:"打印机已删除",missingSpoolAssignment:"已在{{printer}}上开始打印。以下料槽未分配耗材: {{slots}}",printerAdded:"打印机已添加",printerUpdated:"打印机已更新",failedToDelete:"删除打印机失败",failedToAdd:"添加打印机失败",failedToUpdate:"更新打印机失败",commandSent:"命令已发送",failedToSendCommand:"发送命令失败",turnedOn:"{{name}} 已开启",failedToPowerOn:"开启 {{name}} 失败",scriptTriggered:"脚本已触发",printStopped:"打印已停止",printPaused:"打印已暂停",printResumed:"打印已继续",referenceDeleted:"参考已删除",detectionAreaSaved:"检测区域已保存",failedToRunScript:"运行脚本失败",failedToStopPrint:"停止打印失败",failedToPausePrint:"暂停打印失败",failedToResumePrint:"继续打印失败",failedToControlChamberLight:"控制腔室灯失败",failedToSetSpeed:"设置打印速度失败",failedToUpdateSetting:"更新设置失败",failedToSkipObjects:"跳过对象失败",failedToRereadRfid:"重新读取 RFID 失败",failedToCheckPlate:"检查打印板失败",failedToUpdateLabel:"更新标签失败",failedToDeleteReference:"删除参考失败",failedToSaveDetectionArea:"保存检测区域失败",plateCheckEnabled:"打印板检查已启用",plateCheckDisabled:"打印板检查已禁用",calibrationSaved:"校准已保存!",calibrationFailed:"校准失败",rfidRereadInitiated:"已发起 RFID 重新读取"},connection:{connected:"已连接",offline:"离线"},queue:{inQueue:"队列中有 {{count}} 个打印任务",inQueue_plural:"队列中有 {{count}} 个打印任务"},controls:"控制",rfid:{reread:"重新读取 RFID"},permission:{noAdd:"您没有添加打印机的权限",noEdit:"您没有编辑打印机的权限",noDelete:"您没有删除打印机的权限",noControl:"您没有控制打印机的权限",noFiles:"您没有访问打印机文件的权限",noAmsRfid:"您没有重新读取 AMS RFID 的权限",noSmartPlugControl:"您没有控制智能插座的权限",noCamera:"您没有查看摄像头的权限"},modal:{addTitle:"添加打印机",editTitle:"编辑打印机",myPrinter:"我的打印机",selectModel:"选择型号...",locationGroup:"位置 / 分组(可选)",locationPlaceholder:"例如:工作室、办公室、地下室",autoArchiveLabel:"自动归档已完成的打印",fromPrinterSettings:"来自打印机设置",modelOptional:"型号(可选)",saveChanges:"保存更改"},skipObjects:{tooltip:"跳过对象",onlyWhilePrinting:"跳过对象(仅在打印时)",requiresMultiple:"跳过对象(需要2个以上对象)",title:"跳过对象",matchIdsInfo:"将 ID 与打印机显示屏上的 ID 进行对照",printerShowsIds:"打印机屏幕上显示构建板上对象的 ID",skipSelected:"跳过所选",skipping:"跳过中...",noObjectsSelected:"未选择对象",selectObjectsToSkip:"选择要从当前打印中跳过的对象",skipped:"已跳过",objectsSkipped:"对象已跳过",activeCount:"{{count}} 个活跃",waitForLayer:"等待第2层以上才能跳过对象(当前第 {{layer}} 层)",skip:"跳过",confirmTitle:"跳过对象?",confirmMessage:'确定要跳过"{{name}}"吗?此操作无法撤销。'},confirm:{deleteTitle:"删除打印机",deleteMessage:'确定要删除"{{name}}"吗?这将移除所有连接设置。',deleteArchivesNote:"此打印机的所有打印历史将被永久删除。",keepArchivesNote:"打印历史将保留,但不再与此打印机关联。",stopTitle:"停止打印",stopMessage:'确定要停止"{{name}}"上的当前打印吗?这将取消打印任务。',stopButton:"停止打印",pauseTitle:"暂停打印",pauseMessage:'确定要暂停"{{name}}"上的当前打印吗?',pauseButton:"暂停打印",resumeTitle:"继续打印",resumeMessage:'确定要继续"{{name}}"上的打印吗?',resumeButton:"继续打印",powerOnTitle:"开启打印机",powerOnMessage:'确定要打开"{{name}}"的电源吗?',powerOnButton:"开机",powerOffTitle:"关闭打印机",powerOffMessage:'确定要关闭"{{name}}"的电源吗?',powerOffWarning:'警告:"{{name}}"正在打印中!确定要关闭电源吗?这将中断打印并可能损坏打印机。',powerOffButton:"关机"},bulk:{select:"选择",selectAll:"全选",selectByLocation:"按位置选择",selected:"已选择{{count}}台",actions:{stop:"停止",pause:"暂停",resume:"继续",clearPlate:"清除打印床",clearHMS:"清除通知"},confirm:{stopTitle:"停止{{count}}个打印任务",stopMessage:"这将取消{{count}}台打印机上的活动打印任务。此操作无法撤销。",stopButton:"全部停止",pauseTitle:"暂停{{count}}个打印任务",pauseMessage:"这将暂停{{count}}台打印机上的活动打印任务。",pauseButton:"全部暂停",clearPlateTitle:"清除{{count}}个打印床",clearPlateMessage:"这将清除{{count}}台打印机的打印床,可能会触发队列中的任务。",clearPlateButton:"全部清除"},success:"{{action}}已在{{count}}台打印机上完成",partial:"{{succeeded}}成功,{{failed}}失败",noneApplicable:"没有选中的打印机处于适合此操作的状态",selectByState:"按状态选择"},discovery:{title:"发现打印机",searching:"搜索中...",scanning:"扫描中...",scanProgress:"扫描中... {{scanned}}/{{total}}",foundPrinters:"发现 {{count}} 台打印机",noPrintersFound:"未找到打印机",noPrintersFoundSubnet:"在指定子网中未找到打印机。",noPrintersFoundNetwork:"在网络上未找到打印机。",allConfigured:"所有发现的打印机已配置完毕。",alreadyAdded:"已添加",select:"选择",manualEntry:"手动输入",addFromCloud:"从云端添加",subnetToScan:"要扫描的子网",dockerNote:"检测到 Docker 环境。请以 CIDR 格式输入打印机所在子网。需要在 docker-compose.yml 中设置 network_mode: host。",scanSubnet:"扫描子网查找打印机",discoverNetwork:"在网络上发现打印机",scanningSubnet:"正在扫描子网查找拓竹打印机...",scanningNetwork:"正在扫描网络...",serialRequired:"需要序列号",unknown:"未知",failedToStart:"启动发现失败"},drying:{start:"开始干燥",stop:"停止干燥",temperature:"温度",duration:"时长",hours:"小时",timeRemaining:"剩余 {{time}}",active:"干燥中",notSupported:"不支持干燥",powerRequired:"连接AMS电源适配器以启用干燥",startingDrying:"正在启动干燥...",stoppingDrying:"正在停止干燥...",rotateTray:"干燥时旋转料盘"},filaments:"耗材",openCameraOverlay:"打开摄像头叠加层",openCameraWindow:"在新窗口中打开摄像头",firmwareUpdateAvailable:"固件更新可用:{{current}} → {{latest}}",firmwareUpToDate:"固件 {{version}} — 已是最新",firmwareUpdateButton:"更新",plateDetection:{noPermission:"您没有更新打印机的权限",enabledClick:"打印板检查已启用 - 点击禁用",disabledClick:"打印板检查已禁用 - 点击启用",manageCalibration:"管理打印板检测校准",calibrationRequired:"需要校准",calibrationInstructions:"请确保构建板<strong>完全空置</strong>,然后点击校准。",calibrationDescription:"校准会拍摄空置打印板的参考图像。后续检查将与此参考进行比较以检测物体。",calibrationTip:"<strong>提示:</strong>您最多可以为不同的打印板存储5个校准。系统会在检查时自动使用最佳匹配。",plateEmpty:"打印板似乎是空的",objectsDetected:"在打印板上检测到物体",confidence:"置信度",difference:"差异",analysisPreview:"分析预览:",analysisLegend:"绿色框 = 检测区域,红色覆盖 = 与校准的差异",savedReferences:"已保存的参考 ({{count}}/{{max}})",deleteReference:"删除参考",labelPlaceholder:"标签...",clickToEdit:"{{label}} - 点击编辑",clickToAddLabel:"点击添加标签"},speed:{title:"打印速度",silent:"静音 (50%)",standard:"标准 (100%)",sport:"运动 (124%)",ludicrous:"疯狂 (166%)"},fans:{partCooling:"零件冷却风扇",auxiliary:"辅助风扇",chamber:"腔室风扇"},clickToViewHmsErrors:"点击查看 HMS 错误",estimatedCompletion:"预计完成时间",plateNumber:"板 {{number}}",slotOptions:"槽位选项",amsPopup:{friendlyName:"AMS 名称",friendlyNamePlaceholder:"例如 AMS 友好名称",serialNumber:"序列号",firmwareVersion:"固件",save:"保存",clear:"清除",noEditPermission:"您没有重命名 AMS 单元的权限"},firmwareModal:{title:"固件更新",titleUpToDate:"固件信息",currentVersion:"当前版本:",latestVersion:"最新版本:",releaseNotes:"发布说明",checkingPrereqs:"正在检查前提条件...",sdCardReady:"SD 卡已就绪。点击下方上传固件。",uploadedSuccess:"固件已上传到 SD 卡!",applyInstructions:"在打印机上应用更新:",step1:"在打印机触摸屏上,前往<strong>设置</strong>",step2:"导航到<strong>固件</strong>",step3:"选择<strong>从 SD 卡更新</strong>",step4:"更新将需要 10-20 分钟",done:"完成",starting:"启动中...",uploadFirmware:"上传固件",uploadFailed:"上传启动失败:{{error}}",uploadedToast:"固件已上传!请在打印机屏幕上触发更新。"},accessCodePlaceholder:"留空以保持当前值",roi:{title:"检测区域 (ROI)",xStart:"X 起点",yStart:"Y 起点",width:"宽度",height:"高度",instruction:"调整检测区域以聚焦到构建板。预览中的绿色框显示当前区域。"},developerModeWarning:"以下打印机未启用开发者局域网模式:{{names}}。某些功能可能无法使用。",howToEnable:"如何启用",incompatibleFile:"此文件是为 {{slicedFor}} 切片的,但该打印机是 {{printerModel}}",dropNotPrintable:"只能打印 .gcode 和 .gcode.3mf 文件",dropToPrint:"拖放以打印",cannotPrint:"打印机忙碌"},archives:{title:"打印归档",searchPlaceholder:"搜索归档...",filterByPrinter:"按打印机筛选",filterByStatus:"按状态筛选",sortBy:"排序方式",sortNewest:"最新优先",sortOldest:"最旧优先",sortName:"名称",sortDuration:"时长",sortLargest:"最大优先",sortSmallest:"最小优先",sortSize:"大小",noArchives:"未找到归档",noArchivesSearch:"没有匹配搜索的归档",originalPrintNotVisible:"原始打印不可见 - 请尝试清除筛选条件",noArchivesYet:"暂无归档",prints:"条打印",pagination:{showing:"显示",to:"至",of:"共",show:"每页",page:"页",all:"全部"},loadingArchives:"加载归档中...",releaseToUpload:"释放以上传",showAll:"显示全部",showFavoritesOnly:"仅显示收藏",gridView:"网格视图",listView:"列表视图",calendarView:"日历视图",logView:"打印日志",manageTags:"管理标签",showFailedPrints:"显示失败的打印",hideFailedPrints:"隐藏失败的打印",hideDuplicates:"隐藏重复项",viewOriginalPrint:"点击查看原始打印 (#{{id}})",printTime:"打印时间",filamentUsed:"耗材用量",cost:"成本",reprint:"重新打印",preview:"预览",deleteArchive:"删除归档",deleteConfirm:"确定要删除此归档吗?",favorite:"收藏",unfavorite:"取消收藏",viewDetails:"查看详情",status:{completed:"已完成",failed:"失败",stopped:"已停止"},toast:{source3mfAttached:"源 3MF 已附加:{{filename}}",failedUploadSource3mf:"上传源 3MF 失败",source3mfRemoved:"源 3MF 已移除",failedRemoveSource3mf:"移除源 3MF 失败",f3dAttached:"F3D 已附加:{{filename}}",failedUploadF3d:"上传 F3D 失败",f3dRemoved:"F3D 已移除",failedRemoveF3d:"移除 F3D 失败",timelapseAttached:"延时摄影已附加:{{filename}}",timelapseAlreadyAttached:"延时摄影已附加",noMatchingTimelapse:"未找到匹配的延时摄影",failedScanTimelapse:"扫描延时摄影失败",failedAttachTimelapse:"附加延时摄影失败",timelapseRemoved:"延时摄影已移除",failedRemoveTimelapse:"移除延时摄影失败",timelapseUploaded:"延时摄影已上传:{{filename}}",failedUploadTimelapse:"上传延时摄影失败",archiveDeleted:"归档已删除",failedDeleteArchive:"删除归档失败",addedToFavorites:"已添加到收藏",removedFromFavorites:"已从收藏中移除",projectUpdated:"项目已更新",failedUpdateProject:"更新项目失败",linkCopied:"链接已复制到剪贴板",failedCopyLink:"复制链接失败",photoDeleted:"照片已删除",failedDeletePhoto:"删除照片失败",failedDeleteArchives:"删除归档失败",failedUpdateFavorites:"更新收藏失败",exportDownloaded:"导出已下载",exportFailed:"导出失败"},menu:{print:"打印",schedule:"排程",openInBambuStudio:"在切片软件中打开",slice:"切片",externalLink:"外部链接",viewOnMakerWorld:"在 MakerWorld 上查看",preview3d:"3D 预览",viewTimelapse:"查看延时摄影",scanForTimelapse:"扫描延时摄影",uploadTimelapse:"上传延时摄影",removeTimelapse:"移除延时摄影",downloadSource3mf:"下载源 3MF",uploadSource3mf:"上传源 3MF",replaceSource3mf:"替换源 3MF",removeSource3mf:"移除源 3MF",uploadF3d:"上传 F3D",replaceF3d:"替换 F3D",downloadF3d:"下载 F3D",removeF3d:"移除 F3D",download:"下载",copyDownloadLink:"复制下载链接",qrCode:"二维码",viewPhotos:"查看照片",viewPhotosCount:"查看照片 ({{count}})",projectPage:"项目页面",addToFavorites:"添加到收藏",removeFromFavorites:"从收藏中移除",edit:"编辑",goToProject:"前往项目:{{name}}",addToProject:"添加到项目",removeFromProject:"从项目中移除",loading:"加载中...",noProjectsAvailable:"无可用项目",select:"选择",deselect:"取消选择",delete:"删除"},permission:{noReprint:"您没有重新打印此归档的权限",noAddToQueue:"您没有添加到队列的权限",noUpdateArchives:"您没有更新归档的权限",noUploadFiles:"您没有上传文件的权限",noDownload:"您没有下载归档的权限",noCopyLink:"您没有复制下载链接的权限",noDelete:"您没有删除此归档的权限",noCreate:"您没有创建归档的权限"},card:{previousPlate:"上一个板",nextPlate:"下一个板",plateNumber:"板 {{index}}",moreOptions:"右键查看更多选项",addToFavorites:"添加到收藏",removeFromFavorites:"从收藏中移除",cancelled:"已取消",failed:"失败",duplicate:"重复",duplicateTitle:"此模型之前已打印过",openSource3mf:"在 Bambu Studio 中打开源 3MF(右键查看更多选项)",downloadF3d:"下载 Fusion 360 设计文件",viewTimelapse:"查看延时摄影",viewPhoto:"查看 1 张照片",viewPhotos:"查看 {{count}} 张照片",openFolder:"打开文件夹:{{name}}",slicedFile:"已切片文件 - 可以打印",sourceFile:"仅源文件 - 无 AMS 映射可用",gcode:"GCODE",source:"源文件",project:"项目:{{name}}",estimated:"预计:{{time}}",actual:"实际:{{time}}",accuracy:"准确度:{{percent}}%",filament:"{{weight}}g",layer:"{{count}} 层",layers:"{{count}} 层",object:"{{count}} 个对象",objects:"{{count}} 个对象",slicedFor:"为 {{model}} 切片",uploadedBy:"上传者",noPermissionReprint:"您没有重新打印的权限",noFileForReprint:"无可用的 3MF 文件 — 打印记录时无法从打印机下载该文件",noPermissionEdit:"您没有编辑归档的权限",noPermissionDelete:"您没有删除归档的权限",reprint:"重新打印",schedulePrint:"排程打印",schedule:"排程",openInBambuStudio:"在切片软件中打开",openInBambuStudioToSlice:"在切片软件中打开进行切片",slice:"切片",externalLink:"外部链接",makerWorld:"MakerWorld:{{designer}}",viewProject:"查看项目",noExternalLink:"无外部链接",preview3d:"3D 预览",download:"下载",edit:"编辑",delete:"删除"},modal:{deleteArchive:"删除归档",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',deleteButton:"删除",removeSource3mf:"移除源 3MF",removeSource3mfConfirm:'确定要从"{{name}}"中移除源 3MF 文件吗?这将删除原始切片项目文件。',removeButton:"移除",removeF3d:"移除 F3D",removeF3dConfirm:'确定要从"{{name}}"中移除 Fusion 360 设计文件吗?',removeTimelapse:"移除延时摄影",removeTimelapseConfirm:'确定要从"{{name}}"中移除延时摄影视频吗?',timelapse:"{{name}} - 延时摄影",selectTimelapse:"选择延时摄影",selectTimelapseDesc:"未找到自动匹配。请选择此打印的延时摄影:",deleteArchives:"删除归档",deleteArchivesConfirm:"确定要删除 {{count}} 个归档吗?此操作无法撤销。",deleteCount:"删除 {{count}} 个"},page:{title:"归档",printsCount:"{{filtered}} / {{total}} 次打印",dropFilesHere:"将 .3mf 文件拖放到此处",releaseToUpload:"释放以上传",only3mfSupported:"仅支持 .3mf 文件",close:"关闭",selected:"已选择 {{count}} 个",selectAll:"全选",tags:"标签",project:"项目",favorite:"收藏",delete:"删除",toggledFavorites:"已切换 {{count}} 个归档的收藏状态",failedUpdateFavorites:"更新收藏失败",archivesDeleted:"已删除 {{count}} 个归档",failedDeleteArchives:"删除归档失败",photoDeleted:"照片已删除",failedDeletePhoto:"删除照片失败"},list:{name:"名称",printer:"打印机",date:"日期",size:"大小",actions:"操作",hasTimelapse:"有延时摄影"},log:{date:"日期",printName:"打印名称",printer:"打印机",user:"用户",status:"状态",duration:"时长",filament:"耗材",allPrinters:"所有打印机",allUsers:"所有用户",allStatuses:"所有状态",cancelled:"已取消",skipped:"已跳过",dateFrom:"从",dateTo:"到",noEntries:"未找到打印日志条目",showing:"显示 {{count}} / {{total}} 条",rowsPerPage:"行数",page:"页",prev:"上一页",next:"下一页",clearLog:"清除日志",clearLogTitle:"清除打印日志",clearLogConfirm:"所有打印日志条目将被永久删除。归档和队列项目不受影响。此操作无法撤销。确定要继续吗?",clearLogButton:"全部清除",cleared:"已清除 {{count}} 条日志",clearFailed:"清除打印日志失败"}},queue:{title:"打印队列",subtitle:"排程和管理您的打印任务",addToQueue:"添加到队列",print:"打印",reprint:"重新打印",schedulePrint:"排程打印",editQueueItem:"编辑队列项目",printToPrinters:"打印到 {{count}} 台打印机",queueToPrinters:"排队到 {{count}} 台打印机",queueSelectedPlates:"将 {{count}} 个热床加入队列",selectAllPlates:"选择全部 {{count}} 个热床",deselectAll:"取消全选",printQueued:"已加入打印队列",itemsQueued:"{{count}} 个任务已加入队列",sending:"发送中...",sendingProgress:"发送中 {{current}}/{{total}}...",adding:"添加中...",addingProgress:"添加中 {{current}}/{{total}}...",savingProgress:"保存中 {{current}}/{{total}}...",clearQueue:"清空队列",clearHistory:"清除历史",emptyQueue:"队列为空",position:"位置",scheduledTime:"排程时间",moveUp:"上移",moveDown:"下移",startNow:"立即开始",printingInProgress:"打印进行中...",viewArchive:"查看归档",viewInFileManager:"在文件管理器中查看",itemCount:"{{count}} 个项目",itemCount_plural:"{{count}} 个项目",dragToReorder:"拖动以重新排序(仅限尽快)",reorderHint:'位置仅影响"尽快"项目。排程项目按设定时间运行。',sjf:{label:"SJF",tooltip:"最短任务优先 — 调度器优先处理较短的打印任务"},addedBy:"由 {{name}} 添加",nextInQueue:"队列中的下一个",clearPlate:"清理打印板并开始下一个",clearPlateSuccess:"打印板已清理 — 准备进行下一个打印",plateReady:"打印板已清理 — 准备进行下一个打印",plateNumber:"板 {{index}}",quantity:"数量",quantityHint:"创建 {{count}} 个队列项目",activeBatches:"活跃批次",batchProgress:"已完成 {{completed}}/{{total}}",cancelBatch:"取消剩余",batchCancelled:"已取消剩余批次项目",cancelBatchConfirmTitle:"取消批次",cancelBatchConfirmMessage:"取消此批次中所有剩余的待处理项目?",batch:"批次",sections:{currentlyPrinting:"正在打印",queued:"排队中",history:"历史"},status:{pending:"等待中",waiting:"等待中",printing:"打印中",paused:"已暂停",completed:"已完成",failed:"失败",skipped:"已跳过",cancelled:"已取消"},summary:{printing:"打印中",queued:"排队中",totalTime:"总队列时间",totalWeight:"总队列重量",history:"历史"},filter:{allPrinters:"所有打印机",unassigned:"未分配",allStatus:"所有状态",allLocations:"所有位置",any:"任意"},sort:{byPosition:"按位置排序",byName:"按名称排序",byPrinter:"按打印机排序",bySchedule:"按排程排序",byDate:"按日期排序",ascendingOldest:"升序(最旧优先)",descendingNewest:"降序(最新优先)"},badges:{staged:"已暂存",requiresPrevious:"需要前一个成功",autoPowerOff:"自动关机",gcodeInjection:"G-code"},empty:{title:"没有排程的打印",description:'从归档页面使用右键菜单中的"排程"选项来排程打印,或拖放文件开始。'},time:{asap:"尽快",overdue:"已逾期",now:"现在",lessThanMinute:"不到一分钟",inMinutes:"{{count}} 分钟后",inHours:"{{count}} 小时后"},actions:{stopPrint:"停止打印",startPrint:"开始打印",requeue:"重新排队"},bulkEdit:{title:"编辑 {{count}} 个项目",title_plural:"编辑 {{count}} 个项目",description:"仅更改的设置将应用于所选项目。",printer:"打印机",noChange:"— 不更改 —",queueOptions:"队列选项",staged:"暂存(手动开始)",autoPowerOff:"打印后自动关机",requirePrevious:"要求前一个成功",printOptions:"打印选项",bedLevelling:"热床调平",flowCalibration:"流量校准",vibrationCalibration:"振动校准",layerInspection:"首层检查",timelapse:"延时摄影",useAms:"使用 AMS",applyChanges:"应用更改",selectAll:"全选",deselectAll:"取消全选",selected:"已选择 {{count}} 个",editSelected:"编辑所选",cancelSelected:"取消所选"},confirm:{cancelTitle:"取消排程打印",cancelMessage:'确定要取消"{{name}}"吗?',stopTitle:"停止打印",stopMessage:'确定要停止当前打印"{{name}}"吗?这将取消打印机上的打印任务。',removeTitle:"从历史中移除",removeMessage:'确定要从队列历史中移除"{{name}}"吗?',clearHistoryTitle:"清除历史",clearHistoryMessage:"确定要从历史中移除所有 {{count}} 个项目吗?",cancelButton:"取消打印",stopButton:"停止打印",thisPrint:"此打印",thisItem:"此项目"},toast:{cancelled:"队列项目已取消",cancelFailed:"取消项目失败",removed:"队列项目已移除",removeFailed:"移除项目失败",stopped:"打印已停止",stopFailed:"停止打印失败",released:"打印已释放到队列",startFailed:"开始打印失败",reorderFailed:"重新排序队列失败",historyCleared:"已清除 {{count}} 条历史记录",clearHistoryFailed:"清除历史失败",updateFailed:"更新项目失败",bulkCancelled:"已取消 {{count}} 个项目",bulkCancelFailed:"批量取消项目失败"},timeline:{listView:"列表",timelineView:"时间线",unassigned:"未分配",noData:"当天没有计划的打印任务",allDoneBy:"所有打印预计在 {{time}} 前完成",staged:"暂存",filterAll:"全部显示",filterPrinting:"打印中",filterQueued:"排队中",time:{anyMoment:"即将完成",minutesLeft:"剩余{{minutes}}分钟",hoursLeft:"剩余{{hours}}小时",hoursMinutesLeft:"剩余{{hours}}小时{{minutes}}分钟"},day:{previous:"前一天",next:"后一天",today:"今天"}},permissions:{noStopPrint:"您没有停止打印的权限",noStartPrint:"您没有开始打印的权限",noEdit:"您没有编辑此队列项目的权限",noCancel:"您没有取消此队列项目的权限",noRequeue:"您没有重新排队的权限",noRemove:"您没有移除此队列项目的权限",noClearHistory:"您没有清除所有历史的权限",noEditItems:"您没有编辑队列项目的权限",noCancelItems:"您没有取消队列项目的权限"}},backgroundDispatch:{unknownFile:"未知文件",unknownPrinter:"未知打印机",startingPrints:"正在开始打印",progressSummary:"{{complete}}/{{total}} 完成 • 已分发:{{dispatched}} • 处理中:{{processing}}",expandDetails:"展开分发详情",collapseDetails:"收起分发详情",dismissToast:"关闭分发通知",cancelDispatchJob:"取消分发任务",cancel:"取消",cancelling:"取消中…",status:{dispatched:"已分发",processing:"处理中",completed:"已完成",failed:"失败",cancelled:"已取消"},toast:{cancellingUpload:"取消上传中...",cancelled:"分发已取消",cancelFailed:"取消分发失败",completeWithFailures:"后台分发完成:{{completed}} 成功,{{failed}} 失败",completeSuccess:"后台分发完成:{{completed}} 成功",printStartedRemaining:"{{completed}} 个打印已开始,{{remaining}} 个正在发送..."}},stats:{title:"仪表板",subtitle:"拖动小部件以重新排列。点击眼睛图标隐藏。",overview:"概览",totalPrints:"总打印次数",successRate:"成功率",totalPrintTime:"总打印时间",printTime:"打印时间",totalFilament:"总耗材用量",filamentUsed:"耗材用量",filamentCost:"耗材成本",totalCost:"总成本",energyUsed:"能耗",energyCost:"能源成本",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:"虚拟打印机",users:"身份验证",backup:"备份",emailAuth:"邮箱认证",ldap:"LDAP"},ldap:{title:"LDAP 认证",enabledDesc:"LDAP 认证已启用",disabledDesc:"LDAP 认证已禁用",disabledHint:"在下方配置并保存 LDAP 设置,然后启用。",enabled:"LDAP 认证已启用",disabled:"LDAP 认证已禁用",feature1:"用户可以使用 LDAP 凭据登录",feature2:"本地管理员帐户作为后备保留",feature3:"登录时 LDAP 组映射到 BamBuddy 组",serverConfig:"LDAP 服务器配置",serverUrl:"服务器 URL",serverUrlHint:"使用 ldap:// 进行标准连接或 ldaps:// 进行 SSL 连接",security:"安全",securityHint:"StartTLS 将普通连接升级为 TLS。LDAPS 从一开始就使用 TLS。",bindDn:"绑定 DN(服务帐户)",bindPassword:"绑定密码",searchBase:"搜索基础 DN",userFilter:"用户搜索过滤器",userFilterHint:"{username} 替换为登录用户名。OpenLDAP 使用 (uid={username})。",autoProvision:"自动创建用户",autoProvisionHint:"首次 LDAP 登录时自动创建 BamBuddy 帐户",defaultGroup:"默认组",defaultGroupNone:"— 无(无回退)—",defaultGroupHint:"当 LDAP 用户通过身份验证但不在任何已映射的 LDAP 组中时分配的回退组。留空以使未映射的用户没有权限。",groupMapping:"组映射(JSON)",groupMappingHint:"将 LDAP 组 DN 映射到 BamBuddy 组。可用组:",testConnection:"测试连接",settingsSaved:"LDAP 设置已保存",errors:{serverRequired:"LDAP 服务器 URL 为必填项",searchBaseRequired:"搜索基础 DN 为必填项",enableAuthFirst:"请先启用认证",configureLdapFirst:"请先保存 LDAP 设置"}},email:{smtpSettings:"SMTP 配置",smtpHost:"SMTP 服务器",smtpPort:"SMTP 端口",security:"安全",authentication:"认证",username:"用户名",password:"密码",fromEmail:"发件邮箱",fromName:"发件人名称",testConnection:"测试 SMTP 连接",testRecipient:"测试收件邮箱",sendTest:"发送测试邮件",sending:"发送中...",save:"保存设置",saving:"保存中...",advancedAuth:"高级认证",advancedAuthEnabled:"高级认证已启用",advancedAuthEnabledDesc:"基于邮箱的用户管理功能已激活。新用户将通过邮件收到自动生成的密码,用户可以通过忘记密码功能重置密码。",advancedAuthDisabled:"高级认证已禁用",advancedAuthDisabledDesc:"启用高级认证以激活基于邮箱的用户管理功能。",enable:"启用",disable:"禁用",feature1:"密码自动生成并通过邮件发送给新用户",feature2:"用户可以使用用户名或邮箱登录",feature3:"忘记密码功能可用",feature4:"管理员可以通过邮件重置用户密码",errors:{requiredFields:"请填写所有必填字段",usernameRequired:"启用认证时需要用户名",enterTestEmail:"请输入测试邮箱地址",smtpServerAndEmail:"测试前请填写 SMTP 服务器和发件邮箱",usernamePasswordRequired:"启用认证时需要用户名和密码",configureSmtpFirst:"请先配置并测试 SMTP 设置",enableAuthFirst:"请先启用身份验证才能使用基于电子邮件的功能。"},success:{settingsSaved:"SMTP 设置保存成功"},securityOptions:{starttls:"STARTTLS(端口 587)",ssl:"SSL/TLS(端口 465)",none:"无(端口 25)"},authOptions:{enabled:"已启用",disabled:"已禁用"}},appearance:"外观",notifications:"通知",smartPlugs:"智能插座",spoolman:"Spoolman",updates:"更新",language:"语言",languageDescription:"选择您的首选语言",theme:"主题",themeLight:"浅色",themeDark:"深色",themeSystem:"跟随系统",defaultView:"默认视图",defaultViewDescription:"打开应用时显示的页面",checkForUpdates:"检查更新",autoUpdate:"自动更新",currentVersion:"当前版本",latestVersion:"最新版本",upToDate:"已是最新版本",updateAvailable:"有可用更新",notificationLanguage:"通知语言",notificationLanguageDescription:"推送通知的语言",bedCooledThreshold:"热床冷却阈值",bedCooledThresholdDescription:"打印后热床被视为已冷却的温度",userNotificationsEnabled:"用户通知",userNotificationsEnabledDescription:"启用用户通知菜单和打印任务事件的邮件通知。需要高级身份验证。",userNotificationsDisabledHint:"请启用高级身份验证以使用用户通知。",notificationProviders:"通知提供商",addProvider:"添加提供商",editProvider:"编辑提供商",providerType:"提供商类型",testNotification:"测试通知",testSuccess:"测试通知发送成功",testFailed:"发送测试通知失败",quietHours:"免打扰时间",quietHoursDescription:"在此时间段内不发送通知",quietHoursStart:"开始",quietHoursEnd:"结束",events:{title:"通知事件",printStart:"打印开始",printComplete:"打印完成",printFailed:"打印失败",printStopped:"打印停止",printProgress:"进度里程碑",printProgressDescription:"在 25%、50%、75% 时通知",printerOffline:"打印机离线",printerError:"打印机错误",filamentLow:"耗材不足",maintenanceDue:"维护到期",maintenanceDueDescription:"需要维护时通知"},smartPlug:{title:"智能插座",add:"添加智能插座",edit:"编辑智能插座",name:"名称",ipAddress:"IP 地址",linkedPrinter:"关联打印机",autoOn:"自动开启",autoOnDescription:"打印开始时开启",autoOff:"自动关闭",autoOffDescription:"打印完成后关闭",offDelay:"关闭延迟",offDelayMinutes:"打印后分钟数",offDelayTemp:"当喷嘴温度低于",currentState:"当前状态",turnOn:"开启",turnOff:"关闭"},filamentTracking:"耗材追踪",filamentTrackingDesc:"选择如何追踪您的耗材。您可以使用内置库存或连接外部 Spoolman 服务器。",filamentChecks:"耗材检查",disableFilamentWarnings:"禁用耗材警告",disableFilamentWarningsDesc:"在打印或加入队列时不显示耗材不足警告",preferLowestFilament:"优先使用剩余最少的耗材",preferLowestFilamentDesc:"当多个料盘匹配时,使用剩余耗材最少的那个",trackingModeBuiltIn:"内置库存",trackingModeBuiltInDesc:"包含 RFID 自动匹配和用量追踪",trackingModeSpoolmanDesc:"外部耗材管理服务器",builtInFeatureRfid:"自动检测 AMS 中的拓竹 RFID 耗材",builtInFeatureUsage:"追踪每次打印的耗材消耗",builtInFeatureCatalog:"管理耗材、颜色和 K 值配置文件",builtInFeatureThirdParty:"第三方耗材可分配到库存耗材",amsSyncButton:"从 AMS 同步重量",amsSyncTitle:"从 AMS 同步耗材重量",amsSyncMessage:"这将使用已连接打印机的当前 AMS 剩余百分比值覆盖所有库存耗材重量。用于从损坏的重量数据中恢复。打印机必须在线。",amsSyncing:"同步中...",amsSyncSuccess:"已同步 {{synced}} 个耗材,跳过 {{skipped}} 个",amsSyncError:"从 AMS 同步重量失败",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"Spoolman 服务器的 URL(例如 http://localhost:7912)",spoolmanConnected:"已连接",spoolmanDisconnected:"未连接",status:"状态",connect:"连接",disconnect:"断开",howSyncWorks:"同步工作原理",syncInfoRfidOnly:"仅同步带有 RFID 的官方拓竹耗材",syncInfoAutoCreate:"首次同步时自动在 Spoolman 中创建新耗材",syncInfoThirdPartySkipped:"非拓竹耗材(第三方、重新填充的)将被跳过",linkingExistingSpools:"链接现有耗材",linkingExistingSpoolsDesc:'要将现有的 Spoolman 耗材链接到您的 AMS,请将鼠标悬停在 AMS 槽位上并点击"链接到 Spoolman"。',syncMode:"同步模式",syncModeAuto:"自动",syncModeManual:"仅手动",syncModeAutoDesc:"检测到更改时自动同步 AMS 数据",syncModeManualDesc:"仅在手动触发时同步",syncAmsData:"同步 AMS 数据",syncAmsDataDesc:"手动将打印机 AMS 数据同步到 Spoolman",allPrinters:"所有打印机",noDefaultPrinter:"无默认(每次询问)",sidebarOrder:"侧边栏顺序",saveThumbnails:"保存缩略图",captureFinishPhoto:"拍摄完成照片",noPrintersConfigured:"未配置打印机",archiveMode:{always:"始终创建归档条目",never:"从不创建归档条目",ask:"每次询问"},checkForUpdatesLabel:"检查更新",checkPrinterFirmware:"检查打印机固件",includeBetaUpdates:"包含测试版本",includeBetaUpdatesDesc:"检查更新时通知测试版和预发布版本",enableRetry:"启用重试",homeAssistantDescription:"通过 Home Assistant 控制智能插座",environmentManagedLabel:"(环境变量管理)",autoEnabledViaEnv:"通过环境变量自动启用",urlFromEnvReadOnly:"值由 HA_URL 环境变量设置(只读)",tokenFromEnvReadOnly:"值由 HA_TOKEN 环境变量设置(只读)",mqttConnectedTo:"已连接到",prometheusDescription:"以 Prometheus 格式暴露打印机数据",noSmartPlugsTitle:"未配置智能插座",noSmartPlugsDescription:"添加基于 Tasmota 的智能插座以追踪能耗并自动化电源控制。",noProvidersTitle:"未配置提供商",noProvidersDescription:"添加提供商以接收警报。",noTemplatesAvailable:"无可用模板。重启后端以加载默认模板。",apiPermissionView:"查看打印机状态和队列",apiPermissionEdit:"添加和移除打印队列中的项目",apiKeysEmptyTitle:"无 API 密钥",apiKeysEmptyDescription:"创建 API 密钥以与外部服务集成。",noUsersFound:"未找到用户",noGroupsFound:"未找到组",noGroupsAvailable:"无可用组",passwordsDoNotMatch:"密码不匹配",systemGroupWarning:"系统组名称不可更改",authDisabledTitle:"身份验证已禁用",authDisabledFeature1:"需要登录才能访问系统",authDisabledFeature2:"创建多个用户并基于组的权限管理",authDisabledFeature3:"使用 50+ 个细粒度权限控制访问",userHasCreated:"此用户已创建:",userItemsQuestion:"您想如何处理这些项目?",deleteUserConfirm:"确定要删除此用户吗?",actionCannotBeUndone:"此操作无法撤销。",addFirstSmartPlug:"添加您的第一个智能插座",providers:"提供商",log:"日志",testAll:"全部测试",testResults:"测试结果",testPassedCount:"{{count}} 个通过",testFailedCount:"{{count}} 个失败",messageTemplates:"消息模板",messageTemplatesDescription:"自定义每个事件的通知消息。",apiKeys:"API 密钥",apiKeysDescription:"创建 API 密钥用于外部集成和 Webhook。",createKey:"创建密钥",apiKeyCreated:"API 密钥创建成功",apiKeyCopyWarning:"请立即复制此密钥 - 它不会再次显示!",useInApiBrowser:"在 API 浏览器中使用",createNewApiKey:"创建新 API 密钥",keyName:"密钥名称",keyNamePlaceholder:"例如:Home Assistant、OctoPrint",readStatus:"读取状态",readStatusDescription:"查看打印机状态和队列",manageQueue:"管理队列",manageQueueDescription:"添加和移除打印队列中的项目",controlPrinter:"控制打印机",controlPrinterDescription:"暂停、继续和停止打印",unnamedKey:"未命名密钥",lastUsed:"上次使用",read:"读取",control:"控制",createFirstKey:"创建您的第一个密钥",webhookEndpoints:"Webhook 端点",webhookApiKeyHint:"在 X-API-Key 请求头中使用您的 API 密钥。",webhook:{getAllStatus:"获取所有打印机状态",getSpecificStatus:"获取特定打印机状态",addToQueue:"添加到打印队列",pausePrint:"暂停打印",resumePrint:"继续打印",stopPrint:"停止打印"},apiBrowser:"API 浏览器",apiBrowserDescription:"浏览和测试所有可用的 API 端点。",apiKeyForTesting:"测试用 API 密钥",apiKeyPlaceholder:"在此粘贴您的 API 密钥以测试需要认证的端点...",apiKeyHint:"此密钥将作为 X-API-Key 请求头随请求发送。",deleteApiKeyTitle:"删除 API 密钥",deleteApiKeyMessage:"确定要删除此 API 密钥吗?使用此密钥的所有集成将停止工作。",deleteKey:"删除密钥",amsDisplayThresholds:"AMS 显示阈值",amsThresholdsDescription:"配置 AMS 湿度和温度指示器的颜色阈值。",humidity:"湿度",goodGreen:"良好(绿色)",fairOrange:"一般(橙色)",aboveFairBad:"超过一般阈值显示为红色(差)",fairAlsoDryingThreshold:"此阈值也用于触发自动干燥",temperature:"温度",goodBlue:"良好(蓝色)",aboveFairHot:"超过一般阈值显示为红色(热)",historyRetention:"历史保留",keepSensorHistory:"保留传感器历史",historyRetentionDescription:"较旧的湿度和温度数据将被自动删除",defaultPrintOptions:"默认打印选项",defaultPrintOptionsDescription:"设置新打印的默认选项值。可在打印对话框中逐次覆盖。",defaultBedLevelling:"热床调平",defaultBedLevellingDesc:"打印前自动调平热床",defaultFlowCali:"流量校准",defaultFlowCaliDesc:"校准挤出流量",defaultVibrationCali:"振动校准",defaultVibrationCaliDesc:"减少振纹伪影",defaultLayerInspect:"首层检测",defaultLayerInspectDesc:"AI首层检测",defaultTimelapse:"延时摄影",defaultTimelapseDesc:"录制延时摄影视频",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"热床清空确认",requirePlateClear:"需要热床清空确认",requirePlateClearDescription:"启用后,调度器会在已完成打印的打印机上启动排队打印之前,等待每台打印机的热床清空确认。对于物理验证热床的农场工作流,请禁用此选项。",gcodeInjection:"G-code注入",gcodeInjectionDescription:'为Farmloop、SwapMod、AutoClear和Printflow 3D等自动打印系统配置自定义G-code,在打印开始和/或结束时注入。代码片段按打印机型号配置,在队列项目上启用"注入G-code"时应用。',gcodeInjectionNoPrinters:"未找到打印机。添加打印机以配置G-code代码片段。",gcodeStartLabel:"开始G-code",gcodeEndLabel:"结束G-code",gcodeStartPlaceholder:"在打印开始前插入的G-code...",gcodeEndPlaceholder:"在打印结束后追加的G-code...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"自动干燥",queueDryingDescription:"在队列打印之间,打印机空闲时自动干燥AMS耗材。使用上方的湿度阈值触发干燥。",queueDryingEnabled:"启用自动干燥",queueDryingEnabledDescription:"当打印机空闲且湿度超过阈值时,自动启动AMS干燥",queueDryingBlock:"等待干燥完成",queueDryingBlockDescription:"阻止打印队列直到干燥完成。关闭时,打印优先于干燥。",ambientDryingEnabled:"环境干燥",ambientDryingEnabledDescription:"当空闲打印机的湿度超过阈值时自动干燥耗材,无需排队打印。",dryingPresets:"干燥预设",dryingPresetsDescription:"每种耗材类型的温度和时长。AMS 2 Pro使用较低温度,AMS-HT支持较高温度。",dryingFilament:"耗材",printModal:"打印对话框",expandCustomMapping:"默认展开自定义映射",expandCustomMappingDescription:"打印到多台打印机时,默认展开显示每台打印机的 AMS 映射",authentication:"身份验证",authEnabledDescription:"您的实例已通过用户身份验证保护",authDisabledDescription:"启用以要求登录并管理用户访问",authDisabledMessage:"启用身份验证以创建用户账户、管理权限并保护您的 Bambuddy 实例。",enableAuthentication:"启用身份验证",currentUser:"当前用户",changePassword:"修改密码",admin:"管理员",users:"用户",addUser:"添加用户",groups:"组",addGroup:"添加组",system:"系统",noDescription:"无描述",userCount:"{{count}} 个用户",permissionCount:"{{count}} 个权限",createUser:"创建用户",username:"用户名",enterUsername:"输入用户名",password:"密码",enterPassword:"输入密码(至少 6 个字符)",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认密码",viewReleaseOnGitHub:"在 GitHub 上查看发布",turnAllPlugsOn:"开启所有插座",turnAllPlugsOff:"关闭所有插座",clearNotificationLogs:"清除通知日志",clearLogsMessage:"这将永久删除所有 30 天前的通知日志。此操作无法撤销。",clearLogs:"清除日志",resetUiPreferences:"重置 UI 偏好",resetUiPreferencesMessage:"这将重置所有 UI 偏好为默认值:侧边栏顺序、主题、仪表板布局、视图模式和排序偏好。您的打印机、归档和服务器设置不会受到影响。清除后页面将重新加载。",resetPreferences:"重置偏好",deleteGroupTitle:"删除组",deleteGroupMessage:"确定要删除此组吗?此组中的用户将失去这些权限。",deleteGroup:"删除组",disableAuthenticationTitle:"禁用身份验证",disableAuthenticationMessage:"确定要禁用身份验证吗?这将使您的 Bambuddy 实例无需登录即可访问。所有用户将保留在数据库中但身份验证将被禁用。",disableAuthentication:"禁用身份验证",configureBambuddy:"配置 Bambuddy",systemDefault:"系统默认",archiveSettings:"归档设置",newWindow:"新窗口",embeddedOverlay:"嵌入式叠加层",preferredSlicer:"首选切片软件",preferredSlicerDescription:"选择要用于打开文件的切片软件",externalCameras:"外部摄像头",costTracking:"成本追踪",printsOnly:"仅打印",totalConsumption:"总消耗",dataManagement:"数据管理",storageUsage:"存储使用情况",storageUsageDescription:"按类别的数据使用情况明细",storageUsageTotal:"总计",storageUsageErrors:"错误",storageUsageOtherBreakdown:"其他(包括静态资源、脚本和配置文件)",storageUsageSystem:"系统",storageUsageData:"数据",storageUsageUnavailable:"存储使用信息不可用",clearNotificationLogsDescription:"删除 30 天前的通知日志",resetUiPreferencesDescription:"重置侧边栏顺序、主题、视图模式和布局偏好。打印机、归档和设置不受影响。",enableHomeAssistant:"启用 Home Assistant",enableMqtt:"启用 MQTT",useTls:"使用 TLS",enableMetricsEndpoint:"启用指标端点",availableMetrics:"可用指标",editUser:"编辑用户",deleteUserTitle:"删除用户",groupName:"组名称",leaveEmptyForAnonymous:"留空为匿名",leaveEmptyForNoAuth:"留空为无认证",enterNewPassword:"输入新密码",confirmNewPassword:"确认新密码",enterGroupName:"输入组名称",enterDescriptionOptional:"输入描述(可选)",enterCurrentPassword:"输入当前密码",enterNewPasswordMin6:"输入新密码(至少 6 个字符)",toast:{keyCopied:"密钥已复制到剪贴板",copyFailed:"复制密钥失败",keyAddedToBrowser:"密钥已添加到 API 浏览器",clearLogsFailed:"清除日志失败",uiPreferencesReset:"UI 偏好已重置。刷新中...",authDisabled:"身份验证已成功禁用",authDisableFailed:"禁用身份验证失败",apiKeyCreated:"API 密钥已创建",apiKeyDeleted:"API 密钥已删除",userCreated:"用户创建成功",userUpdated:"用户更新成功",userDeleted:"用户删除成功",groupCreated:"组创建成功",groupUpdated:"组更新成功",groupDeleted:"组删除成功",fillRequiredFields:"请填写所有必填字段",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符",enterGroupName:"请输入组名称",settingsSaved:"设置已保存",cameraSettingsSaved:"摄像头设置已保存",enterCameraUrl:"请输入摄像头 URL",passwordChanged:"密码修改成功",connectionFailed:"连接失败",testFailed:"测试失败",cameraConnected:"摄像头已连接{{resolution}}"},testConnection:"测试连接",catalog:{spoolCatalog:"耗材目录",spoolCatalogDescription:"按品牌/类型的空耗材重量。用于添加耗材时的自动重量查找。",searchCatalog:"搜索目录...",addNewEntry:"添加新条目",namePlaceholder:"名称(例如:Bambu Lab - 塑料)",weight:"重量",type:"类型",default:"默认",custom:"自定义",noMatch:"没有条目匹配您的搜索",empty:"目录中没有条目",deleteEntry:"删除条目",deleteConfirm:'确定要删除"{{name}}"吗?',resetCatalog:"重置目录",resetConfirm:"重置目录为默认值?这将移除所有自定义条目。",loadFailed:"加载耗材目录失败",nameWeightRequired:"名称和重量为必填项",entryAdded:"条目已添加",addFailed:"添加条目失败",entryUpdated:"条目已更新",updateFailed:"更新条目失败",entryDeleted:"条目已删除",deleteFailed:"删除条目失败",resetSuccess:"目录已重置为默认值",resetFailed:"重置目录失败",exported:"已导出 {{count}} 条",imported:"已导入 {{added}} 条(跳过 {{skipped}} 条)",importFailed:"导入失败:无效的 JSON 格式",exportTooltip:"导出目录为 JSON",importTooltip:"从 JSON 导入目录",resetTooltip:"重置为默认值",selectedCount:"已选择 {{count}} 项",deleteSelected:"删除所选",bulkDeleteConfirm:"确定要删除 {{count}} 个条目吗?",bulkDeleted:"已删除 {{count}} 个条目",bulkDeleteFailed:"删除条目失败"},colorCatalog:{title:"颜色目录",description:"按制造商/材料的耗材颜色。用于添加耗材时的自动颜色查找。",searchColors:"搜索颜色...",allManufacturers:"所有制造商",addNewColor:"添加新颜色",manufacturer:"制造商",colorName:"颜色名称",hex:"十六进制",materialOptional:"材料(可选)",showing:"显示 {{filtered}} / {{total}} 种颜色",noMatch:"没有颜色匹配您的搜索",empty:"目录中没有颜色",deleteColor:"删除颜色",deleteConfirm:'确定要删除"{{name}}"吗?',resetCatalog:"重置颜色目录",resetConfirm:"重置目录为默认值?这将移除所有自定义颜色。",sync:"同步",starting:"启动中...",syncTooltip:"从 FilamentColors.xyz 同步(2000+ 种颜色,可能需要一分钟)",loadFailed:"加载颜色目录失败",fieldsRequired:"制造商、颜色名称和十六进制颜色为必填项",colorAdded:"颜色已添加",addFailed:"添加颜色失败",colorUpdated:"颜色已更新",updateFailed:"更新颜色失败",colorDeleted:"颜色已删除",deleteFailed:"删除颜色失败",resetSuccess:"颜色目录已重置为默认值",resetFailed:"重置目录失败",syncUpToDate:"已是最新(检查了 {{count}} 种颜色)",syncComplete:"添加了 {{added}} 种新颜色({{skipped}} 种已存在)",syncError:"同步错误",syncFailed:"从 FilamentColors.xyz 同步失败",exported:"已导出 {{count}} 种颜色",imported:"已导入 {{added}} 种颜色(跳过 {{skipped}} 种)",importFailed:"导入失败:无效的 JSON 格式",selectedCount:"已选择 {{count}} 项",deleteSelected:"删除所选",bulkDeleteConfirm:"确定要删除 {{count}} 种颜色吗?",bulkDeleted:"已删除 {{count}} 种颜色",bulkDeleteFailed:"删除颜色失败"},dateFormat:"日期格式",dateFormatUs:"美式 (MM/DD/YYYY)",dateFormatEu:"欧式 (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"时间格式",timeFormat12:"12小时制 (3:30 PM)",timeFormat24:"24小时制 (15:30)",defaultPrinter:"默认打印机",defaultPrinterDescription:"为上传、重印和其他操作预选此打印机。",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"拖拽侧边栏项目以重新排序。在此处重置为默认顺序。",setDefault:"设为默认",sidebarOrderSetDefaultHint:"设为默认将当前菜单顺序应用于尚未自定义的用户。",sidebarDefaultSet:"已设置默认菜单顺序。",sidebarDefaultCleared:"已清除默认菜单顺序。",sidebarDefaultFailed:"设置默认菜单顺序失败。",reset:"重置",darkMode:"深色模式",lightMode:"浅色模式",active:"(当前)",background:"背景",accent:"强调色",style:"样式",bgNeutral:"中性",bgWarm:"暖色",bgCool:"冷色",bgOled:"OLED 纯黑",bgSlate:"石板蓝",bgForest:"森林绿",accentGreen:"绿色",accentTeal:"青色",accentBlue:"蓝色",accentOrange:"橙色",accentPurple:"紫色",accentRed:"红色",styleClassic:"经典",styleGlow:"发光",styleVibrant:"鲜艳",themeToggleHint:"使用侧边栏中的太阳/月亮图标在深色和浅色模式之间切换。",autoArchivePrints:"自动归档打印",autoArchiveDescription:"打印完成时自动保存3MF文件",saveThumbnailsDescription:"从3MF文件中提取并保存预览图像",captureFinishPhotoDescription:"打印完成时从打印机摄像头拍照",ffmpegNotInstalled:"未安装ffmpeg",ffmpegRequired:"摄像头捕获需要ffmpeg。通过 <brew>brew install ffmpeg</brew>(macOS)或 <apt>apt install ffmpeg</apt>(Linux)安装。",camera:"摄像头",cameraViewMode:"摄像头查看模式",cameraOverlayDescription:"摄像头在主屏幕上以可调大小的覆盖层打开",cameraWindowDescription:"摄像头在单独的浏览器窗口中打开",externalCamerasDescription:"配置外部摄像头以替换内置打印机摄像头。支持MJPEG流、RTSP、HTTP快照和USB摄像头(V4L2)。启用后,外部摄像头将用于实时查看和完成照片。",cameraPlaceholderUsb:"设备路径 (/dev/video0)",cameraPlaceholderUrl:"摄像头URL (rtsp://... 或 http://...)",cameraTypeMjpeg:"MJPEG 流",cameraTypeRtsp:"RTSP 流",cameraTypeSnapshot:"HTTP 快照",cameraTypeUsb:"USB 摄像头 (V4L2)",cameraRotation:"旋转",test:"测试",connected:"已连接",disconnected:"未连接",currency:"货币",defaultFilamentCost:"默认耗材成本(每公斤)",electricityCost:"每千瓦时电费",energyDisplayMode:"能源显示模式",energyModePrintDescription:"仪表板显示打印期间使用的能源总和",energyModeTotalDescription:"仪表板显示智能插座的累计能源",fileManager:"文件管理器",createArchiveEntry:"打印时创建归档条目",createArchiveEntryDescription:"从文件管理器打印时,可选择创建归档条目",lowDiskSpaceWarning:"磁盘空间不足警告",lowDiskSpaceDescription:"当可用磁盘空间低于此阈值时显示警告",printerFirmware:"打印机固件",checkFirmwareDescription:"检查Bambu Lab的打印机固件更新",bambuddySoftware:"Bambuddy 软件",autoCheckDescription:"启动时自动检查新版本",checkNow:"立即检查",updateAvailableVersion:"可用更新:v{{version}}",releaseNotes:"发布说明",updateViaDocker:"通过 Docker Compose 更新:",installUpdate:"安装更新",latestVersionRunning:"您正在运行最新版本",failedToCheckUpdates:"检查更新失败:{{error}}",backupRestore:"备份与恢复",backupRestoreDescription:"导出/导入设置并配置GitHub备份",goToBackup:"前往备份",externalUrl:"外部URL",externalUrlDescription:"Bambuddy可访问的外部URL。用于通知图像和外部集成。",bambuddyUrl:"Bambuddy URL",externalUrlHint:"包含协议和端口(例如:http://192.168.1.100:8000)",ftpRetry:"FTP重试",ftpRetryDescription:"当打印机WiFi不稳定时重试FTP操作。适用于3MF下载、打印上传、延时摄影下载和固件更新。",autoRetryDescription:"自动重试失败的FTP操作",retryAttempts:"重试次数",retryDelay:"重试延迟",connectionTimeout:"连接超时",time_one:"{{count}}次",time_other:"{{count}}次",second_one:"{{count}}秒",second_other:"{{count}}秒",nSeconds:"{{count}}秒",increaseForWeakWifi:"对WiFi信号弱的打印机增加此值",homeAssistant:"Home Assistant",homeAssistantFullDescription:"连接到Home Assistant,通过HA REST API控制智能插座。支持switch、light、input_boolean和script实体。",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"长期访问令牌",haTokenHint:"在HA中创建令牌:个人资料 → 长期访问令牌 → 创建令牌",connectionSuccessful:"连接成功",connectionFailed:"连接失败",haConnectionSuccess:"已成功连接到Home Assistant。",haConnectionFailed:"连接Home Assistant失败。",mqttPublishing:"MQTT发布",mqttDescription:"将BamBuddy事件发布到外部MQTT代理,用于与Node-RED、Home Assistant和其他自动化系统集成。",mqttEnableDescription:"向外部MQTT代理发布事件",brokerHostname:"代理主机名",port:"端口",usernameOptional:"用户名(可选)",passwordOptional:"密码(可选)",topicPrefix:"主题前缀",topicPrefixHint:"主题格式:{{prefix}}/printers/<serial>/status 等",prometheusMetrics:"Prometheus 指标",prometheusEndpointDescription:"在 <code>/api/v1/metrics</code> 公开打印机指标,用于Prometheus/Grafana监控。",bearerTokenOptional:"Bearer令牌(可选)",bearerTokenHint:"设置后,请求必须包含 <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"连接状态",metricsPrinterState:"打印机状态(空闲/打印中等)",metricsPrintProgress:"打印进度 0-100%",metricsBedTemp:"热床温度",metricsNozzleTemp:"喷嘴温度",metricsPrintsTotal:"按结果分类的总打印数",metricsMore:"...以及更多(层数、风扇、队列、耗材用量)",smartPlugsDescription:"连接智能插座(Tasmota或Home Assistant)以自动化电源控制并跟踪打印机的能源使用情况。",allOn:"全部开启",allOff:"全部关闭",addSmartPlug:"添加智能插座",energySummary:"能源概要",currentPower:"当前功率",plugsOnline:"{{reachable}}/{{total}} 个插座在线",today:"今天",yesterday:"昨天",total:"总计",enablePlugsForSummary:"启用插座以查看能源概要",addNotificationProvider:"添加",systemBadge:"(系统)",creating:"创建中...",changing:"修改中...",deleteUserAndItems:"删除用户及其所有项目",deleteUserKeepItems:"删除用户,保留项目(将变为无主项目)",ok:"确定"},notification:{printStarted:{title:"打印已开始",body:"{{printer}}:{{filename}} 已开始打印"},printCompleted:{title:"打印已完成",body:"{{printer}}:{{filename}} 已成功完成"},printFailed:{title:"打印失败",body:"{{printer}}:{{filename}} 打印失败"},printStopped:{title:"打印已停止",body:"{{printer}}:{{filename}} 已停止"},printProgress:{title:"打印进度",body:"{{printer}}:{{filename}} 已完成 {{percent}}%"},printerOffline:{title:"打印机离线",body:"{{printer}} 已离线"},printerError:{title:"打印机错误",body:"{{printer}}:{{error}}"},filamentLow:{title:"耗材不足",body:"{{printer}}:耗材即将用完"},maintenanceDue:{title:"维护到期",body:"{{printer}}:{{items}} 需要关注"}},errors:{generic:"出了点问题",networkError:"网络错误。请检查您的连接。",notFound:"未找到",unauthorized:"未授权",serverError:"服务器错误",validationError:"请检查您的输入",printerConnectionFailed:"连接打印机失败",saveFailed:"保存更改失败",deleteFailed:"删除失败",loadFailed:"加载数据失败"},hmsErrors:{title:"错误 - {{name}}",noErrors:"无错误",viewOnWiki:"在拓竹 Wiki 上查看",clearInstructions:"在打印机上清除错误以在此处消除它们。",clearErrors:"清除错误",clearSuccess:"HMS 错误已清除",clearFailed:"清除 HMS 错误失败"},mqttDebug:{title:"MQTT 调试日志",searchPlaceholder:"搜索主题或负载...",noMessages:"尚未记录消息",startLoggingHint:'点击"开始记录"以开始捕获 MQTT 消息',noMessagesMatch:"没有消息匹配您的筛选条件",adjustFilterHint:"尝试调整您的搜索或筛选条件",incoming:"传入",outgoing:"传出",loggingStopped:"记录已停止",loggingActive:"记录中 - 消息将自动刷新",startLogging:"开始记录",stopLogging:"停止记录",clearLog:"清除日志",topic:"主题",timestamp:"时间戳",direction:"方向",all:"全部"},printerFiles:{title:"文件管理器",storageUsed:"已用:",storageFree:"剩余:",filterPlaceholder:"筛选文件...",deleteButton:"删除",deleteFiles:"删除 {{count}} 个文件",deleteFileConfirm:'删除"{{name}}"?此操作无法撤销。',deleteFilesConfirm:"删除 {{count}} 个选中的文件?此操作无法撤销。",noFiles:"打印机上没有文件",loadingFiles:"加载文件中...",failedToLoad:"加载文件失败",toast:{filesDeleted:"已删除 {{count}} 个文件",deleteFailed:"删除失败:{{error}}"}},confirm:{delete:"确定要删除吗?",unsavedChanges:"您有未保存的更改。确定要离开吗?",clearQueue:"确定要清空队列吗?"},login:{title:"Bambuddy 登录",subtitle:"登录您的账户",username:"用户名",usernamePlaceholder:"输入您的用户名",usernameOrEmail:"用户名或邮箱",usernameOrEmailPlaceholder:"用户名或 @ 邮箱",password:"密码",passwordPlaceholder:"输入您的密码",signIn:"登录",signingIn:"登录中...",forgotPassword:"忘记密码?",loginSuccess:"登录成功",loginFailed:"登录失败",enterCredentials:"请输入用户名和密码",forgotPasswordTitle:"忘记密码",forgotPasswordMessage:"如果您忘记了密码,请联系系统管理员进行重置。",forgotPasswordEmailMessage:"输入您的邮箱地址,我们将向您发送新密码。",emailAddress:"邮箱地址",emailPlaceholder:"your.email@example.com",cancel:"取消",sending:"发送中...",sendResetEmail:"发送重置邮件",howToReset:"如何重置密码:",resetStep1:"联系您的 Bambuddy 管理员",resetStep2:"请他们在用户管理中重置您的密码",resetStep3:"他们可以为您设置一个临时密码",resetStep4:"使用新密码登录并在设置中修改密码",gotIt:"知道了"},setup:{title:"Bambuddy 设置",subtitle:"为您的 Bambuddy 实例配置身份验证",enableAuth:"启用身份验证",adminAccount:"管理员账户",adminAccountDesc:"如果管理员用户已存在,将使用现有管理员账户启用身份验证。如需使用现有管理员,请将下方字段留空,或输入新凭据创建新管理员用户。",adminUsername:"管理员用户名",adminPassword:"管理员密码",optionalIfAdminExists:"(如管理员用户已存在则为可选)",adminUsernamePlaceholder:"输入管理员用户名(可选)",adminPasswordPlaceholder:"输入管理员密码(可选)",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认管理员密码",settingUp:"设置中...",completeSetup:"完成设置",toast:{authEnabledAdminCreated:"身份验证已启用并创建了管理员用户",authEnabledExistingAdmins:"使用现有管理员用户启用了身份验证",setupCompleted:"设置完成",enterBothCredentials:"请输入管理员用户名和密码,或将两者留空以使用现有管理员用户",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符"}},changePassword:{title:"修改密码",currentPassword:"当前密码",currentPasswordPlaceholder:"输入当前密码",newPassword:"新密码",newPasswordPlaceholder:"输入新密码(至少 6 个字符)",confirmPassword:"确认新密码",confirmPasswordPlaceholder:"确认新密码",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符",changing:"修改中...",success:"密码修改成功",failed:"密码修改失败"},plateAlert:{title:"打印已暂停!",message:"在构建板上检测到物体。打印已自动暂停。请清理打印板并继续打印。",understand:"我知道了"},camera:{title:"摄像头视图",invalidPrinterId:"无效的打印机 ID",live:"实时",snapshot:"快照",restartStream:"重启流",refreshSnapshot:"刷新快照",fullscreen:"全屏",exitFullscreen:"退出全屏",connectingToCamera:"连接摄像头中...",capturingSnapshot:"拍摄快照中...",connectionLost:"连接已断开",connectionFailed:"摄像头连接失败",reconnecting:"{{countdown}} 秒后重新连接...(第 {{attempt}}/{{max}} 次尝试)",reconnectNow:"立即重新连接",cameraUnavailable:"摄像头不可用",cameraUnavailableDesc:"请确保打印机已通电并已连接。",noCamera:"无可用摄像头",retry:"重试",cameraStream:"摄像头流",zoomOut:"缩小",zoomIn:"放大",resetZoom:"重置缩放",recording:"录制中",startRecording:"开始录制",stopRecording:"停止录制",chamberLight:"切换腔室灯"},groups:{title:"组管理",subtitle:"管理访问控制的权限组",backToSettings:"返回设置",createGroup:"创建组",noPermission:"您没有访问此页面的权限。",system:"系统",noDescription:"无描述",usersCount:"{{count}} 个用户",permissionsCount:"{{count}} 个权限",edit:"编辑",delete:"删除",toast:{created:"组创建成功",updated:"组更新成功",deleted:"组删除成功",enterGroupName:"请输入组名称"},modal:{editGroup:"编辑组",createGroup:"创建组",cancel:"取消",saving:"保存中...",creating:"创建中...",saveChanges:"保存更改"},form:{groupName:"组名称",groupNamePlaceholder:"输入组名称",systemGroupWarning:"系统组名称不可更改",description:"描述",descriptionPlaceholder:"输入描述(可选)",permissions:"权限(已选 {{count}} 个)"},deleteModal:{title:"删除组",message:"确定要删除此组吗?此组中的用户将失去这些权限。",confirm:"删除组"},editor:{title:"编辑组",createTitle:"创建组",search:"搜索权限...",selectAll:"全选",clearAll:"清除全部",permissionsSelected:"已选 {{count}} 个",noResults:"没有权限匹配您的搜索"}},users:{title:"用户管理",subtitle:"管理用户及其对 Bambuddy 实例的访问",backToSettings:"返回设置",createUser:"创建用户",noPermission:"您没有访问此页面的权限。",admin:"管理员",noGroups:"无组",active:"活跃",inactive:"非活跃",edit:"编辑",delete:"删除",system:"系统",noGroupsAvailable:"无可用组",table:{username:"用户名",groups:"组",status:"状态",actions:"操作"},toast:{created:"用户创建成功",updated:"用户更新成功",deleted:"用户删除成功",fillRequired:"请填写所有必填字段",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符"},modal:{createUser:"创建用户",editUser:"编辑用户",cancel:"取消",creating:"创建中...",saving:"保存中...",saveChanges:"保存更改",advancedAuthSubtitle:"使用高级认证"},form:{username:"用户名",usernamePlaceholder:"输入用户名",email:"邮箱",emailPlaceholder:"user@example.com",password:"密码",passwordPlaceholder:"输入密码",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认密码",newPasswordPlaceholder:"输入新密码",confirmNewPasswordPlaceholder:"确认新密码",leaveBlankToKeep:"留空以保持当前值",groups:"组",optional:"可选",autoGeneratedPassword:"将自动生成安全密码并通过邮件发送给用户。",passwordManagedByAdvancedAuth:'密码由高级认证管理。使用"重置密码"通过邮件向用户发送新密码。',resetPassword:"重置密码",resettingPassword:"重置密码中..."},deleteModal:{title:"删除用户",message:"确定要删除此用户吗?此操作无法撤销。",confirm:"删除用户"}},streamOverlay:{title:"流叠加层",invalidPrinterId:"无效的打印机 ID",cameraStream:"摄像头流",progress:"进度",eta:"预计完成时间",printerIdle:"打印机空闲",printerOffline:"打印机离线",status:{printing:"打印中",paused:"已暂停",finished:"已完成",failed:"失败",idle:"空闲",unknown:"未知"}},profiles:{title:"配置文件",subtitle:"管理您的切片预设和压力推进校准",tabs:{cloud:"云端配置文件",local:"本地配置文件",kprofiles:"K 值配置"},localProfiles:{title:"本地配置文件",subtitle:"从 OrcaSlicer 导入和管理切片预设",import:"导入配置文件",importDesc:"将 .bbscfg、.bbsflmt、.orca_filament、.zip 或 .json 文件拖放到此处",importing:"导入中...",search:"搜索本地预设...",noPresets:"暂无本地预设",badge:"本地",edit:"编辑",delete:"删除",cancel:"取消",deleteConfirmTitle:"删除预设",deleteConfirm:"确定要删除此预设吗?此操作无法撤销。",source:"来源",inheritsFrom:"继承自",filamentType:"类型",vendor:"厂商",compatiblePrinters:"兼容打印机",nozzleTemp:"喷嘴温度",cost:"成本",density:"密度",pressureAdvance:"压力推进",filament:"耗材",process:"工艺",printer:"打印机",toast:{importSuccess:"已导入 {{count}} 个预设",importSkipped:"跳过 {{count}} 个预设(重复)",importError:"导入时出现 {{count}} 个错误",deleted:"预设已删除",updated:"预设已更新"}},connectedAs:"已连接为",logout:"退出登录",noLogoutPermission:"您没有退出登录的权限",failedToLoad:"加载配置文件失败",retry:"重试",time:{justNow:"刚刚",minsAgo:"{{count}} 分钟前",hoursAgo:"{{count}} 小时前",daysAgo:"{{count}} 天前"},toast:{loggedOut:"已退出登录"},login:{title:"连接到拓竹云",subtitle:"跨设备同步您的切片预设",email:"邮箱",password:"密码",region:"地区",regionGlobal:"全球",regionChina:"中国",verificationCode:"验证码",totpCode:"验证器代码",checkEmail:"检查您的邮箱 ({{email}}) 获取 6 位验证码",enterTotpHint:"输入验证器应用中的 6 位代码",accessToken:"访问令牌",accessTokenHint:"粘贴您的拓竹访问令牌(来自 Bambu Studio)",back:"返回",loginButton:"登录",verifyButton:"验证",setTokenButton:"设置令牌",useToken:"改用访问令牌",useEmail:"改用邮箱登录",toast:{loggedIn:"登录成功",codeSent:"验证码已发送到您的邮箱",enterTotp:"输入验证器应用中的代码",tokenSet:"令牌设置成功"}},presets:{myPreset:"我的预设(可编辑)",duplicate:"复制",editable:"可编辑",failedToLoadDetails:"加载预设详情失败",deleteConfirm:"删除此预设?",deleteWarning:'这将从拓竹云中永久删除"{{name}}"。此操作无法撤销。',noDuplicatePermission:"您没有复制预设的权限",noEditPermission:"您没有编辑预设的权限",noDeletePermission:"您没有删除预设的权限",types:{filament:"耗材预设",printer:"打印机预设",process:"工艺预设"},toast:{deleted:"预设已删除",created:"预设已创建",updated:"预设已更新",duplicated:"预设已复制",fieldAdded:'字段"{{key}}"已添加',exported:"预设已导出"},baseLabel:"基础:{{name}}",currentLabel:"当前:{{name}}",newPreset:"新建预设",editPreset:"编辑预设",duplicatePreset:"复制预设",createNewPreset:"创建新预设",customizeSettings:"自定义新预设的设置",compareWithBase:"与基础预设比较",compare:"比较",basePreset:"基础预设",selectBasePreset:"选择基础预设...",presetName:"预设名称",myCustomPreset:"我的自定义预设",inheritsFrom:"继承自",dropJsonToImport:"拖放 JSON 以导入",tabs:{common:"常用",allFields:"所有字段"},availableFields:"可用字段",searchFieldsPlaceholder:"搜索字段...",noMatchingFields:"没有匹配的字段",allFieldsAdded:"所有字段已添加",addCustomField:"添加自定义字段",yourOverrides:"您的覆盖值",noOverridesYet:"暂无覆盖值",clickFieldsToAdd:"点击左侧的字段进行添加",saveAsTemplate:"保存为模板",jsonTip:"提示:将 .json 文件拖放到此对话框的任意位置以导入设置"},cloudView:{searchPlaceholder:"搜索预设...",templates:"模板",refresh:"刷新",newPreset:"新建预设",clearFilters:"清除筛选",compareMode:"比较模式",selectAnotherPreset:"选择另一个 {{type}} 预设",clickTwoPresets:"点击两个相同类型的预设进行比较",selectFirst:"1. 选择第一个",selectSecond:"2. 选择第二个",compareNow:"立即比较",lastSynced:"上次同步:",showingCount:"显示 {{showing}} / {{total}} 个预设",noPresetsFound:"未找到预设",columns:{filament:"耗材",process:"工艺",printer:"打印机"},noFilamentPresets:"无耗材预设",noProcessPresets:"无工艺预设",noPrinterPresets:"无打印机预设",filters:{type:"类型",owner:"所有者",printer:"打印机",nozzle:"喷嘴",filament:"耗材",layer:"层",all:"全部",myPresets:"我的预设",builtIn:"内置",process:"工艺"},noTemplatesPermission:"您没有管理模板的权限",noRefreshPermission:"您没有刷新配置文件的权限",noCreatePermission:"您没有创建预设的权限"},templates:{title:"快速模板",noTemplates:"暂无模板",createFirst:"从预设编辑器创建模板",typeFilter:"类型:",deleteTitle:"删除模板",deleteWarning:"此操作无法撤销",deleteConfirm:'确定要删除"{{name}}"吗?',namePlaceholder:"模板名称",descriptionPlaceholder:"描述",settingsJson:"设置 (JSON)",fieldsCount:"{{count}} 个字段",shownInModals:"在对话框中显示",hiddenInModals:"在对话框中隐藏",apply:"应用",toast:{deleted:"模板已删除",updated:"模板已更新",created:"模板已创建",applied:"模板已应用"}}},support:{debugLoggingActive:"调试日志记录已激活",manageLogs:"管理",collectItem7:"打印机连接和固件版本",collectItem8:"集成状态(Spoolman、MQTT、HA)",collectItem9:"网络接口(仅子网)",collectItem10:"Python 包版本",collectItem11:"数据库健康检查",collectItem12:"Docker 环境详情"},fileManager:{title:"文件管理器",subtitle:"组织和管理您的打印文件",uploadFiles:"上传文件",newFolder:"新建文件夹",folderName:"文件夹名称",folderNamePlaceholder:"例如:功能零件",renameFile:"重命名文件",renameFolder:"重命名文件夹",moveFiles:"移动 {{count}} 个文件",rootNoFolder:"根目录(无文件夹)",current:"当前",linkFolder:"链接文件夹",linkFolderDescription:'将"{{name}}"链接到项目或归档以便快速访问。',project:"项目",archive:"归档",noProjectsFound:"未找到项目",noArchivesFound:"未找到归档",unlink:"取消链接",link:"链接",dragDropFiles:"将文件拖放到此处",dropFilesHere:"将文件放在此处",orClickToBrowse:"或点击浏览",allFileTypesSupported:"支持所有文件类型。ZIP 文件将被解压。",zipFilesDetected:"检测到 ZIP 文件",zipExtractOptions:"ZIP 文件将被解压。选择如何处理文件夹结构:",preserveZipStructure:"保留 ZIP 中的文件夹结构",createFolderFromZip:"从 ZIP 文件名创建文件夹",stlThumbnailGeneration:"STL 缩略图生成",zipMayContainStl:"ZIP 文件可能包含 STL 文件。可以在解压时生成缩略图。",thumbnailsCanBeGenerated:"可以为 STL 文件生成缩略图。大型模型可能需要更长时间处理。",generateThumbnailsForStl:"为 STL 文件生成缩略图",threemfDetected:"检测到 3MF 文件",threemfExtractionInfo:"将自动从 3MF 文件中提取打印机型号、材料、颜色和打印设置。",willBeExtracted:"将被解压",filesExtracted:"已解压 {{count}} 个文件",uploadComplete:"上传完成:{{succeeded}} 个成功",uploadFailed:"{{count}} 个失败",zipFilesFailed:"{{count}} 个文件失败",uploading:"上传中...",changeLink:"更改链接...",linkTo:"链接到...",linkToProjectOrArchive:"链接到项目或归档",addToQueue:"添加到队列",schedulePrint:"排程",generateThumbnail:"生成缩略图",generateThumbnails:"生成缩略图",generateThumbnailsForMissing:"为缺少缩略图的 STL 文件生成缩略图",gridView:"网格视图",listView:"列表视图",lowDiskSpaceWarning:"磁盘空间不足警告",lowDiskSpaceDetails:"仅剩 {{free}}(总共 {{total}})。阈值设置为 {{threshold}} GB。",files:"文件",folders:"文件夹",size:"大小",free:"剩余",allFiles:"所有文件",wrap:"换行",enableTextWrapping:"启用文本换行",disableTextWrapping:"禁用文本换行",dragToResizeTooltip:"拖动调整大小,双击重置",searchFiles:"搜索文件...",allTypes:"所有类型",prints:"打印",ascending:"升序",descending:"降序",resultsCount:"{{showing}} / {{total}} 个文件",selectAll:"全选",deselectAll:"取消全选",selected:"已选择 {{count}} 个",adding:"添加中...",loadingFiles:"加载文件中...",folderIsEmpty:"文件夹为空",noFilesYet:"暂无文件",folderEmptyDescription:"上传文件或将文件移入此文件夹以开始使用。",noFilesDescription:"上传文件以开始组织您的打印相关文件。",noMatchingFiles:"没有匹配的文件",noMatchingFilesDescription:"没有文件匹配您当前的搜索或筛选条件。",clearFilters:"清除筛选",printedCount:"已打印 {{count}} 次",uploadedBy:"上传者",deleteFolder:"删除文件夹",deleteFile:"删除文件",deleteFilesCount:"删除 {{count}} 个文件",deleteFolderConfirm:"确定要删除此文件夹吗?其中的所有文件也将被删除。",deleteFileConfirm:"确定要删除此文件吗?",deleteFilesConfirm:"确定要删除 {{count}} 个选中的文件吗?此操作无法撤销。",deleting:"删除中...",noPermissionRenameFolder:"您没有重命名文件夹的权限",noPermissionLinkFolder:"您没有链接文件夹的权限",noPermissionDeleteFolder:"您没有删除文件夹的权限",noPermissionPrint:"您没有打印的权限",noPermissionAddToQueue:"您没有添加到队列的权限",noPermissionDownload:"您没有下载文件的权限",noPermissionRenameFile:"您没有重命名此文件的权限",noPermissionGenerateThumbnail:"您没有生成缩略图的权限",noPermissionDeleteFile:"您没有删除此文件的权限",noPermissionCreateFolder:"您没有创建文件夹的权限",noPermissionUpload:"您没有上传文件的权限",noPermissionMoveFiles:"您没有移动文件的权限",noPermissionDeleteFiles:"您没有删除文件的权限",linkExternal:"链接外部",linkExternalFolder:"链接外部文件夹",linkExternalFolderDescription:"将主机目录(NAS、USB、网络共享)挂载到文件管理器中。文件不会被复制——直接从原始路径访问。",externalFolderNamePlaceholder:"例如:NAS打印文件",externalPath:"主机路径",externalPathHelp:"Docker主机上目录的绝对路径。必须以绑定挂载方式挂载到容器中。",readOnly:"只读",readOnlyHelp:"防止上传和删除",showHiddenFiles:"显示隐藏文件(点文件)",externalFolder:"外部文件夹",scanFolder:"扫描",toast:{folderCreated:"文件夹已创建",folderDeleted:"文件夹已删除",fileDeleted:"文件已删除",filesDeleted:"已删除 {{count}} 个文件",filesMoved:"文件已移动",folderLinked:"文件夹已链接",folderUnlinked:"文件夹已取消链接",externalFolderLinked:"外部文件夹已链接并扫描",folderScanned:"扫描完成:添加 {{added}} 个,移除 {{removed}} 个",addedToQueue:"已将 {{count}} 个文件添加到队列",addedToQueuePartial:"已添加 {{added}} 个文件,{{failed}} 个失败",failedToAddToQueue:"添加文件失败:{{error}}",fileRenamed:"文件已重命名",folderRenamed:"文件夹已重命名",thumbnailsGenerated:"已生成 {{count}} 个缩略图",thumbnailsGeneratedPartial:"已生成 {{succeeded}} 个缩略图,{{failed}} 个失败",noStlMissingThumbnails:"没有缺少缩略图的 STL 文件",failedToGenerateThumbnails:"生成缩略图失败:{{error}}",thumbnailGenerated:"缩略图已生成",failedToGenerateThumbnail:"生成缩略图失败:{{error}}"}},projects:{title:"项目",subtitle:"组织和跟踪您的 3D 打印项目",newProject:"新建项目",editProject:"编辑项目",deleteProject:"删除项目",projectName:"项目名称",description:"描述",noProjects:"暂无项目",noProjectsFiltered:"没有{{status}}项目",noProjectsFilteredHelp:"您没有任何{{status}}项目。当项目状态更改时,它们将出现在这里。",createFirst:"创建您的第一个项目以开始组织相关打印、跟踪进度和管理构建。",createFirstButton:"创建您的第一个项目",create:"创建",files:"文件",prints:"打印",plates:"板",parts:"零件",lastModified:"最后修改",deleteConfirm:"确定要删除此项目吗?归档和队列项目将被取消链接但不会被删除。",addFiles:"添加文件",removeFile:"移除文件",viewDetails:"查看详情",namePlaceholder:"例如:Voron 2.4 构建",descriptionPlaceholder:"可选描述...",color:"颜色",targetPlates:"目标板数",targetPlatesPlaceholder:"例如:25",targetPlatesHelp:"打印任务数量",targetParts:"目标零件数",targetPartsPlaceholder:"例如:150",targetPartsHelp:"所需零件总数",tagsLabel:"标签(逗号分隔)",tagsPlaceholder:"例如:voron、功能件、礼物",dueDate:"截止日期",priority:"优先级",priorityLow:"低",priorityNormal:"普通",priorityHigh:"高",priorityUrgent:"紧急",statusActive:"进行中",statusCompleted:"已完成",statusArchived:"已归档",done:"完成",completed:"已完成",failed:"失败",inQueue:"队列中",noPrintsYet:"暂无打印",printJobs:"打印任务(板)",partsPrinted:"已打印零件",failedParts:"失败零件",import:"导入",export:"导出",importProject:"导入项目",exportAll:"导出所有项目",loading:"加载项目中...",noEditPermission:"您没有编辑项目的权限",noDeletePermission:"您没有删除项目的权限",noCreatePermission:"您没有创建项目的权限",noImportPermission:"您没有导入项目的权限",noExportPermission:"您没有导出项目的权限",toast:{created:"项目已创建",updated:"项目已更新",deleted:"项目已删除",imported:"项目已导入",multipleImported:"已导入 {{count}} 个项目",importFailed:"导入失败",exported:"项目已导出(仅元数据)"}},projectDetail:{notFound:"未找到项目",backToProjects:"返回项目",export:"导出",exportProject:"导出项目",noExportPermission:"您没有导出项目的权限",noEditPermission:"您没有编辑项目的权限",partOf:"属于:",priorityLabel:"优先级:",noPrints:"此项目暂无打印",status:{active:"进行中",completed:"已完成",archived:"已归档"},priority:{low:"低",normal:"普通",high:"高",urgent:"紧急"},dueDate:{overdue:"已逾期",today:"今天到期",daysLeft:"还有 {{count}} 天"},progress:{platesProgress:"板进度",partsProgress:"零件进度",printJobs:"打印任务",parts:"零件",percentComplete:"{{percent}}% 完成",remaining:"剩余 {{count}} 个"},stats:{printJobs:"打印任务",total:"总计",failed:"{{count}} 个失败",partsPrinted:"已打印 {{count}} 个零件",printTime:"打印时间",filamentUsed:"耗材用量"},cost:{title:"成本追踪",filamentCost:"耗材成本",energy:"能源",totalCost:"总成本",total:"总计",includesBom:"含物料清单",budget:"预算",remaining:"剩余"},subProjects:{title:"子项目 ({{count}})"},notes:{title:"备注",noEditPermission:"您没有编辑备注的权限",placeholder:"添加关于此项目的备注...",empty:"暂无备注。点击编辑添加备注。"},files:{title:"文件",linkFolders:"从文件管理器链接文件夹",forQuickAccess:"到此项目以便快速访问。",fileCount:"{{count}} 个文件",empty:"未链接文件夹。前往文件管理器将文件夹链接到此项目。"},bom:{title:"材料清单",acquired:"已获取 {{completed}}/{{total}}",showAll:"显示全部",hideDone:"隐藏已完成",addPart:"添加零件",noAddPermission:"您没有添加零件的权限",partNamePlaceholder:"零件名称(例如:M3x8 螺丝)",partName:"零件名称",qty:"数量",price:"价格 ({{currency}})",sourcingUrlPlaceholder:"采购链接(可选)",remarksPlaceholder:"备注(可选)",deletePart:"删除零件",deleteConfirm:'确定要删除"{{name}}"吗?',noUpdatePermission:"您没有更新零件的权限",noEditPermission:"您没有编辑零件的权限",noDeletePermission:"您没有删除零件的权限",totalCost:"总成本:",empty:"材料清单中没有零件。添加硬件、电子元件或其他组件以跟踪需要采购的物品。"},timeline:{title:"活动时间线",empty:"暂无活动。"},template:{saveAsTemplate:"保存为模板",noCreatePermission:"您没有创建模板的权限"},queue:{title:"队列",viewAll:"查看全部",printing:"{{count}} 个打印中",queued:"{{count}} 个排队中"},prints:{title:"打印 ({{count}})"},toast:{projectUpdated:"项目已更新",partAdded:"零件已添加",partRemoved:"零件已移除",exportFailed:"导出失败",projectExported:"项目已导出",templateCreated:"模板已创建"}},system:{title:"系统信息",version:"版本",uptime:"运行时间",cpuUsage:"CPU 使用率",memoryUsage:"内存使用率",diskUsage:"磁盘使用率",networkInfo:"网络信息",logs:"日志",debugMode:"调试模式",enableDebug:"启用调试日志",disableDebug:"禁用调试日志",downloadLogs:"下载日志",clearLogs:"清除日志",dockerInfo:"Docker 信息",containerName:"容器名称",imageName:"镜像名称",platform:"平台",architecture:"架构"},library:{title:"耗材库",addFilament:"添加耗材",editFilament:"编辑耗材",deleteFilament:"删除耗材",vendor:"厂商",material:"材料",color:"颜色",kFactor:"K 值",temperature:"温度",noFilaments:"耗材库中没有耗材",deleteConfirm:"确定要删除此耗材吗?",importFromPrinter:"从打印机导入",exportToFile:"导出到文件"},spoolman:{title:"Spoolman 集成",enabled:"Spoolman 已启用",url:"Spoolman URL",connected:"已连接",disconnected:"未连接",testConnection:"测试连接",sync:"同步",syncing:"同步中...",lastSync:"上次同步",linkToSpoolman:"链接到 Spoolman",openInSpoolman:"在 Spoolman 中打开",unlinkSpool:"取消链接耗材",unlinkConfirmTitle:"解开线轴?",unlinkConfirmMessage:"这将断开卷轴与 Spoolman 的连接。Spoolman 中的卷轴数据将保持不变。",selectSpool:"选择耗材",noUnlinkedSpools:"无未链接的耗材",linkSuccess:"耗材已成功链接到 Spoolman",linkFailed:"链接耗材失败",unlinkSuccess:"已成功从 Spoolman 取消链接耗材",unlinkFailed:"取消链接耗材失败",spoolId:"耗材 ID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"剩余",disableWeightSync:"禁用 AMS 估计重量同步",disableWeightSyncDesc:"不从 AMS 估计值更新剩余容量。如果您更喜欢 Spoolman 的用量追踪而非 AMS 百分比估计,请使用此选项。新耗材仍将使用 AMS 估计值作为初始重量。",reportPartialUsage:"报告失败打印的部分用量",reportPartialUsageDesc:"当打印失败或被取消时,根据层进度报告估计的耗材使用量。"},inventory:{title:"耗材库存",addSpool:"添加耗材",editSpool:"编辑耗材",material:"材料",selectMaterial:"选择材料...",subtype:"子类型",brand:"品牌",searchBrand:"搜索品牌...",useCustomBrand:'使用"{{brand}}"',useCustomMaterial:"使用自定义材料:{{material}}",colorName:"颜色名称",colorNamePlaceholder:"翡翠白、烈焰红...",color:"颜色",hexColor:"十六进制颜色",pickColor:"选择自定义颜色",labelWeight:"标签重量",coreWeight:"空盘重量",searchSpoolWeight:"搜索耗材重量...",weightUsed:"已使用",currentWeight:"剩余重量",measuredWeight:"称量重量",spoolName:"线轴",costPerKg:"每公斤成本",measuredWeightError:"称量重量必须在 {{min}}g 到 {{max}}g 之间。",slicerFilament:"切片耗材",slicerFilamentName:"切片预设名称",slicerPreset:"切片预设",searchPresets:"搜索耗材预设...",selectedPreset:"已选择",noPresetsFound:"未找到预设",tempOverrides:"温度覆盖",note:"备注",notePlaceholder:"关于此耗材的任何备注...",archive:"归档",restore:"恢复",noSpools:"暂无耗材。添加您的第一个耗材开始使用。",noManualSpools:"没有手动添加的耗材。请先向库存中添加耗材。",kProfiles:"K 值配置",addKProfile:"添加 K 值配置",assignSpool:"分配耗材",unassignSpool:"取消分配",assignSuccess:"耗材已分配,AMS 槽位已配置",assignFailed:"分配耗材失败",assignMismatchTitle:"材料不匹配",assignMismatchMessage:'所选线轴材料 "{{spoolMaterial}}" 与 {{location}} 的料槽材料 "{{trayMaterial}}" 不匹配。仍要分配吗?',assignMismatchConfirm:"仍然分配",assignPartialMismatchMessage:'线轴材料 "{{spoolMaterial}}" 与 {{location}} 的 "{{trayMaterial}}" 相近但不完全一致。是否继续?',assignProfileMismatchMessage:'线轴配置 "{{spoolProfile}}" 与 {{location}} 的料槽配置 "{{trayProfile}}" 不一致。是否继续?',selectSpool:"选择要分配到此槽位的耗材",assigned:"已分配",assigning:"分配中...",searchSpools:"搜索耗材...",showAllSpools:"显示所有耗材",allMaterials:"所有材料",filterByBrand:"按品牌筛选...",showArchived:"显示已归档",quickAdd:"快速添加(库存)",quantity:"数量",stock:"库存",configured:"已配置",spoolsCreated:"已创建 {{count}} 个耗材",spoolCreated:"耗材已创建",spoolUpdated:"耗材已更新",spoolDeleted:"耗材已删除",spoolArchived:"耗材已归档",spoolRestored:"耗材已恢复",deleteConfirm:"确定要删除此耗材吗?此操作无法撤销。",archiveConfirm:"确定要归档此耗材吗?",advancedSettings:"高级设置",filamentInfoTab:"耗材信息",paProfileTab:"PA 配置",filamentInfo:"耗材",additional:"附加",loadingPresets:"加载云端预设中...",cloudConnected:"云端已连接",cloudNotConnected:"云端未连接(使用默认值)",recentColors:"最近",searchColors:"搜索颜色...",searchResults:"搜索结果",allColors:"所有颜色",commonColors:"常用颜色",showLess:"显示更少",showAll:"显示全部",noColorsFound:"没有颜色匹配您的搜索",noResults:"未找到匹配项",selectMaterialFirst:"请先在耗材信息选项卡中选择材料。",noPrintersConfigured:"未配置打印机。添加打印机以使用 PA 配置。",matchingFilter:"匹配",anyBrand:"任何品牌",anyVariant:"任何变体",autoSelect:"自动选择",matches:"匹配",match:"匹配",noMatches:"无匹配",connected:"已连接",offline:"离线",printerOffline:"打印机离线。连接后查看校准配置。",noKProfilesMatch:"没有 K 值配置匹配所选耗材。",leftNozzle:"左喷嘴",rightNozzle:"右喷嘴",profilesSelected:"个校准配置已选择",totalInventory:"总库存",totalConsumed:"总消耗",byMaterial:"按材料",inPrinter:"在打印机中",lowStock:"库存不足",sinceTracking:"自开始追踪",loadedInAms:"已装载到 AMS/外置",remaining:"剩余",weightCheck:"重量检查",lastWeighed:"上次称量",neverWeighed:"从未称量",search:"搜索耗材...",showing:"显示",to:"到",of:"共",show:"显示",spools:"个耗材",spool:"个耗材",page:"页",noSpoolsMatch:"未找到结果",noSpoolsMatchDesc:"尝试调整您的搜索或筛选条件。",active:"活跃",archived:"已归档",all:"全部",used:"已使用",new:"新的",clearFilters:"清除筛选",table:"表格",cards:"卡片",net:"净重",groupSimilar:"分组",groupedSpools:"{{count}} 个相同耗材",groupedRows:"行",columns:"列",configureColumns:"配置列",configureColumnsDesc:"拖动以重新排序列或使用箭头。使用眼睛图标切换可见性。",visible:"可见",reset:"重置",cancel:"取消",applyChanges:"应用更改",moveUp:"上移",moveDown:"下移",hideColumn:"隐藏列",showColumn:"显示列",linkToSpool:"链接到耗材",tagLinked:"标签已链接到耗材",tagLinkFailed:"链接标签失败",tagAlreadyLinked:"标签已链接到其他耗材",unknownTag:"检测到未知 RFID 标签",usageHistory:"使用历史",noUsageHistory:"暂无使用记录",printName:"打印名称",weightConsumed:"消耗重量",clearHistory:"清除",historyCleared:"使用历史已清除",fillSourceLabel:"(库存)",lowStockThresholdError:"阈值必须在 0.1 到 99.9 之间"},timelapse:{title:"延时摄影",create:"创建延时摄影",download:"下载",delete:"删除",preview:"预览",frameRate:"帧率",quality:"质量",processing:"处理中...",noTimelapses:"无可用延时摄影"},ams:{title:"AMS",slot:"槽位",empty:"空",emptySlot:"空槽位",unknown:"未知",humidity:"湿度",temperature:"温度",filamentType:"耗材类型",filamentColor:"颜色",remaining:"剩余",history:"AMS 历史",noHistory:"无可用历史",configureSlot:"配置槽位",externalSpool:"外置耗材",profile:"配置",kFactor:"K 值",fill:"填充",configure:"配置",used:"已使用",remainingUnit:"剩余"},printModal:{title:"开始打印",selectPrinter:"选择打印机",selectPlate:"选择板",filamentMapping:"耗材映射",totalCost:"总成本:",slotRemainingShort:" - 剩余 {{grams}}g",printSettings:"打印设置",bedLeveling:"热床调平",flowCalibration:"流量校准",vibrationCalibration:"振动校准",layerInspection:"首层检查",timelapse:"延时摄影",startPrint:"开始打印",addToQueue:"添加到队列",cancel:"取消",noPrintersAvailable:"无可用打印机",printerBusy:"打印机忙碌",printerOffline:"打印机离线",sameTypeDifferentColor:"相同类型,不同颜色",filamentTypeNotLoaded:"耗材类型未装载",openCalendar:"打开日历",leftNozzle:"左",rightNozzle:"右",leftNozzleTooltip:"左喷嘴",rightNozzleTooltip:"右喷嘴",filamentOverride:"耗材覆盖",filamentOverrideHint:"可选覆盖用于基于模型的耗材分配。调度器将使用您选择的耗材而不是原始 3MF 值进行匹配。",originalFilament:"原始",overrideWith:"覆盖为",resetToOriginal:"恢复为原始",insufficientFilamentTitle:"耗材不足",insufficientFilamentMessage:"部分已分配线轴的剩余耗材少于本次打印所需:",insufficientFilamentLine:"{{printer}} - {{slot}}:需要 {{required}}g,剩余 {{remaining}}g",printAnyway:"仍然打印",forceColorMatch:"强制颜色匹配",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"分批发送到 {{count}} 台打印机",gcodeInjection:"注入自动打印G-code"},backup:{title:"备份与恢复",createBackup:"创建备份",restoreBackup:"恢复备份",restoreDescription:"从备份文件替换所有数据",downloadBackup:"下载备份",uploadBackup:"上传备份",lastBackup:"上次备份",autoBackup:"自动备份",backupNow:"立即备份",restoreWarning:"警告:恢复备份将覆盖所有当前数据。",includeArchives:"包含归档",includeSettings:"包含设置",includeProfiles:"包含配置文件",backupSuccess:"备份创建成功",restoreSuccess:"备份恢复成功",backupFailed:"备份失败",restoreFailed:"恢复失败",restoreNote:"恢复期间虚拟打印机将停止",githubBackup:"GitHub 备份",enabled:"已启用",cloudLoginRequired:"需要登录 Bambu Cloud。请在 配置文件 → 云配置文件 中登录以启用 GitHub 备份。",cloudLoginRequiredShort:"需要Cloud登录",githubDescription:"自动将您的配置文件同步到私有 GitHub 仓库以进行备份和版本历史记录。",repositoryUrl:"仓库 URL",personalAccessToken:"个人访问令牌",tokenSaved:"(已保存)",enterNewToken:"输入新令牌以更新",tokenHint:"具有内容读写权限的细粒度令牌",branch:"分支",manualOnly:"仅手动",hourly:"每小时",daily:"每天",weekly:"每周",includeInBackup:"包含在备份中",kProfiles:"K 配置文件",kProfilesDescription:"来自已连接打印机的压力推进校准",noPrintersConnected:"没有打印机连接",printersConnected:"{{connected}}/{{total}} 已连接",cloudProfiles:"云配置文件",cloudProfilesDescription:"来自 Bambu Cloud 的耗材、打印机和工艺预设",appSettings:"应用设置",appSettingsDescription:"Bambuddy 配置(完整数据库)",spoolInventory:"耗材库存",spoolInventoryDescription:"耗材卷轴、使用记录和成本追踪",printArchives:"打印档案",printArchivesDescription:"打印历史元数据(不含 gcode/3MF 文件)",lastBackupAt:"上次备份:",noBackupsYet:"尚无备份",next:"下次:",startingBackup:"正在启动备份...",test:"测试",enableBackup:"启用备份",testConnection:"测试连接",enterRepoUrl:"请输入仓库 URL",enterRepoAndToken:"请输入仓库 URL 和访问令牌",repoRequired:"仓库 URL 为必填项",tokenRequired:"访问令牌为必填项",githubBackupEnabled:"GitHub 备份已启用",tokenUpdated:"令牌已更新",settingsSaved:"设置已保存",failedToSave:"保存失败:{{message}}",backupCompleteFiles:"备份完成 - {{count}} 个文件已更新",backupSkippedNoChanges:"备份已跳过 - 无更改",backupFailed2:"备份失败:{{message}}",clearedLogs:"已清除 {{count}} 条日志",failedToClearLogs:"清除日志失败:{{message}}",history:"历史记录",clear:"清除",date:"日期",status:"状态",commit:"提交",localBackup:"本地备份",localBackupDescription:"创建 Bambuddy 数据的完整备份,包括数据库、档案、上传和所有文件。",downloadBackupLabel:"下载备份",completeBackupZip:"完整备份:数据库 + 所有文件(ZIP)",download:"下载",preparingBackup:"正在准备备份...",creatingArchive:"正在创建备份归档...对于大型归档可能需要一些时间。",downloadingFile:"正在下载备份文件...",backupDownloaded:"备份下载成功",failedToCreateBackup:"创建备份失败:{{message}}",restore:"恢复",restoreReplacesAll:"恢复将替换所有数据。",restoreReplacesAllDetail:"您当前的数据库和文件将被完全替换。恢复后需要重启。",restoreConfirmTitle:"恢复备份",restoreConfirmMessage:'您确定要从"{{filename}}"恢复吗?这将完全替换您当前的数据库和所有文件。恢复后需要重启应用程序。',restoreConfirmButton:"恢复备份",uploadingFile:"正在上传备份文件...",backupRestoredRestart:"备份已恢复。请重启 Bambuddy。",failedToRestore:"恢复备份失败。请检查文件格式。",reloadNow:"立即重新加载",creatingBackup:"正在创建备份",restoringBackup:"正在恢复备份",preparing:"准备中...",processing:"处理中...",doNotClosePage:"请不要关闭此页面或导航离开。对于大型备份,此操作可能需要几分钟。",restoring:"恢复中...",restoreComplete:"恢复完成",restoreFailed2:"恢复失败",importSettings:"从备份文件导入设置",pleaseWaitRestoring:"请等待数据恢复中",selectBackupFile:"点击选择备份文件(.json 或 .zip)",duplicateHandling:"重复项处理方式:",matchPrinters:"打印机",matchPrintersBy:"按序列号匹配",matchSmartPlugs:"智能插座",matchSmartPlugsBy:"按 IP 地址匹配",matchNotificationProviders:"通知提供者",matchNotificationProvidersBy:"按名称匹配",matchFilaments:"耗材",matchFilamentsBy:"按名称 + 类型 + 品牌匹配",matchArchives:"档案",matchArchivesBy:"按内容哈希匹配(始终跳过)",matchPendingUploads:"待上传",matchPendingUploadsBy:"按文件名匹配",matchSettingsTemplates:"设置和模板",matchSettingsTemplatesBy:"始终覆盖",replaceExisting:"替换现有数据",keepExisting:"保留现有数据",overwriteDescription:"用备份数据覆盖已存在的项目",keepDescription:"仅恢复尚不存在的项目",overwriteCaution:"注意:",overwriteWarning:"覆盖将用备份数据替换您当前的配置。出于安全考虑,打印机访问代码永远不会被覆盖。",cancel:"取消",processingBackup:"正在处理备份文件...",itemsRestored:"已恢复项目",itemsSkipped:"已跳过项目",restored:"已恢复",skippedAlreadyExist:"已跳过(已存在)",filesCategory:"文件(3MF、缩略图等)",andMore:"...还有 {{count}} 项",newApiKeysGenerated:"已生成新的 API 密钥",keysShownOnce:"这些密钥仅显示一次。请立即复制!",copy:"复制",noDataFound:"在备份文件中未找到可恢复的数据。",close:"关闭",categories:{settings:"设置",notification_providers:"通知提供者",notification_templates:"通知模板",smart_plugs:"智能插座",printers:"打印机",filaments:"耗材",maintenance_types:"维护类型",archives:"档案",projects:"项目",pending_uploads:"待上传",external_links:"外部链接",api_keys:"API 密钥"}},tags:{title:"标签",addTag:"添加标签",editTag:"编辑标签",deleteTag:"删除标签",tagName:"标签名称",tagColor:"标签颜色",noTags:"无标签",deleteConfirm:"确定要删除此标签吗?",manageTags:"管理标签"},uploadModal:{title:"上传 3MF 文件",dragDrop:"将 .3mf 文件拖放到此处",or:"或",browseFiles:"浏览文件",extractionInfo:"将从 3MF 文件元数据中自动提取打印机型号。",uploaded:"已上传",failed:"失败",uploading:"上传中...",upload:"上传",uploadFailed:"上传失败"},editArchive:{title:"编辑归档",name:"名称",namePlaceholder:"打印名称",printer:"打印机",noPrinter:"无打印机",project:"项目",noProject:"无项目",itemsPrinted:"打印数量",itemsPrintedHelp:"此打印任务中生产的物品数量",notes:"备注",notesPlaceholder:"添加关于此打印的备注...",externalLink:"外部链接",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"链接到 Printables、Thingiverse 或其他来源",tags:"标签",tagsPlaceholder:"添加标签...",addMoreTags:"添加更多标签...",matchingTags:'匹配"{{query}}"',existingTags:"现有标签",clickToAdd:"(点击添加)",status:"状态",failureReason:"失败原因",selectReason:"选择原因...",photos:"打印成品照片",photosHelp:"点击 + 添加打印成品照片",printResult:"打印成品",saving:"保存中...",failureReasons:{adhesionFailure:"附着力失败",spaghettiDetached:"拉丝 / 脱落",layerShift:"层偏移",cloggedNozzle:"喷嘴堵塞",filamentRunout:"耗材用完",warping:"翘曲",stringing:"拉丝",underExtrusion:"挤出不足",powerFailure:"断电",userCancelled:"用户取消",other:"其他"},statuses:{completed:"已完成",failed:"失败",aborted:"已取消",printing:"打印中"}},kProfiles:{title:"K 值配置",noPrintersConfigured:"未配置打印机",addPrinterInSettings:"在设置中添加打印机以管理 K 值配置",noActivePrinters:"无活跃打印机",enablePrinterConnection:"启用打印机连接以查看其 K 值配置",loadingProfiles:"加载 K 值配置中...",printerOffline:"打印机离线",printerOfflineDesc:"所选打印机未连接。开启电源以查看 K 值配置。",noMatchingProfiles:"无匹配的配置",noMatchingProfilesDesc:"没有配置匹配您的搜索条件",noKProfiles:"无 K 值配置",noKProfilesDesc:"未找到 {{diameter}}mm 喷嘴的压力推进配置",createFirstProfile:"创建第一个配置",printer:"打印机",nozzle:"喷嘴",refresh:"刷新",addProfile:"添加配置",export:"导出",import:"导入",select:"选择",selectAll:"全选",delete:"删除",searchPlaceholder:"按名称或耗材搜索...",allExtruders:"所有挤出机",leftOnly:"仅左侧",rightOnly:"仅右侧",allFlow:"所有流量",hfOnly:"仅高流量",sOnly:"仅标准",sortName:"排序:名称",sortKValue:"排序:K 值",sortFilament:"排序:耗材",leftExtruder:"左挤出机",rightExtruder:"右挤出机",modal:{addTitle:"添加 K 值配置",editTitle:"编辑 K 值配置",profileName:"配置名称",profileNamePlaceholder:"我的 PLA 配置",kValue:"K 值",kValuePlaceholder:"0.020",kValueHelp:"典型范围:PLA 0.01 - 0.06,PETG 0.02 - 0.10",filament:"耗材",selectFilament:"选择耗材...",noFilamentsHelp:"未找到耗材。请先在 Bambu Studio 中创建 K 值配置。",flowType:"流量类型",highFlow:"高流量",standard:"标准",nozzleSize:"喷嘴尺寸",extruder:"挤出机",extruders:"挤出机",left:"左",right:"右",notes:"备注(本地存储)",notesPlaceholder:"添加关于此配置的备注...",notesHelp:"备注保存在 Bambuddy 中,不在打印机上",syncing:"与打印机同步中...",savingExtruder:"保存到挤出机 {{current}}/{{total}}...",pleaseWait:"请稍候"},deleteConfirm:{title:"删除配置",cannotUndo:"此操作无法撤销",message:'确定要从打印机删除"{{name}}"吗?'},bulkDelete:{title:"删除配置",cannotUndo:"此操作无法撤销",message:"确定要从打印机删除 {{count}} 个选中的配置吗?"},toast:{profileSaved:"K 值配置已保存",profilesSaved:"K 值配置已保存到 {{count}} 个挤出机",selectAtLeastOneExtruder:"请至少选择一个挤出机",profileDeleted:"K 值配置已删除",profilesDeleted:"已删除 {{count}} 个配置",exportedProfiles:"已导出 {{count}} 个配置",importedProfiles:"已导入 {{count}} / {{total}} 个配置",noProfilesToExport:"无可导出的配置",invalidFileFormat:"无效的文件格式",failedToParseImport:"解析导入文件失败",failedToSaveBatch:"批量保存 K 值配置失败",noteSaved:"备注已保存",failedToSaveNote:"保存备注失败"},permission:{noRead:"您没有刷新配置的权限",noCreate:"您没有添加配置的权限",noUpdate:"您没有更新 K 值配置的权限",noDelete:"您没有删除 K 值配置的权限",noExport:"您没有导出配置的权限",noImport:"您没有导入配置的权限"}},virtualPrinter:{title:"虚拟打印机",running:"运行中",stopped:"已停止",description:{default:"启用虚拟打印机,使其在 Bambu Studio 和 OrcaSlicer 中可见。发送到此打印机的文件将直接归档而不打印。",proxy:"启用代理,将切片软件流量中继到真实打印机,允许在任何网络上远程打印。"},enable:{title:"启用虚拟打印机",visibleInSlicer:'在切片软件发现中显示为"Bambuddy"',proxyingTo:"代理到 {{name}}",notActive:"未激活"},model:{title:"打印机型号",description:"选择要模拟的打印机型号。",restartWarning:"更改型号将重启虚拟打印机"},accessCode:{title:"访问码",isSet:"访问码已设置",notSet:"未设置访问码 - 需要设置才能启用",placeholder:"输入 8 位字符代码",placeholderChange:"输入新代码以更改",hint:"必须恰好 8 个字符。切片软件使用此代码进行认证。",charCount:"({{count}}/8)"},targetPrinter:{title:"目标打印机",configured:"代理目标已配置",notConfigured:"未选择目标打印机 - 代理模式需要设置",placeholder:"选择打印机...",hint:"选择要将切片软件流量代理到的打印机。打印机必须处于局域网模式。",noPrinters:"未配置打印机。请先添加打印机以使用代理模式。"},remoteInterface:{title:"网络接口覆盖",configured:"接口覆盖已激活",optional:"可选 - 当自动检测的 IP 不正确时使用(例如多网卡、Docker、VPN)",placeholder:"自动检测(默认)...",hint:"覆盖通过 SSDP 广播并在 TLS 证书中使用的 IP 地址。在 Bambuddy 有多个网络接口时很有用。"},mode:{title:"模式",archive:"归档",archiveDesc:"立即归档文件",review:"审核",reviewDesc:"归档前审核",queue:"队列",queueDesc:"归档并添加到队列",proxy:"代理",proxyDesc:"中继到真实打印机"},autoDispatch:{title:"自动派发",description:"添加到队列时自动开始打印。关闭后,打印任务等待手动派发。"},setupRequired:{title:"需要设置",description:"虚拟打印机功能需要额外的系统配置才能工作。包括端口转发、防火墙规则和平台特定设置。",readGuide:"启用前请阅读设置指南"},howItWorks:{title:"工作原理",step1:"在同一局域网中,虚拟打印机会通过发现机制自动出现在您的切片软件(Bambu Studio / OrcaSlicer)中。从其他网络,通过 IP 地址和访问码手动添加。",step2:'在归档、审核和队列模式下,使用切片软件中的"发送"按钮将 3MF 文件上传到 Bambuddy。切片软件会显示"打印成功"— 文件已存储,未打印。',step3:"在代理模式下,虚拟打印机将所有流量中继到真实打印机 — 打印会立即开始,就像直接连接一样。"},status:{title:"状态详情",printerName:"打印机名称",model:"型号",serialNumber:"序列号",mode:"模式",pendingFiles:"待处理文件",targetPrinter:"目标打印机",ftpPort:"FTP 端口",mqttPort:"MQTT 端口",ftpConnections:"FTP 连接",mqttConnections:"MQTT 连接"},toast:{updated:"虚拟打印机设置已更新",failedToUpdate:"更新设置失败",accessCodeRequired:"请先设置访问码",targetPrinterRequired:"请先选择目标打印机",bindIpRequired:"请先设置绑定 IP",accessCodeEmpty:"访问码不能为空",accessCodeLength:"访问码必须恰好 8 个字符",created:"虚拟打印机已创建",failedToCreate:"创建虚拟打印机失败",deleted:"虚拟打印机已删除",failedToDelete:"删除虚拟打印机失败"},list:{title:"虚拟打印机",add:"添加",addFirst:"添加虚拟打印机",empty:"未配置虚拟打印机。添加一个以开始使用。"},bindIp:{title:"绑定接口",placeholder:"选择接口...",hint:"此虚拟打印机绑定的网络接口。每台打印机必须唯一。"},proxy:{accessCodeHint:"在代理模式下,在切片软件中使用目标打印机的访问码。连接会透明转发到真实打印机。"},addDialog:{title:"添加虚拟打印机",name:"名称",hint:"创建后可以配置访问码、目标打印机和其他设置。",create:"创建"},deleteConfirm:{title:"删除虚拟打印机",message:'确定要删除"{{name}}"吗?这将停止此打印机的所有服务。'}},modelViewer:{openInSlicer:"在切片软件中打开",tabs:{model:"3D 模型",gcode:"G-code 预览"},notAvailable:"不可用",notSliced:"未切片",plates:"板",allPlates:"所有板",plateNumber:"板 {{number}}",plateCount:"{{count}} 个板",plateCount_other:"{{count}} 个板",objectCount:"{{count}} 个对象",objectCount_other:"{{count}} 个对象",filamentCount:"{{count}} 种耗材",filamentCount_other:"{{count}} 种耗材",eta:"预计 {{minutes}} 分钟",noPreview:"此文件无可用预览",pagination:{pageOf:"第 {{current}} / {{total}} 页",prev:"上一页",next:"下一页"},errors:{failedToLoad:"加载文件失败",noMeshes:"3MF 文件中未找到网格",unsupportedFormat:"不支持的文件格式"}},maintenanceDescriptions:{lubricateCarbonRods:"在碳纤维杆上涂抹润滑剂以确保顺畅运动",lubricateRails:"在线性导轨上涂抹润滑剂以确保顺畅运动",cleanNozzle:"清洁热端和喷嘴以防止堵塞",checkBelts:"检查皮带张力以确保打印精度",cleanBuildPlate:"清洁构建板以获得更好的附着力",checkExtruder:"检查挤出机齿轮磨损情况",checkCooling:"确保冷却风扇正常工作",generalInspection:"打印机综合检查",cleanCarbonRods:"清洁碳纤维杆以减少摩擦",lubricateSteelRods:"在钢杆上涂抹润滑剂以确保顺畅运动",cleanSteelRods:"清洁钢杆以减少摩擦",cleanLinearRails:"擦拭线性导轨以清除灰尘和碎屑",checkPtfeTube:"检查 PTFE 管的磨损或损坏",replaceHepaFilter:"更换 HEPA 过滤器以保证空气质量",replaceCarbonFilter:"更换活性炭过滤器",lubricateLeftNozzleRail:"润滑左喷嘴导轨(H2 系列)"},smartPlugs:{offline:"离线",admin:"管理",openPlugAdminPage:"打开插座管理页面",deleteSmartPlug:"删除智能插座",turnOnSmartPlug:"开启智能插座",turnOffSmartPlug:"关闭智能插座",turnOn:"开启",turnOff:"关闭",addSmartPlug:{scanningNetwork:"扫描网络中...",chooseEntity:"选择实体...",connectionFailed:"连接失败",searchEntities:"搜索实体...",searchPowerSensors:"搜索功率传感器...",searchEnergySensors:"搜索能量传感器...",placeholders:{plugName:"客厅插座",mqttStateOnValue:"ON、true、1",mqttSameAsPower:"与功率主题相同,或不同"}},linkedTo:"关联到:",monitorOnly:"仅监控",alerts:"警报",scheduleOn:"开启 {{time}}",scheduleOff:"关闭 {{time}}",on:"开启",off:"关闭",power:"功率",kwhToday:"今日kWh",settings:"设置",automationSettings:"自动化设置",showInSwitchbar:"在开关栏显示",quickAccessSidebar:"从侧边栏快速访问",enabled:"已启用",enableAutomation:"为此插座启用自动化",autoOn:"自动开启",autoOnDescription:"打印开始时开启",autoOff:"自动关闭",autoOffDescription:"打印完成时关闭(一次性)",autoOffPersistent:"保持启用",autoOffPersistentDescription:"在打印之间保持启用而非一次性",turnOffDelayMode:"关闭延迟模式",time:"时间",temp:"温度",delayMinutes:"延迟(分钟)",tempThreshold:"温度阈值(°C)",tempThresholdDescription:"当喷嘴冷却到此温度以下时关闭",edit:"编辑",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',turnOnConfirm:'确定要开启"{{name}}"吗?',turnOffConfirm:'确定要关闭"{{name}}"吗?这将切断连接设备的电源。',failedToTurn:'无法{{action}}"{{name}}"',unknown:"未知",addTitle:"添加智能插座",editTitle:"编辑智能插座",stopScanning:"停止扫描",discoverTasmota:"发现Tasmota设备",foundDevices:"找到{{count}}个设备 - 点击选择:",noDevicesFound:"未在您的网络中找到Tasmota设备",haNotConfigured:"Home Assistant未配置。请在以下位置设置",haSettingsPath:"设置 → 网络 → Home Assistant",selectEntity:"选择实体 *",ipAddress:"IP地址 *",nameLabel:"名称 *",username:"用户名",password:"密码",authHint:"如果您的Tasmota设备不需要认证,请留空",linkToPrinter:"关联打印机",noPrinter:"无打印机(仅手动控制)",linkingDescription:"关联后可在打印开始/完成时自动开关",powerAlerts:"功率警报",alertAbove:"高于时警报(W)",alertBelow:"低于时警报(W)",alertDescription:"当电力消耗超过这些阈值时收到通知。留空以禁用该方向。",dailySchedule:"每日计划",turnOnAt:"开启时间",turnOffAt:"关闭时间",scheduleDescription:"每天在这些时间自动开关插座。留空以跳过该操作。",showOnPrinterCard:"在打印机卡片上显示",displayOnPrinterCard:"在打印机卡片上显示按钮",connectedResult:"已连接!",deviceLabel:"设备:{{name}} - ",stateLabel:"状态:{{state}}",test:"测试",delete:"删除",save:"保存",add:"添加",cancel:"取消",failedToStartScan:"无法开始扫描",nameRequired:"名称为必填项",entityRequired:"Home Assistant插座需要实体",mqttTopicRequired:"必须为功率、能源或状态监控配置至少一个MQTT主题",loadingEntities:"正在加载实体...",loading:"加载中...",failedToLoadEntities:"加载实体失败:{{error}}",noEntitiesMatching:'未找到匹配"{{search}}"的实体',noEntitiesAvailable:"无可用实体",searchingEntities:"搜索所有实体(找到{{count}}个)",showingEntities:"显示 switch、light、input_boolean({{count}}个可用)",energyMonitoringOptional:"能源监控(可选)",energyMonitoringHint:"搜索并选择提供功率/能源数据的传感器。",powerSensorW:"功率传感器(W)",energyTodayKwh:"今日能源(kWh)",totalEnergyKwh:"总能源(kWh)",noMatchingSensors:"无匹配的传感器",none:"无",mqttNotConfigured:"MQTT代理未配置。请在以下位置设置代理地址",mqttSettingsPath:"设置 → 网络 → MQTT发布",mqttNotConfiguredSuffix:"(您不需要启用发布,只需填写代理详细信息)。",mqttMonitorOnlyDescription:"MQTT插座通过MQTT订阅接收功率/能源数据。开关控制不可用 - 请使用您的MQTT代理或家庭自动化系统。",powerMonitoring:"功率监控",energyMonitoring:"能源监控",stateMonitoring:"状态监控",optional:"可选",topic:"主题",jsonPath:"JSON路径",multiplier:"乘数",onValue:"ON值",mqttPowerHint:`JSON路径从JSON负载中提取值(例如"power_l1")。如果主题发布原始数值,请留空。
  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:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"功率URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"功率乘数",restEnergyUrl:"能耗URL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"能耗乘数",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"功率数据的独立URL(留空则使用状态URL)",restEnergyUrlHint:"能耗数据的独立URL(留空则使用状态URL)",restEnergyHint:"每个值可以使用独立的URL,或回退到状态URL。使用乘数进行单位转换(例如:0.001 将 Wh 转换为 kWh)。",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"开关栏中没有开关",enableSwitchbarHint:'在设置 > 智能插座中启用"在开关栏显示"'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"电子邮件",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTP 电子邮件通知",telegram:"通过 Telegram 机器人发送通知",discord:"通过 Webhook 发送到 Discord 频道",ntfy:"免费、可自托管的推送通知",pushover:"简单、可靠的推送通知",callmebot:"通过 CallMeBot 免费发送 WhatsApp 通知",webhook:"通用 HTTP POST 到任意 URL",homeassistant:"Home Assistant 仪表板中的持久通知"},lastSuccess:"上次:{{date}}",error:"错误",printer:"打印机:",allPrinters:"所有打印机",sendTestNotification:"发送测试通知",eventSettings:"事件设置",enabled:"已启用",sendFromProvider:"从此提供商发送通知",printEvents:"打印事件",printerStatus:"打印机状态",amsAlarms:"AMS 警报",amsHtAlarms:"AMS-HT 警报",printQueue:"打印队列",start:"开始",plateCheck:"热床检测",complete:"完成",failed:"失败",stopped:"已停止",progress:"进度",offline:"离线",lowFilament:"耗材不足",maintenance:"维护",amsHumidity:"AMS 湿度",amsTemp:"AMS 温度",amsHtHumidity:"AMS-HT 湿度",amsHtTemp:"AMS-HT 温度",bedCooled:"热床已冷却",firstLayer:"首层完成",quiet:"免打扰",digest:"摘要 {{time}}",printStarted:"打印已开始",plateNotEmpty:"热床非空",plateNotEmptyDescription:"打印前检测到物体",printCompleted:"打印已完成",bedCooledLabel:"热床已冷却",bedCooledDescription:"打印后热床温度降至阈值以下",firstLayerCompleteLabel:"首层打印完成",firstLayerCompleteDescription:"首层完成时发送带照片的通知",missingSpoolAssignmentLabel:"缺少料卷分配",missingSpoolAssignmentDescription:"当打印开始且所需料盘没有分配料卷时发送通知",printFailed:"打印失败",printStopped:"打印已停止",progressMilestones:"进度里程碑",progressMilestonesDescription:"在 25%、50%、75% 时通知",printerOffline:"打印机离线",printerError:"打印机错误",lowFilamentLabel:"耗材不足",maintenanceDue:"需要维护",maintenanceDueDescription:"需要维护时通知",amsHumidityHigh:"AMS 湿度过高",amsHumidityHighDescription:"普通 AMS 湿度超过阈值",amsTemperatureHigh:"AMS 温度过高",amsTemperatureHighDescription:"普通 AMS 温度超过阈值",amsHtHumidityHigh:"AMS-HT 湿度过高",amsHtHumidityHighDescription:"AMS-HT 湿度超过阈值",amsHtTemperatureHigh:"AMS-HT 温度过高",amsHtTemperatureHighDescription:"AMS-HT 温度超过阈值",jobAdded:"任务已添加",jobAddedDescription:"任务已添加到队列",jobAssigned:"任务已分配",jobAssignedDescription:"基于模型的任务已分配给打印机",jobStarted:"任务已开始",jobStartedDescription:"队列任务已开始打印",jobWaiting:"任务等待中",jobWaitingDescription:"任务正在等待耗材或打印机",jobSkipped:"任务已跳过",jobSkippedDescription:"任务已跳过(上一个失败)",jobFailed:"任务失败",jobFailedDescription:"任务启动失败",queueComplete:"队列已完成",queueCompleteDescription:"所有队列任务已完成",quietHours:"免打扰时段",noNotificationsDuring:"在此时段内不发送通知",editProviderToChangeQuietHours:"编辑提供商以更改免打扰时段",dailyDigest:"每日摘要",batchNotifications:"将通知汇总为每日摘要",sendAt:"发送于 {{time}}",editProviderToChangeDigestTime:"编辑提供商以更改摘要时间",edit:"编辑",deleteProvider:"删除通知提供商",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',delete:"删除",addTitle:"添加通知提供商",editTitle:"编辑通知提供商",nameLabel:"名称 *",namePlaceholder:"我的通知",providerTypeLabel:"提供商类型 *",configuration:"配置",testConfiguration:"测试配置",printerFilter:"打印机筛选",onlyFromPrinter:"仅发送来自此打印机的事件通知",quietHoursDnd:"免打扰时段",quietStart:"开始",quietEnd:"结束",dailyDigestLabel:"每日摘要",sendDigestAt:"发送摘要于",digestCollected:"事件将被收集并在此时间作为单条摘要发送",notificationEvents:"通知事件",progressPercent:"(25%、50%、75%)",bedCooledAfterPrint:"(打印完成后)",cancel:"取消",save:"保存",add:"添加",nameRequired:"名称为必填项",fieldRequired:"{{field}}为必填项",phoneNumber:"电话号码",apiKey:"API 密钥",serverUrl:"服务器 URL",topic:"主题",authToken:"认证令牌",userKey:"用户密钥",appToken:"应用令牌",priority:"优先级",botToken:"机器人令牌",chatId:"聊天 ID",smtpServer:"SMTP 服务器",smtpPort:"SMTP 端口",security:"安全",authentication:"认证",username:"用户名",password:"密码",fromEmail:"发件人邮箱",toEmail:"收件人邮箱",webhookUrl:"Webhook URL",payloadFormat:"负载格式",authorization:"授权",titleFieldName:"标题字段名",messageFieldName:"消息字段名",editTemplate:"编辑模板:{{name}}",titleLabel:"标题",bodyLabel:"正文",titlePlaceholder:"通知标题...",bodyPlaceholder:"通知正文...",availableVariables:"可用变量",clickToInsert:"点击插入到正文光标位置",livePreview:"实时预览",hide:"隐藏",show:"显示",loadingPreview:"加载预览中...",enterTemplateContent:"输入模板内容以查看预览",titlePreview:"标题:",bodyPreview:"正文:",resetToDefault:"恢复默认",titleRequired:"标题为必填项",bodyRequired:"正文为必填项",notificationLog:"通知日志",showFailedOnly:"仅显示失败",last24Hours:"最近 24 小时",last7Days:"最近 7 天",last30Days:"最近 30 天",last90Days:"最近 90 天",justNow:"刚刚",noFailedNotifications:"没有失败的通知",noNotificationsLogged:"没有通知记录",unknownProvider:"未知提供商",logTitle:"标题",logMessage:"消息",logError:"错误",logProvider:"提供商:{{type}}",logTime:"时间:{{time}}",refresh:"刷新",clearOld:"清除旧记录",statsSummary:"最近 {{days}} 天:",statsNotifications:"条通知",statsSent:"{{count}} 条已发送",statsFailed:"{{count}} 条失败",eventTypes:{print_start:"打印已开始",print_complete:"打印完成",print_failed:"打印失败",print_stopped:"打印已停止",print_progress:"进度",printer_offline:"打印机离线",printer_error:"打印机错误",filament_low:"耗材不足",maintenance_due:"需要维护",test:"测试"},userEmail:{title:"通知",emailNotifications:"邮件通知",emailNotificationsDesc:"接收您自己打印任务的邮件通知。邮件将通过高级身份验证中配置的 SMTP 设置发送。",sendingTo:"通知将发送至",noEmailWarning:"您的账户没有邮件地址。请联系管理员添加。",printJobNotifications:"打印任务通知",printJobNotificationsDesc:"选择哪些事件会触发您提交的打印任务的邮件通知。",printJobStarts:"打印任务开始",printJobStartsDesc:"当您的打印任务开始时收到通知。",printJobFinishes:"打印任务完成",printJobFinishesDesc:"当您的打印任务成功完成时收到通知。",printErrors:"打印错误",printErrorsDesc:"当您的打印任务失败或遇到错误时收到通知。",printJobStops:"打印任务停止",printJobStopsDesc:"当您的打印任务被取消或停止时收到通知。",saveSuccess:"通知偏好设置已保存。",saveError:"保存通知偏好设置失败。"}},richTextEditor:{bold:"粗体",italic:"斜体",underline:"下划线",bulletList:"无序列表",numberedList:"有序列表",alignLeft:"左对齐",alignCenter:"居中对齐",alignRight:"右对齐",addLink:"添加链接",removeLink:"移除链接"},externalLinks:{noLinksConfigured:"未配置外部链接",deleteLink:"删除链接",removeCustomIcon:"移除自定义图标",openInNewTab:"在新标签页中打开",placeholders:{linkName:"我的链接"}},keyboardShortcuts:{title:"键盘快捷键",navigation:"导航",archivesSection:"归档",kProfilesSection:"K 值配置",generalSection:"通用",shortcuts:{goToPrinters:"前往打印机",goToArchives:"前往归档",goToQueue:"前往队列",goToStats:"前往统计",goToProfiles:"前往云端配置",goToSettings:"前往设置",focusSearch:"聚焦搜索",openUploadModal:"打开上传对话框",clearSelection:"清除选择 / 取消焦点",contextMenu:"卡片右键菜单",refreshProfiles:"刷新配置",newProfile:"新建配置",exitSelectionMode:"退出选择模式",showHelp:"显示此帮助"},footer:"按 Esc 或点击外部关闭"},notificationLog:{title:"通知日志",events:{printStarted:"打印开始",printComplete:"打印完成",printFailed:"打印失败",printStopped:"打印停止",progress:"进度",printerOffline:"打印机离线",printerError:"打印机错误",lowFilament:"耗材不足",maintenanceDue:"维护到期",test:"测试"},timeAgo:{justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前"}},restoreBackup:{title:"恢复备份",restoring:"恢复中...",restoreComplete:"恢复完成",restoreFailed:"恢复失败",importSettings:"从备份文件导入设置",pleaseWait:"请稍候,正在恢复您的数据",clickToSelect:"点击选择备份文件(.json 或 .zip)",howDuplicateHandling:"重复处理方式:",categories:{printers:"打印机",smartPlugs:"智能插座",notificationProviders:"通知提供商",filaments:"耗材",archives:"归档",pendingUploads:"待处理上传",settingsTemplates:"设置和模板"},matchingInfo:{printers:"按序列号匹配",smartPlugs:"按 IP 地址匹配",notificationProviders:"按名称匹配",filaments:"按名称 + 类型 + 品牌匹配",archives:"按内容哈希匹配",pendingUploads:"按文件名匹配",settingsTemplates:"始终覆盖"},replaceExisting:"替换现有数据",keepExisting:"保留现有数据",replaceDescription:"用备份数据覆盖已存在的项目",keepDescription:"仅恢复不存在的项目",caution:"注意:",cautionText:"覆盖将用备份数据替换您当前的配置。出于安全考虑,打印机访问码永远不会被覆盖。",itemsRestored:"已恢复项目",itemsSkipped:"已跳过项目",restored:"已恢复",skipped:"已跳过(已存在)",filesLabel:"文件(3MF、缩略图等)",newApiKeysGenerated:"已生成新 API 密钥",newApiKeysWarning:"这些密钥仅显示一次。请立即复制!",processingBackup:"处理备份文件中...",noDataFound:"备份文件中未找到可恢复的数据。",failedToRestore:"恢复备份失败。请检查文件格式。"},backupExport:{title:"导出备份",selectData:"选择要包含的数据",selectAll:"全选",selectNone:"全不选",categoryDescriptions:{settings:"语言、主题、更新偏好",notifications:"ntfy、Pushover、Discord 等",templates:"自定义消息模板",smartPlugs:"Tasmota 插座配置",externalLinks:"侧边栏外部服务链接",printers:"打印机信息(不含访问码)",plateDetection:"空打印板参考图像",filaments:"耗材类型和成本",maintenance:"自定义维护计划",archives:"所有打印数据 + 文件(3MF、缩略图、照片)",projects:"项目、材料清单和附件",pendingUploads:"虚拟打印机待审核的上传",apiKeys:"Webhook API 密钥(导入时生成新密钥)"},requiresPrinters:"需要选择打印机",zipFileWarning:"将创建 ZIP 文件。",zipFileDescription:"包括所有 3MF 文件、缩略图、延时摄影和照片。这可能需要一些时间并生成较大的文件。",includeAccessCodes:"包含访问码",includeAccessCodesDescription:"用于转移到另一台机器",includeAccessCodesWarning:"访问码将以明文形式包含。请妥善保管此备份文件!",categoriesSelected:"已选择 {{selectedCount}} 个类别"},pendingUploads:{placeholders:{notes:"添加关于此打印的备注..."},discardUpload:"丢弃上传",archiveAllUploads:"归档所有上传",discardAllUploads:"丢弃所有上传",archive:"归档",timeAgo:{justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前",daysAgo:"{{days}} 天前"}},apiBrowser:{placeholders:{requestBody:"JSON 请求体...",searchEndpoints:"搜索端点..."}},configureAmsSlot:{title:"配置 AMS 槽位",slotConfigured:"槽位已配置!",configuringSlot:"正在配置槽位:",slotLabel:"{{ams}} 槽位 {{slot}}",searchPresets:"搜索预设...",colorPlaceholder:"颜色名称或十六进制(例如:棕色、FF8800)",clearCustomColor:"清除自定义颜色",noCloudPresets:"无云端预设。登录拓竹云以同步。",noPresetsAvailable:"无可用预设。登录拓竹云或导入本地配置。",noMatchingPresets:"未找到匹配的预设。",custom:"自定义",builtin:"内置",settingsSentToPrinter:"设置已发送到打印机",filamentProfile:"耗材配置",kProfileLabel:"K 值配置(压力推进)",filteringFor:"筛选:{{material}}",noKProfile:"无 K 值配置(使用默认值 0.020)",noMatchingKProfiles:"未找到匹配的 K 值配置。将使用默认 K=0.020。",selectFilamentFirst:"请先选择耗材配置",kFromCalibration:"K={{value}}(来自打印机校准)",customColorLabel:"自定义颜色(可选)",presetColors:"{{name}} 颜色:",showLessColors:"显示更少颜色",showMoreColors:"显示更多颜色",clear:"清除",hexLabel:"十六进制:#{{hex}}",resetting:"重置中...",resetSlot:"重置槽位",cancel:"取消",configuring:"配置中...",configureSlot:"配置槽位"},githubBackup:{title:"GitHub 备份",history:"历史",downloadBackup:"下载备份",restoreBackup:"恢复备份",noBackupsYet:"暂无备份"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"搜索标签...",renameTag:"重命名标签",deleteTag:"删除标签"},notificationTemplates:{placeholders:{title:"通知标题...",body:"通知正文..."}},batchTag:{placeholders:{newTag:"输入新标签..."}},photoGallery:{deletePhoto:"删除照片"},filamentHoverCard:{copySpoolUuid:"复制耗材 UUID"},kProfilesView:{hasNote:"有备注",copyProfile:"复制配置"},layout:{openMenu:"打开菜单",noPermissionSystemInfo:"您没有查看系统信息的权限"},dashboard:{dragToReorder:"拖动以重新排列",hideWidget:"隐藏小部件"},notificationProviderCard:{deleteNotificationProvider:"删除通知提供商"},fileManagerModal:{closeFileManager:"关闭文件管理器",sortFiles:"排序文件",goToParentFolder:"返回上级文件夹",threeView:"3D 视图"},embeddedCameraViewer:{refreshStream:"刷新流",close:"关闭",zoomOut:"缩小",resetZoom:"重置缩放",zoomIn:"放大",dragToResize:"拖动调整大小"},timelapseViewer:{skipBack5s:"后退 5 秒",skipForward5s:"前进 5 秒"},notificationProviders:{descriptions:{email:"SMTP 邮件通知",telegram:"通过 Telegram 机器人通知",discord:"通过 Webhook 发送到 Discord 频道",ntfy:"免费、可自托管的推送通知",pushover:"简单、可靠的推送通知",callmebot:"通过 CallMeBot 的免费 WhatsApp 通知",webhook:"通用 HTTP POST 到任意 URL"}},logViewer:{searchPlaceholder:"搜索消息或日志名称...",noLogEntries:"未找到日志条目"},switchbarPopover:{noSwitchesInSwitchbar:"切换栏中没有开关"},projectPageModal:{placeholders:{title:"标题",designer:"设计师",license:"许可证",description:"输入描述...",profileTitle:"配置标题",profileDescription:"配置描述..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"等待中",justNow:"刚刚",now:"现在",minsAgo:"{{count}} 分钟前",inMins:"{{count}} 分钟后",hoursAgo:"{{count}} 小时前",inHours:"{{count}} 小时后",daysAgo:"{{count}} 天前",inDays:"{{count}} 天后"},spoolbuddy:{nav:{dashboard:"仪表板",ams:"AMS",inventory:"库存",writeTag:"写入",settings:"设置"},status:{nfcReady:"NFC 就绪",nfcOff:"NFC 关闭",offline:"离线",online:"在线",noPrinters:"无打印机",deviceOffline:"设备离线",waitingConnection:"等待设备连接...",systemReady:"系统就绪",status:"状态"},dashboard:{readyToScan:"准备扫描",idleMessage:"将耗材放在秤上以识别",nfcHint:"NFC 标签将自动读取",device:"设备",syncWeight:"同步重量",weightSynced:"已同步!",unknownTag:"未知标签",newTag:"检测到新标签",onScale:"在秤上",linkSpool:"链接到耗材",linkTagTitle:"将标签链接到耗材",linkTag:"链接标签",selectSpool:"选择要链接此标签的耗材:",noUntagged:"未找到没有标签的耗材",tagDetected:"检测到标签",noTag:"无标签",tagId:"标签",grossWeight:"毛重",spoolSize:"耗材盘尺寸",close:"关闭",currentSpool:"当前耗材"},modal:{spoolDetected:"检测到耗材",assignToAms:"分配到 AMS",syncWeight:"同步重量",weightSynced:"已同步!",syncing:"同步中...",newTagDetected:"检测到新标签",addToInventory:"添加到库存",assignToAmsTitle:"分配到 AMS",selectSlot:"选择槽位",assign:"分配",assigning:"分配中...",assignSuccess:"已分配!",assignError:"分配耗材失败。请重试。",noPrinterSelected:"选择打印机...",noAmsDetected:"此打印机未检测到 AMS",slot:"槽位"},weight:{noReading:"无读数",stable:"稳定",measuring:"测量中...",tare:"去皮",calibrate:"校准"},spool:{remaining:"剩余",material:"材料",brand:"品牌",color:"颜色",coreWeight:"空盘",labelWeight:"标签",scaleWeight:"秤重",netWeight:"净重",lastUsed:"上次使用"},ams:{noData:"未检测到 AMS",connectAms:"连接 AMS 以查看耗材槽位",noPrinter:"未选择打印机",selectPrinter:"从顶部栏选择打印机",printerDisconnected:"打印机已断开",humidity:"湿度",level:"余量",active:"活跃",slot:"槽位",empty:"空"},inventory:{search:"搜索耗材...",empty:"库存中没有耗材",noResults:"没有匹配的耗材",spools:"个耗材",addSpool:"添加耗材"},settings:{tabDevice:"设备",tabDisplay:"显示",tabScale:"秤",tabUpdates:"更新",nfcReader:"NFC 读卡器",type:"类型",connection:"连接",notConnected:"不适用",deviceInfo:"设备信息",hostname:"主机",uptime:"运行时间",brightness:"亮度",saved:"已保存",noBacklight:"未检测到 DSI 背光。亮度控制需要 DSI 显示屏。",screenBlank:"屏幕熄灭超时",screenBlankDesc:"不活动后屏幕关闭。触摸唤醒。",displayNote:"亮度作为软件滤镜应用。",scaleCalibration:"秤校准",currentWeight:"当前重量",tareOffset:"去皮",calFactor:"系数",knownWeight:"已知重量",calStep1:"移除秤上所有物品并按设置零点。",calStep2:"将已知重量放在秤上。",setZero:"设置零点",calibrateNow:"校准",calibrated:"已校准",tareSet:"去皮命令已发送。等待设备响应...",tareFailed:"发送去皮命令失败",zeroSet:"零点已设置。将已知重量放在秤上。",calibrationDone:"校准完成!",calibrationFailed:"校准失败",lastCalibrated:"上次校准",stable:"稳定",settling:"稳定中...",firmware:"固件",scale:"秤",noDevice:"未找到 SpoolBuddy 设备",daemonVersion:"守护进程版本",currentVersion:"当前",versionPending:"等待守护进程...",checking:"检查中...",checkUpdates:"检查更新",updateAvailable:"有可用更新",updateInstructions:"通过 SSH 更新:运行 SpoolBuddy 安装脚本进行升级。",upToDate:"已是最新",includeBeta:"包含测试版本"},writeTag:{tabExisting:"现有耗材",tabNew:"新耗材",tabReplace:"替换标签",searchPlaceholder:"按材料、颜色、品牌搜索...",noUntaggedSpools:"没有无标签的耗材",noTaggedSpools:"没有有标签的耗材",selectSpool:"选择一个耗材,然后将空白 NTAG 放在读卡器上",placeTag:"将 NTAG 放在读卡器上",tagReady:"检测到标签 — 准备写入",writeTag:"写入标签",replaceTag:"替换标签",writing:"写入标签中...",waiting:"等待 SpoolBuddy...",writeSuccess:"标签写入成功!",writeFailed:"写入失败",queueFailed:"排队写入命令失败",tryAgain:"重试",cancel:"取消",replaceWarning:"旧标签将被取消链接。新标签将替换它。",deviceOffline:"SpoolBuddy 离线",material:"材料",colorName:"颜色名称",color:"颜色",brand:"品牌",weight:"重量 (g)",createSpool:"创建耗材",creating:"创建中...",spoolCreated:"耗材已创建!准备写入。",createFailed:"创建耗材失败"},quickMenu:{printerPower:"打印机电源",systemControls:"系统",restartDaemon:"重启守护进程",restartBrowser:"重启浏览器",reboot:"重启",shutdown:"关机",swipeToClose:"向下滑动关闭",confirmTitle:"确认",confirmShutdown:"确定要关闭SpoolBuddy吗?您需要物理访问才能重新开启。",confirmReboot:"确定要重启SpoolBuddy吗?",confirmRestartDaemon:"重启SpoolBuddy守护进程?NFC和秤将暂时不可用。",confirmRestartBrowser:"重启kiosk浏览器?屏幕将短暂变黑。",confirm:"确认",confirmPlugOn:"开启 {{name}}?",confirmPlugOff:"关闭 {{name}}?",turnOn:"开启",turnOff:"关闭"}},bugReport:{title:"报告错误",description:"描述",descriptionPlaceholder:"出了什么问题?请描述问题...",email:"邮箱(可选)",emailPlaceholder:"your@email.com",emailPrivacy:"如果提供,您的邮箱将包含在GitHub Issue的折叠部分中,以便维护者后续跟进。",screenshot:"截图",uploadOrPaste:"上传、粘贴或拖拽图片",dataCollectedSummary:"报告中包含哪些数据?",dataIncluded:"包含:",dataIncludedList:"应用版本、操作系统、架构、Python版本、数据库统计(仅计数)、打印机型号、喷嘴数量、固件版本、连接状态、集成状态(Spoolman、MQTT、HA)、非敏感设置、网络接口数量、Docker详情、依赖版本。",dataNeverIncluded:"绝不包含:",dataNeverIncludedList:"打印机名称、序列号、访问代码、密码、IP地址、邮箱地址、API密钥、令牌、Webhook URL、主机名或用户名。",submit:"提交",startLogging:"开始调试日志",stepEnableLogging:"调试日志已启用",stepReproduce:"请现在重现问题",stepStopLogging:"停止并提交报告",stopAndSubmit:"停止并提交",maxDuration:"{{minutes}}分钟后自动停止",stoppingLogs:"正在收集日志并提交...",submitting:"正在提交错误报告...",submitSuccess:"错误报告提交成功!",submitFailed:"提交错误报告失败",thankYou:"谢谢!",submitted:"您的错误报告已提交。",viewIssue:"查看Issue",unexpectedError:"发生了意外错误"}},Aue={en:{translation:Sue},de:{translation:_ue},fr:{translation:kue},ja:{translation:Nue},it:{translation:Cue},"pt-BR":{translation:Pue},"zh-CN":{translation:Tue}};oo.use(TX).use(eue).init({resources:Aue,fallbackLng:"en",supportedLngs:["en","de","fr","ja","it","pt-BR","zh-CN"],detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:"bambutrack_language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!1}});const G8=[{code:"en",name:"English",nativeName:"English"},{code:"de",name:"German",nativeName:"Deutsch"},{code:"fr",name:"French",nativeName:"Français"},{code:"ja",name:"Japanese",nativeName:"日本語"},{code:"it",name:"Italian",nativeName:"Italiano"},{code:"pt-BR",name:"Portuguese (Brazil)",nativeName:"Português (Brasil)"},{code:"zh-CN",name:"Chinese (Simplified)",nativeName:"简体中文"}];var W8="popstate";function Mue(t={}){function e(r,i){let{pathname:s,search:o,hash:l}=r.location;return C3("",{pathname:s,search:o,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(r,i){return typeof i=="string"?i:E0(i)}return Eue(e,n,null,t)}function ya(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function Kl(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function jue(){return Math.random().toString(36).substring(2,10)}function K8(t,e){return{usr:t.state,key:t.key,idx:e}}function C3(t,e,n=null,r){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof e=="string"?Yx(e):e,state:n,key:e&&e.key||r||jue()}}function E0({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 Yx(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substring(n),t=t.substring(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substring(r),t=t.substring(0,r)),t&&(e.pathname=t)}return e}function Eue(t,e,n,r={}){let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,l="POP",c=null,d=u();d==null&&(d=0,o.replaceState({...o.state,idx:d},""));function u(){return(o.state||{idx:null}).idx}function m(){l="POP";let b=u(),g=b==null?null:b-d;d=b,c&&c({action:l,location:v.location,delta:g})}function p(b,g){l="PUSH";let _=C3(v.location,b,g);d=u()+1;let k=K8(_,d),P=v.createHref(_);try{o.pushState(k,"",P)}catch(N){if(N instanceof DOMException&&N.name==="DataCloneError")throw N;i.location.assign(P)}s&&c&&c({action:l,location:v.location,delta:1})}function f(b,g){l="REPLACE";let _=C3(v.location,b,g);d=u();let k=K8(_,d),P=v.createHref(_);o.replaceState(k,"",P),s&&c&&c({action:l,location:v.location,delta:0})}function y(b){return Due(b)}let v={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(W8,m),c=b,()=>{i.removeEventListener(W8,m),c=null}},createHref(b){return e(i,b)},createURL:y,encodeLocation(b){let g=y(b);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:p,replace:f,go(b){return o.go(b)}};return v}function Due(t,e=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ya(n,"No window.location.(origin|href) available to create URL");let r=typeof t=="string"?t:E0(t);return r=r.replace(/ $/,"%20"),!e&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function AX(t,e,n="/"){return Fue(t,e,n,!1)}function Fue(t,e,n,r){let i=typeof e=="string"?Yx(e):e,s=$u(i.pathname||"/",n);if(s==null)return null;let o=MX(t);Rue(o);let l=null;for(let c=0;l==null&&c<o.length;++c){let d=Gue(s);l=$ue(o[c],d,r)}return l}function MX(t,e=[],n=[],r="",i=!1){let s=(o,l,c=i,d)=>{let u={relativePath:d===void 0?o.path||"":d,caseSensitive:o.caseSensitive===!0,childrenIndex:l,route:o};if(u.relativePath.startsWith("/")){if(!u.relativePath.startsWith(r)&&c)return;ya(u.relativePath.startsWith(r),`Absolute route path "${u.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),u.relativePath=u.relativePath.slice(r.length)}let m=Ru([r,u.relativePath]),p=n.concat(u);o.children&&o.children.length>0&&(ya(o.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${m}".`),MX(o.children,e,p,m,c)),!(o.path==null&&!o.index)&&e.push({path:m,score:Hue(m,o.index),routesMeta:p})};return t.forEach((o,l)=>{if(o.path===""||!o.path?.includes("?"))s(o,l);else for(let c of jX(o.path))s(o,l,!0,c)}),e}function jX(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=jX(r.join("/")),l=[];return l.push(...o.map(c=>c===""?s:[s,c].join("/"))),i&&l.push(...o),l.map(c=>t.startsWith("/")&&c===""?"/":c)}function Rue(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:que(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Lue=/^:[\w-]+$/,Oue=3,Iue=2,zue=1,Uue=10,Bue=-2,Y8=t=>t==="*";function Hue(t,e){let n=t.split("/"),r=n.length;return n.some(Y8)&&(r+=Bue),e&&(r+=Iue),n.filter(i=>!Y8(i)).reduce((i,s)=>i+(Lue.test(s)?Oue:s===""?zue:Uue),r)}function que(t,e){return t.length===e.length&&t.slice(0,-1).every((r,i)=>r===e[i])?t[t.length-1]-e[e.length-1]:0}function $ue(t,e,n=!1){let{routesMeta:r}=t,i={},s="/",o=[];for(let l=0;l<r.length;++l){let c=r[l],d=l===r.length-1,u=s==="/"?e:e.slice(s.length)||"/",m=Yk({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},u),p=c.route;if(!m&&d&&n&&!r[r.length-1].route.index&&(m=Yk({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},u)),!m)return null;Object.assign(i,m.params),o.push({params:i,pathname:Ru([s,m.pathname]),pathnameBase:Xue(Ru([s,m.pathnameBase])),route:p}),m.pathnameBase!=="/"&&(s=Ru([s,m.pathnameBase]))}return o}function Yk(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=Vue(t.path,t.caseSensitive,t.end),i=e.match(n);if(!i)return null;let s=i[0],o=s.replace(/(.)\/+$/,"$1"),l=i.slice(1);return{params:r.reduce((d,{paramName:u,isOptional:m},p)=>{if(u==="*"){let y=l[p]||"";o=s.slice(0,s.length-y.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 Vue(t,e=!1,n=!0){Kl(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let r=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(r.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function Gue(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Kl(!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 $u(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}var Wue=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Kue(t,e="/"){let{pathname:n,search:r="",hash:i=""}=typeof t=="string"?Yx(t):t,s;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?s=X8(n.substring(1),"/"):s=X8(n,e)):s=e,{pathname:s,search:Que(r),hash:Zue(i)}}function X8(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 oj(t,e,n,r){return`Cannot include a '${t}' character in a manually specified \`to.${e}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Yue(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function WL(t){let e=Yue(t);return e.map((n,r)=>r===e.length-1?n.pathname:n.pathnameBase)}function KL(t,e,n,r=!1){let i;typeof t=="string"?i=Yx(t):(i={...t},ya(!i.pathname||!i.pathname.includes("?"),oj("?","pathname","search",i)),ya(!i.pathname||!i.pathname.includes("#"),oj("#","pathname","hash",i)),ya(!i.search||!i.search.includes("#"),oj("#","search","hash",i)));let s=t===""||i.pathname==="",o=s?"/":i.pathname,l;if(o==null)l=n;else{let m=e.length-1;if(!r&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),m-=1;i.pathname=p.join("/")}l=m>=0?e[m]:"/"}let c=Kue(i,l),d=o&&o!=="/"&&o.endsWith("/"),u=(s||o===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}var Ru=t=>t.join("/").replace(/\/\/+/g,"/"),Xue=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),Que=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,Zue=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,Jue=class{constructor(t,e,n,r=!1){this.status=t,this.statusText=e||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function eme(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function tme(t){return t.map(e=>e.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var EX=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function DX(t,e){let n=t;if(typeof n!="string"||!Wue.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(EX)try{let s=new URL(window.location.href),o=n.startsWith("//")?new URL(s.protocol+n):new URL(n),l=$u(o.pathname,e);o.origin===s.origin&&l!=null?n=l+o.search+o.hash:i=!0}catch{Kl(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var FX=["POST","PUT","PATCH","DELETE"];new Set(FX);var nme=["GET",...FX];new Set(nme);var Xx=w.createContext(null);Xx.displayName="DataRouter";var vP=w.createContext(null);vP.displayName="DataRouterState";var rme=w.createContext(!1),RX=w.createContext({isTransitioning:!1});RX.displayName="ViewTransition";var ame=w.createContext(new Map);ame.displayName="Fetchers";var ime=w.createContext(null);ime.displayName="Await";var dl=w.createContext(null);dl.displayName="Navigation";var Nw=w.createContext(null);Nw.displayName="Location";var ac=w.createContext({outlet:null,matches:[],isDataRoute:!1});ac.displayName="Route";var YL=w.createContext(null);YL.displayName="RouteError";var LX="REACT_ROUTER_ERROR",sme="REDIRECT",ome="ROUTE_ERROR_RESPONSE";function lme(t){if(t.startsWith(`${LX}:${sme}:{`))try{let e=JSON.parse(t.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function cme(t){if(t.startsWith(`${LX}:${ome}:{`))try{let e=JSON.parse(t.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new Jue(e.status,e.statusText,e.data)}catch{}}function dme(t,{relative:e}={}){ya(Qx(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=w.useContext(dl),{hash:i,pathname:s,search:o}=Pw(t,{relative:e}),l=s;return n!=="/"&&(l=s==="/"?n:Ru([n,s])),r.createHref({pathname:l,search:o,hash:i})}function Qx(){return w.useContext(Nw)!=null}function Ic(){return ya(Qx(),"useLocation() may be used only in the context of a <Router> component."),w.useContext(Nw).location}var OX="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function IX(t){w.useContext(dl).static||w.useLayoutEffect(t)}function Eo(){let{isDataRoute:t}=w.useContext(ac);return t?kme():ume()}function ume(){ya(Qx(),"useNavigate() may be used only in the context of a <Router> component.");let t=w.useContext(Xx),{basename:e,navigator:n}=w.useContext(dl),{matches:r}=w.useContext(ac),{pathname:i}=Ic(),s=JSON.stringify(WL(r)),o=w.useRef(!1);return IX(()=>{o.current=!0}),w.useCallback((c,d={})=>{if(Kl(o.current,OX),!o.current)return;if(typeof c=="number"){n.go(c);return}let u=KL(c,JSON.parse(s),i,d.relative==="path");t==null&&e!=="/"&&(u.pathname=u.pathname==="/"?e:Ru([e,u.pathname])),(d.replace?n.replace:n.push)(u,d.state,d)},[e,n,s,i,t])}var zX=w.createContext(null);function Zx(){return w.useContext(zX)}function mme(t){let e=w.useContext(ac).outlet;return w.useMemo(()=>e&&w.createElement(zX.Provider,{value:t},e),[e,t])}function Cw(){let{matches:t}=w.useContext(ac),e=t[t.length-1];return e?e.params:{}}function Pw(t,{relative:e}={}){let{matches:n}=w.useContext(ac),{pathname:r}=Ic(),i=JSON.stringify(WL(n));return w.useMemo(()=>KL(t,JSON.parse(i),r,e==="path"),[t,i,r,e])}function hme(t,e){return UX(t,e)}function UX(t,e,n,r,i){ya(Qx(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=w.useContext(dl),{matches:o}=w.useContext(ac),l=o[o.length-1],c=l?l.params:{},d=l?l.pathname:"/",u=l?l.pathnameBase:"/",m=l&&l.route;{let _=m&&m.path||"";HX(d,!m||_.endsWith("*")||_.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${d}" (under <Route path="${_}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
  31. Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}/*`}">.`)}let p=Ic(),f;if(e){let _=typeof e=="string"?Yx(e):e;ya(u==="/"||_.pathname?.startsWith(u),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${u}" but pathname "${_.pathname}" was given in the \`location\` prop.`),f=_}else f=p;let y=f.pathname||"/",v=y;if(u!=="/"){let _=u.replace(/^\//,"").split("/");v="/"+y.replace(/^\//,"").split("/").slice(_.length).join("/")}let b=AX(t,{pathname:v});Kl(m||b!=null,`No routes matched location "${f.pathname}${f.search}${f.hash}" `),Kl(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 g=xme(b&&b.map(_=>Object.assign({},_,{params:Object.assign({},c,_.params),pathname:Ru([u,s.encodeLocation?s.encodeLocation(_.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?u:Ru([u,s.encodeLocation?s.encodeLocation(_.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathnameBase])})),o,n,r,i);return e&&g?w.createElement(Nw.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...f},navigationType:"POP"}},g):g}function pme(){let t=_me(),e=eme(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,r="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:r},s={padding:"2px 4px",backgroundColor:r},o=null;return console.error("Error handled by React Router default ErrorBoundary:",t),o=w.createElement(w.Fragment,null,w.createElement("p",null,"💿 Hey developer 👋"),w.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",w.createElement("code",{style:s},"ErrorBoundary")," or"," ",w.createElement("code",{style:s},"errorElement")," prop on your route.")),w.createElement(w.Fragment,null,w.createElement("h2",null,"Unexpected Application Error!"),w.createElement("h3",{style:{fontStyle:"italic"}},e),n?w.createElement("pre",{style:i},n):null,o)}var fme=w.createElement(pme,null),BX=class extends w.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,e){return e.location!==t.location||e.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:e.error,location:e.location,revalidation:t.revalidation||e.revalidation}}componentDidCatch(t,e){this.props.onError?this.props.onError(t,e):console.error("React Router caught the following error during render",t)}render(){let t=this.state.error;if(this.context&&typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){const n=cme(t.digest);n&&(t=n)}let e=t!==void 0?w.createElement(ac.Provider,{value:this.props.routeContext},w.createElement(YL.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?w.createElement(gme,{error:t},e):e}};BX.contextType=rme;var lj=new WeakMap;function gme({children:t,error:e}){let{basename:n}=w.useContext(dl);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let r=lme(e.digest);if(r){let i=lj.get(e);if(i)throw i;let s=DX(r.location,n);if(EX&&!lj.get(e))if(s.isExternal||r.reloadDocument)window.location.href=s.absoluteURL||s.to;else{const o=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(s.to,{replace:r.replace}));throw lj.set(e,o),o}return w.createElement("meta",{httpEquiv:"refresh",content:`0;url=${s.absoluteURL||s.to}`})}}return t}function bme({routeContext:t,match:e,children:n}){let r=w.useContext(Xx);return r&&r.static&&r.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=e.route.id),w.createElement(ac.Provider,{value:t},n)}function xme(t,e=[],n=null,r=null,i=null){if(t==null){if(!n)return null;if(n.errors)t=n.matches;else if(e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let s=t,o=n?.errors;if(o!=null){let u=s.findIndex(m=>m.route.id&&o?.[m.route.id]!==void 0);ya(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,y=m.route.loader&&!p.hasOwnProperty(m.route.id)&&(!f||f[m.route.id]===void 0);if(m.route.lazy||y){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}let d=n&&r?(u,m)=>{r(u,{location:n.location,params:n.matches?.[0]?.params??{},unstable_pattern:tme(n.matches),errorInfo:m})}:void 0;return s.reduceRight((u,m,p)=>{let f,y=!1,v=null,b=null;n&&(f=o&&m.route.id?o[m.route.id]:void 0,v=m.route.errorElement||fme,l&&(c<0&&p===0?(HX("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),y=!0,b=null):c===p&&(y=!0,b=m.route.hydrateFallbackElement||null)));let g=e.concat(s.slice(0,p+1)),_=()=>{let k;return f?k=v:y?k=b:m.route.Component?k=w.createElement(m.route.Component,null):m.route.element?k=m.route.element:k=u,w.createElement(bme,{match:m,routeContext:{outlet:u,matches:g,isDataRoute:n!=null},children:k})};return n&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?w.createElement(BX,{location:n.location,revalidation:n.revalidation,component:v,error:f,children:_(),routeContext:{outlet:null,matches:g,isDataRoute:!0},onError:d}):_()},null)}function XL(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function yme(t){let e=w.useContext(Xx);return ya(e,XL(t)),e}function vme(t){let e=w.useContext(vP);return ya(e,XL(t)),e}function wme(t){let e=w.useContext(ac);return ya(e,XL(t)),e}function QL(t){let e=wme(t),n=e.matches[e.matches.length-1];return ya(n.route.id,`${t} can only be used on routes that contain a unique "id"`),n.route.id}function Sme(){return QL("useRouteId")}function _me(){let t=w.useContext(YL),e=vme("useRouteError"),n=QL("useRouteError");return t!==void 0?t:e.errors?.[n]}function kme(){let{router:t}=yme("useNavigate"),e=QL("useNavigate"),n=w.useRef(!1);return IX(()=>{n.current=!0}),w.useCallback(async(i,s={})=>{Kl(n.current,OX),n.current&&(typeof i=="number"?await t.navigate(i):await t.navigate(i,{fromRouteId:e,...s}))},[t,e])}var Q8={};function HX(t,e,n){!e&&!Q8[t]&&(Q8[t]=!0,Kl(!1,n))}w.memo(Nme);function Nme({routes:t,future:e,state:n,onError:r}){return UX(t,void 0,n,r,e)}function gx({to:t,replace:e,state:n,relative:r}){ya(Qx(),"<Navigate> may be used only in the context of a <Router> component.");let{static:i}=w.useContext(dl);Kl(!i,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:s}=w.useContext(ac),{pathname:o}=Ic(),l=Eo(),c=KL(t,WL(s),o,r==="path"),d=JSON.stringify(c);return w.useEffect(()=>{l(JSON.parse(d),{replace:e,state:n,relative:r})},[l,d,r,e,n]),null}function qX(t){return mme(t.context)}function Mr(t){ya(!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 Cme({basename:t="/",children:e=null,location:n,navigationType:r="POP",navigator:i,static:s=!1,unstable_useTransitions:o}){ya(!Qx(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=t.replace(/^\/*/,"/"),c=w.useMemo(()=>({basename:l,navigator:i,static:s,unstable_useTransitions:o,future:{}}),[l,i,s,o]);typeof n=="string"&&(n=Yx(n));let{pathname:d="/",search:u="",hash:m="",state:p=null,key:f="default"}=n,y=w.useMemo(()=>{let v=$u(d,l);return v==null?null:{location:{pathname:v,search:u,hash:m,state:p,key:f},navigationType:r}},[l,d,u,m,p,f,r]);return Kl(y!=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.`),y==null?null:w.createElement(dl.Provider,{value:c},w.createElement(Nw.Provider,{children:e,value:y}))}function Pme({children:t,location:e}){return hme(P3(t),e)}function P3(t,e=[]){let n=[];return w.Children.forEach(t,(r,i)=>{if(!w.isValidElement(r))return;let s=[...e,i];if(r.type===w.Fragment){n.push.apply(n,P3(r.props.children,s));return}ya(r.type===Mr,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ya(!r.props.index||!r.props.children,"An index route cannot have child routes.");let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=P3(r.props.children,s)),n.push(o)}),n}var bk="get",xk="application/x-www-form-urlencoded";function wP(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function Tme(t){return wP(t)&&t.tagName.toLowerCase()==="button"}function Ame(t){return wP(t)&&t.tagName.toLowerCase()==="form"}function Mme(t){return wP(t)&&t.tagName.toLowerCase()==="input"}function jme(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function Eme(t,e){return t.button===0&&(!e||e==="_self")&&!jme(t)}function T3(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let r=t[n];return e.concat(Array.isArray(r)?r.map(i=>[n,i]):[[n,r]])},[]))}function Dme(t,e){let n=T3(t);return e&&e.forEach((r,i)=>{n.has(i)||e.getAll(i).forEach(s=>{n.append(i,s)})}),n}var C_=null;function Fme(){if(C_===null)try{new FormData(document.createElement("form"),0),C_=!1}catch{C_=!0}return C_}var Rme=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function cj(t){return t!=null&&!Rme.has(t)?(Kl(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${xk}"`),null):t}function Lme(t,e){let n,r,i,s,o;if(Ame(t)){let l=t.getAttribute("action");r=l?$u(l,e):null,n=t.getAttribute("method")||bk,i=cj(t.getAttribute("enctype"))||xk,s=new FormData(t)}else if(Tme(t)||Mme(t)&&(t.type==="submit"||t.type==="image")){let l=t.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=t.getAttribute("formaction")||l.getAttribute("action");if(r=c?$u(c,e):null,n=t.getAttribute("formmethod")||l.getAttribute("method")||bk,i=cj(t.getAttribute("formenctype"))||cj(l.getAttribute("enctype"))||xk,s=new FormData(l,t),!Fme()){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(wP(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=bk,r=null,i=xk,o=t}return s&&i==="text/plain"&&(o=s,s=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:s,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function ZL(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function Ome(t,e,n,r){let i=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return n?i.pathname.endsWith("/")?i.pathname=`${i.pathname}_.${r}`:i.pathname=`${i.pathname}.${r}`:i.pathname==="/"?i.pathname=`_root.${r}`:e&&$u(i.pathname,e)==="/"?i.pathname=`${e.replace(/\/$/,"")}/_root.${r}`:i.pathname=`${i.pathname.replace(/\/$/,"")}.${r}`,i}async function Ime(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 zme(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 Ume(t,e,n){let r=await Promise.all(t.map(async i=>{let s=e.routes[i.route.id];if(s){let o=await Ime(s,n);return o.links?o.links():[]}return[]}));return $me(r.flat(1).filter(zme).filter(i=>i.rel==="stylesheet"||i.rel==="preload").map(i=>i.rel==="stylesheet"?{...i,rel:"prefetch",as:"style"}:{...i,rel:"prefetch"}))}function Z8(t,e,n,r,i,s){let o=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>n[d].pathname!==c.pathname||n[d].route.path?.endsWith("*")&&n[d].params["*"]!==c.params["*"];return s==="assets"?e.filter((c,d)=>o(c,d)||l(c,d)):s==="data"?e.filter((c,d)=>{let u=r.routes[c.route.id];if(!u||!u.hasLoader)return!1;if(o(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let m=c.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(t,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof m=="boolean")return m}return!0}):[]}function Bme(t,e,{includeHydrateFallback:n}={}){return Hme(t.map(r=>{let i=e.routes[r.route.id];if(!i)return[];let s=[i.module];return i.clientActionModule&&(s=s.concat(i.clientActionModule)),i.clientLoaderModule&&(s=s.concat(i.clientLoaderModule)),n&&i.hydrateFallbackModule&&(s=s.concat(i.hydrateFallbackModule)),i.imports&&(s=s.concat(i.imports)),s}).flat(1))}function Hme(t){return[...new Set(t)]}function qme(t){let e={},n=Object.keys(t).sort();for(let r of n)e[r]=t[r];return e}function $me(t,e){let n=new Set;return new Set(e),t.reduce((r,i)=>{let s=JSON.stringify(qme(i));return n.has(s)||(n.add(s),r.push({key:s,link:i})),r},[])}function $X(){let t=w.useContext(Xx);return ZL(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function Vme(){let t=w.useContext(vP);return ZL(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var JL=w.createContext(void 0);JL.displayName="FrameworkContext";function VX(){let t=w.useContext(JL);return ZL(t,"You must render this element inside a <HydratedRouter> element"),t}function Gme(t,e){let n=w.useContext(JL),[r,i]=w.useState(!1),[s,o]=w.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:u,onTouchStart:m}=e,p=w.useRef(null);w.useEffect(()=>{if(t==="render"&&o(!0),t==="viewport"){let v=g=>{g.forEach(_=>{o(_.isIntersecting)})},b=new IntersectionObserver(v,{threshold:.5});return p.current&&b.observe(p.current),()=>{b.disconnect()}}},[t]),w.useEffect(()=>{if(r){let v=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(v)}}},[r]);let f=()=>{i(!0)},y=()=>{i(!1),o(!1)};return n?t!=="intent"?[s,p,{}]:[s,p,{onFocus:dv(l,f),onBlur:dv(c,y),onMouseEnter:dv(d,f),onMouseLeave:dv(u,y),onTouchStart:dv(m,f)}]:[!1,p,{}]}function dv(t,e){return n=>{t&&t(n),n.defaultPrevented||e(n)}}function Wme({page:t,...e}){let{router:n}=$X(),r=w.useMemo(()=>AX(n.routes,t,n.basename),[n.routes,t,n.basename]);return r?w.createElement(Yme,{page:t,matches:r,...e}):null}function Kme(t){let{manifest:e,routeModules:n}=VX(),[r,i]=w.useState([]);return w.useEffect(()=>{let s=!1;return Ume(t,e,n).then(o=>{s||i(o)}),()=>{s=!0}},[t,e,n]),r}function Yme({page:t,matches:e,...n}){let r=Ic(),{future:i,manifest:s,routeModules:o}=VX(),{basename:l}=$X(),{loaderData:c,matches:d}=Vme(),u=w.useMemo(()=>Z8(t,e,d,s,r,"data"),[t,e,d,s,r]),m=w.useMemo(()=>Z8(t,e,d,s,r,"assets"),[t,e,d,s,r]),p=w.useMemo(()=>{if(t===r.pathname+r.search+r.hash)return[];let v=new Set,b=!1;if(e.forEach(_=>{let k=s.routes[_.route.id];!k||!k.hasLoader||(!u.some(P=>P.route.id===_.route.id)&&_.route.id in c&&o[_.route.id]?.shouldRevalidate||k.hasClientLoader?b=!0:v.add(_.route.id))}),v.size===0)return[];let g=Ome(t,l,i.unstable_trailingSlashAwareDataRequests,"data");return b&&v.size>0&&g.searchParams.set("_routes",e.filter(_=>v.has(_.route.id)).map(_=>_.route.id).join(",")),[g.pathname+g.search]},[l,i.unstable_trailingSlashAwareDataRequests,c,r,s,u,e,t,o]),f=w.useMemo(()=>Bme(m,s),[m,s]),y=Kme(m);return w.createElement(w.Fragment,null,p.map(v=>w.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),f.map(v=>w.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),y.map(({key:v,link:b})=>w.createElement("link",{key:v,nonce:n.nonce,...b,crossOrigin:b.crossOrigin??n.crossOrigin})))}function Xme(...t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var Qme=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Qme&&(window.__reactRouterVersion="7.13.0")}catch{}function Zme({basename:t,children:e,unstable_useTransitions:n,window:r}){let i=w.useRef();i.current==null&&(i.current=Mue({window:r,v5Compat:!0}));let s=i.current,[o,l]=w.useState({action:s.action,location:s.location}),c=w.useCallback(d=>{n===!1?l(d):w.startTransition(()=>l(d))},[n]);return w.useLayoutEffect(()=>s.listen(c),[s,c]),w.createElement(Cme,{basename:t,children:e,location:o.location,navigationType:o.action,navigator:s,unstable_useTransitions:n})}var GX=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,vo=w.forwardRef(function({onClick:e,discover:n="render",prefetch:r="none",relative:i,reloadDocument:s,replace:o,state:l,target:c,to:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},y){let{basename:v,unstable_useTransitions:b}=w.useContext(dl),g=typeof d=="string"&&GX.test(d),_=DX(d,v);d=_.to;let k=dme(d,{relative:i}),[P,N,M]=Gme(r,f),A=the(d,{replace:o,state:l,target:c,preventScrollReset:u,relative:i,viewTransition:m,unstable_defaultShouldRevalidate:p,unstable_useTransitions:b});function T(F){e&&e(F),F.defaultPrevented||A(F)}let C=w.createElement("a",{...f,...M,href:_.absoluteURL||k,onClick:_.isExternal||s?e:T,ref:Xme(y,N),target:c,"data-discover":!g&&n==="render"?"true":void 0});return P&&!g?w.createElement(w.Fragment,null,C,w.createElement(Wme,{page:k})):C});vo.displayName="Link";var Gb=w.forwardRef(function({"aria-current":e="page",caseSensitive:n=!1,className:r="",end:i=!1,style:s,to:o,viewTransition:l,children:c,...d},u){let m=Pw(o,{relative:d.relative}),p=Ic(),f=w.useContext(vP),{navigator:y,basename:v}=w.useContext(dl),b=f!=null&&she(m)&&l===!0,g=y.encodeLocation?y.encodeLocation(m).pathname:m.pathname,_=p.pathname,k=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;n||(_=_.toLowerCase(),k=k?k.toLowerCase():null,g=g.toLowerCase()),k&&v&&(k=$u(k,v)||k);const P=g!=="/"&&g.endsWith("/")?g.length-1:g.length;let N=_===g||!i&&_.startsWith(g)&&_.charAt(P)==="/",M=k!=null&&(k===g||!i&&k.startsWith(g)&&k.charAt(g.length)==="/"),A={isActive:N,isPending:M,isTransitioning:b},T=N?e:void 0,C;typeof r=="function"?C=r(A):C=[r,N?"active":null,M?"pending":null,b?"transitioning":null].filter(Boolean).join(" ");let F=typeof s=="function"?s(A):s;return w.createElement(vo,{...d,"aria-current":T,className:C,ref:u,style:F,to:o,viewTransition:l},typeof c=="function"?c(A):c)});Gb.displayName="NavLink";var Jme=w.forwardRef(({discover:t="render",fetcherKey:e,navigate:n,reloadDocument:r,replace:i,state:s,method:o=bk,action:l,onSubmit:c,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},y)=>{let{unstable_useTransitions:v}=w.useContext(dl),b=ahe(),g=ihe(l,{relative:d}),_=o.toLowerCase()==="get"?"get":"post",k=typeof l=="string"&&GX.test(l),P=N=>{if(c&&c(N),N.defaultPrevented)return;N.preventDefault();let M=N.nativeEvent.submitter,A=M?.getAttribute("formmethod")||o,T=()=>b(M||N.currentTarget,{fetcherKey:e,method:A,navigate:n,replace:i,state:s,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p});v&&n!==!1?w.startTransition(()=>T()):T()};return w.createElement("form",{ref:y,method:_,action:g,onSubmit:r?c:P,...f,"data-discover":!k&&t==="render"?"true":void 0})});Jme.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 WX(t){let e=w.useContext(Xx);return ya(e,ehe(t)),e}function the(t,{target:e,replace:n,state:r,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l,unstable_useTransitions:c}={}){let d=Eo(),u=Ic(),m=Pw(t,{relative:s});return w.useCallback(p=>{if(Eme(p,e)){p.preventDefault();let f=n!==void 0?n:E0(u)===E0(m),y=()=>d(t,{replace:f,state:r,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l});c?w.startTransition(()=>y()):y()}},[u,d,m,n,r,e,t,i,s,o,l,c])}function eO(t){Kl(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let e=w.useRef(T3(t)),n=w.useRef(!1),r=Ic(),i=w.useMemo(()=>Dme(r.search,n.current?null:e.current),[r.search]),s=Eo(),o=w.useCallback((l,c)=>{const d=T3(typeof l=="function"?l(new URLSearchParams(i)):l);n.current=!0,s("?"+d,c)},[s,i]);return[i,o]}var nhe=0,rhe=()=>`__${String(++nhe)}__`;function ahe(){let{router:t}=WX("useSubmit"),{basename:e}=w.useContext(dl),n=Sme(),r=t.fetch,i=t.navigate;return w.useCallback(async(s,o={})=>{let{action:l,method:c,encType:d,formData:u,body:m}=Lme(s,e);if(o.navigate===!1){let p=o.fetcherKey||rhe();await r(p,n,o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:u,body:m,formMethod:o.method||c,formEncType:o.encType||d,flushSync:o.flushSync})}else await i(o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:u,body:m,formMethod:o.method||c,formEncType:o.encType||d,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[r,i,e,n])}function ihe(t,{relative:e}={}){let{basename:n}=w.useContext(dl),r=w.useContext(ac);ya(r,"useFormAction must be used inside a RouteContext");let[i]=r.matches.slice(-1),s={...Pw(t||".",{relative:e})},o=Ic();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:Ru([n,s.pathname])),E0(s)}function she(t,{relative:e}={}){let n=w.useContext(RX);ya(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=WX("useViewTransitionState"),i=Pw(t,{relative:e});if(!n.isTransitioning)return!1;let s=$u(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=$u(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Yk(i.pathname,o)!=null||Yk(i.pathname,s)!=null}var Cu=xX();const ohe=rc(Cu);var lg=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(){}},lhe={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},che=class{#t=lhe;#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)}},af=new che;function dhe(t){setTimeout(t,0)}var Ff=typeof window>"u"||"Deno"in globalThis;function Ts(){}function uhe(t,e){return typeof t=="function"?t(e):t}function A3(t){return typeof t=="number"&&t>=0&&t!==1/0}function KX(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Th(t,e){return typeof t=="function"?t(e):t}function jl(t,e){return typeof t=="function"?t(e):t}function J8(t,e){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:l}=t;if(o){if(r){if(e.queryHash!==tO(o,e.options))return!1}else if(!D0(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 e6(t,e){const{exact:n,status:r,predicate:i,mutationKey:s}=t;if(s){if(!e.options.mutationKey)return!1;if(n){if(Rf(e.options.mutationKey)!==Rf(s))return!1}else if(!D0(e.options.mutationKey,s))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function tO(t,e){return(e?.queryKeyHashFn||Rf)(t)}function Rf(t){return JSON.stringify(t,(e,n)=>M3(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function D0(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>D0(t[n],e[n])):!1}var mhe=Object.prototype.hasOwnProperty;function nO(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=t6(t)&&t6(e);if(!r&&!(M3(t)&&M3(e)))return e;const s=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),l=o.length,c=r?new Array(l):{};let d=0;for(let u=0;u<l;u++){const m=r?u:o[u],p=t[m],f=e[m];if(p===f){c[m]=p,(r?u<s:mhe.call(t,m))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){c[m]=f;continue}const y=nO(p,f,n+1);c[m]=y,y===p&&d++}return s===l&&d===s?t:c}function F0(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 t6(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function M3(t){if(!n6(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!n6(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function n6(t){return Object.prototype.toString.call(t)==="[object Object]"}function hhe(t){return new Promise(e=>{af.setTimeout(e,t)})}function j3(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?nO(t,e):e}function phe(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function fhe(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var rO=Symbol();function YX(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===rO?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function aO(t,e){return typeof t=="function"?t(...e):!!t}function ghe(t,e,n){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??=e(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),t}var bhe=class extends lg{#t;#e;#n;constructor(){super(),this.#n=t=>{if(!Ff&&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"}},iO=new bhe;function E3(){let t,e;const n=new Promise((i,s)=>{t=i,e=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},n.reject=i=>{r({status:"rejected",reason:i}),e(i)},n}var xhe=dhe;function yhe(){let t=[],e=0,n=l=>{l()},r=l=>{l()},i=xhe;const s=l=>{e?t.push(l):i(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&i(()=>{r(()=>{l.forEach(c=>{n(c)})})})};return{batch:l=>{let c;e++;try{c=l()}finally{e--,e||o()}return c},batchCalls:l=>(...c)=>{s(()=>{l(...c)})},schedule:s,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var Ua=yhe(),vhe=class extends lg{#t=!0;#e;#n;constructor(){super(),this.#n=t=>{if(!Ff&&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}},Xk=new vhe;function whe(t){return Math.min(1e3*2**t,3e4)}function XX(t){return(t??"online")==="online"?Xk.isOnline():!0}var D3=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function QX(t){let e=!1,n=0,r;const i=E3(),s=()=>i.status!=="pending",o=v=>{if(!s()){const b=new D3(v);p(b),t.onCancel?.(b)}},l=()=>{e=!0},c=()=>{e=!1},d=()=>iO.isFocused()&&(t.networkMode==="always"||Xk.isOnline())&&t.canRun(),u=()=>XX(t.networkMode)&&t.canRun(),m=v=>{s()||(r?.(),i.resolve(v))},p=v=>{s()||(r?.(),i.reject(v))},f=()=>new Promise(v=>{r=b=>{(s()||d())&&v(b)},t.onPause?.()}).then(()=>{r=void 0,s()||t.onContinue?.()}),y=()=>{if(s())return;let v;const b=n===0?t.initialPromise:void 0;try{v=b??t.fn()}catch(g){v=Promise.reject(g)}Promise.resolve(v).then(m).catch(g=>{if(s())return;const _=t.retry??(Ff?0:3),k=t.retryDelay??whe,P=typeof k=="function"?k(n,g):k,N=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,g);if(e||!N){p(g);return}n++,t.onFail?.(n,g),hhe(P).then(()=>d()?void 0:f()).then(()=>{e?p(g):y()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:c,canStart:u,start:()=>(u()?y():f().then(y),i)}}var ZX=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),A3(this.gcTime)&&(this.#t=af.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Ff?1/0:300*1e3))}clearGcTimeout(){this.#t&&(af.clearTimeout(this.#t),this.#t=void 0)}},She=class extends ZX{#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=a6(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=a6(this.options);e.data!==void 0&&(this.setState(r6(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){const n=j3(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(Ts).catch(Ts):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(t=>jl(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===rO||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Th(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:!KX(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(t&&this.setOptions(t),!this.options.queryFn){const l=this.observers.find(c=>c.options.queryFn);l&&this.setOptions(l.options)}const n=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{const l=YX(this.options,e),d=(()=>{const u={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(u),u})();return this.#o=!1,this.options.persister?this.options.persister(l,d,this):l(d)},o=(()=>{const l={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#s({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=QX({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof D3&&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 D3){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,...JX(n.data,this.options),fetchMeta:t.meta??null};case"success":const r={...n,...r6(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#e=t.manual?r:void 0,r;case"error":const i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=e(this.state),Ua.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function JX(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:XX(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function r6(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function a6(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var sO=class extends lg{constructor(t,e){super(),this.options=e,this.#t=t,this.#s=null,this.#o=E3(),this.bindMethods(),this.setOptions(e)}#t;#e=void 0;#n=void 0;#a=void 0;#r;#i;#o;#s;#p;#u;#m;#c;#d;#l;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),i6(this.#e,this.options)?this.#f():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return F3(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return F3(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 jl(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&&!F0(this.options,e)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&s6(this.#e,n,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#e!==n||jl(this.options.enabled,this.#e)!==jl(e.enabled,this.#e)||Th(this.options.staleTime,this.#e)!==Th(e.staleTime,this.#e))&&this.#g();const i=this.#b();r&&(this.#e!==n||jl(this.options.enabled,this.#e)!==jl(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 khe(this,n)&&(this.#a=n,this.#i=this.options,this.#r=this.#e.state),n}getCurrentResult(){return this.#a}trackResult(t,e){return new Proxy(t,{get:(n,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(t){this.#h.add(t)}getCurrentQuery(){return this.#e}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#t.defaultQueryOptions(t),n=this.#t.getQueryCache().build(this.#t,e);return n.fetch().then(()=>this.createResult(n,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#f(t){this.#S();let e=this.#e.fetch(this.options,t);return t?.throwOnError||(e=e.catch(Ts)),e}#g(){this.#v();const t=Th(this.options.staleTime,this.#e);if(Ff||this.#a.isStale||!A3(t))return;const n=KX(this.#a.dataUpdatedAt,t)+1;this.#c=af.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,!(Ff||jl(this.options.enabled,this.#e)===!1||!A3(this.#l)||this.#l===0)&&(this.#d=af.setInterval(()=>{(this.options.refetchIntervalInBackground||iO.isFocused())&&this.#f()},this.#l))}#y(){this.#g(),this.#x(this.#b())}#v(){this.#c&&(af.clearTimeout(this.#c),this.#c=void 0)}#w(){this.#d&&(af.clearInterval(this.#d),this.#d=void 0)}createResult(t,e){const n=this.#e,r=this.options,i=this.#a,s=this.#r,o=this.#i,c=t!==n?t.state:this.#n,{state:d}=t;let u={...d},m=!1,p;if(e._optimisticResults){const T=this.hasListeners(),C=!T&&i6(t,e),F=T&&s6(t,n,e,r);(C||F)&&(u={...u,...JX(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:v}=u;p=u.data;let b=!1;if(e.placeholderData!==void 0&&p===void 0&&v==="pending"){let T;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(T=i.data,b=!0):T=typeof e.placeholderData=="function"?e.placeholderData(this.#m?.state.data,this.#m):e.placeholderData,T!==void 0&&(v="success",p=j3(i?.data,T,e),m=!0)}if(e.select&&p!==void 0&&!b)if(i&&p===s?.data&&e.select===this.#p)p=this.#u;else try{this.#p=e.select,p=e.select(p),p=j3(i?.data,p,e),this.#u=p,this.#s=null}catch(T){this.#s=T}this.#s&&(f=this.#s,p=this.#u,y=Date.now(),v="error");const g=u.fetchStatus==="fetching",_=v==="pending",k=v==="error",P=_&&g,N=p!==void 0,A={status:v,fetchStatus:u.fetchStatus,isPending:_,isSuccess:v==="success",isError:k,isInitialLoading:P,isLoading:P,data:p,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:y,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:g,isRefetching:g&&!_,isLoadingError:k&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:k&&N,isStale:oO(t,e),refetch:this.refetch,promise:this.#o,isEnabled:jl(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const T=A.data!==void 0,C=A.status==="error"&&!T,F=X=>{C?X.reject(A.error):T&&X.resolve(A.data)},$=()=>{const X=this.#o=A.promise=E3();F(X)},I=this.#o;switch(I.status){case"pending":t.queryHash===n.queryHash&&F(I);break;case"fulfilled":(C||A.data!==I.value)&&$();break;case"rejected":(!C||A.error!==I.reason)&&$();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),F0(e,t))return;this.#a=e;const n=()=>{if(!t)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#h.size)return!0;const s=new Set(i??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(o=>{const l=o;return this.#a[l]!==t[l]&&s.has(l)})};this.#_({listeners:n()})}#S(){const t=this.#t.getQueryCache().build(this.#t,this.options);if(t===this.#e)return;const e=this.#e;this.#e=t,this.#n=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#_(t){Ua.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#a)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function _he(t,e){return jl(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function i6(t,e){return _he(t,e)||t.state.data!==void 0&&F3(t,e,e.refetchOnMount)}function F3(t,e,n){if(jl(e.enabled,t)!==!1&&Th(e.staleTime,t)!=="static"){const r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&oO(t,e)}return!1}function s6(t,e,n,r){return(t!==e||jl(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&oO(t,n)}function oO(t,e){return jl(e.enabled,t)!==!1&&t.isStaleByTime(Th(e.staleTime,t))}function khe(t,e){return!F0(t.getCurrentResult(),e)}function o6(t){return{onFetch:(e,n)=>{const r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,s=e.state.data?.pages||[],o=e.state.data?.pageParams||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let u=!1;const m=y=>{ghe(y,()=>e.signal,()=>u=!0)},p=YX(e.options,e.fetchOptions),f=async(y,v,b)=>{if(u)return Promise.reject();if(v==null&&y.pages.length)return Promise.resolve(y);const _=(()=>{const M={client:e.client,queryKey:e.queryKey,pageParam:v,direction:b?"backward":"forward",meta:e.options.meta};return m(M),M})(),k=await p(_),{maxPages:P}=e.options,N=b?fhe:phe;return{pages:N(y.pages,k,P),pageParams:N(y.pageParams,v,P)}};if(i&&s.length){const y=i==="backward",v=y?Nhe:l6,b={pages:s,pageParams:o},g=v(r,b);l=await f(b,g,y)}else{const y=t??s.length;do{const v=c===0?o[0]??r.initialPageParam:l6(r,l);if(c>0&&v==null)break;l=await f(l,v),c++}while(c<y)}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 l6(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function Nhe(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}var Che=class extends ZX{#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||eQ(),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=QX({fn:()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),onFail:(s,o)=>{this.#r({type:"failed",failureCount:s,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#a.canStart();try{if(r)e();else{this.#r({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,n);const o=await this.options.onMutate?.(t,n);o!==this.state.context&&this.#r({type:"pending",context:o,variables:t,isPaused:i})}const s=await this.#a.start();return await this.#n.config.onSuccess?.(s,t,this.state.context,this,n),await this.options.onSuccess?.(s,t,this.state.context,n),await this.#n.config.onSettled?.(s,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(s,null,t,this.state.context,n),this.#r({type:"success",data:s}),s}catch(s){try{await this.#n.config.onError?.(s,t,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(s,t,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#n.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,s,t,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:s}),s}finally{this.#n.runNext(this)}}#r(t){const e=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=e(this.state),Ua.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function eQ(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Phe=class extends lg{constructor(t={}){super(),this.config=t,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(t,e,n){const r=new Che({client:t,mutationCache:this,mutationId:++this.#n,options:t.defaultMutationOptions(e),state:n});return this.add(r),r}add(t){this.#t.add(t);const e=P_(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=P_(t);if(typeof e=="string"){const n=this.#e.get(e);if(n)if(n.length>1){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}else n[0]===t&&this.#e.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){const e=P_(t);if(typeof e=="string"){const r=this.#e.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){const e=P_(t);return typeof e=="string"?this.#e.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ua.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=>e6(e,n))}findAll(t={}){return this.getAll().filter(e=>e6(t,e))}notify(t){Ua.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){const t=this.getAll().filter(e=>e.state.isPaused);return Ua.batch(()=>Promise.all(t.map(e=>e.continue().catch(Ts))))}};function P_(t){return t.options.scope?.id}var The=class extends lg{#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),F0(this.options,n)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&Rf(n.mutationKey)!==Rf(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??eQ();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){Ua.batch(()=>{if(this.#a&&this.hasListeners()){const n=this.#e.variables,r=this.#e.context,i={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,n,r,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(e.data,null,n,r,i)}catch(s){Promise.reject(s)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,n,r,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(void 0,e.error,n,r,i)}catch(s){Promise.reject(s)}}}this.listeners.forEach(n=>{n(this.#e)})})}};function c6(t,e){const n=new Set(e);return t.filter(r=>!n.has(r))}function Ahe(t,e,n){const r=t.slice(0);return r[e]=n,r}var Mhe=class extends lg{#t;#e;#n;#a;#r;#i;#o;#s;#p;#u=[];constructor(t,e,n){super(),this.#t=t,this.#a=n,this.#n=[],this.#r=[],this.#e=[],this.setQueries(e)}onSubscribe(){this.listeners.size===1&&this.#r.forEach(t=>{t.subscribe(e=>{this.#l(t,e)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#r.forEach(t=>{t.destroy()})}setQueries(t,e){this.#n=t,this.#a=e,Ua.batch(()=>{const n=this.#r,r=this.#d(this.#n);r.forEach(u=>u.observer.setOptions(u.defaultedQueryOptions));const i=r.map(u=>u.observer),s=i.map(u=>u.getCurrentResult()),o=n.length!==i.length,l=i.some((u,m)=>u!==n[m]),c=o||l,d=c?!0:s.some((u,m)=>{const p=this.#e[m];return!p||!F0(u,p)});!c&&!d||(c&&(this.#u=r,this.#r=i),this.#e=s,this.hasListeners()&&(c&&(c6(n,i).forEach(u=>{u.destroy()}),c6(i,n).forEach(u=>{u.subscribe(m=>{this.#l(u,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#r.map(t=>t.getCurrentQuery())}getObservers(){return this.#r}getOptimisticResult(t,e){const n=this.#d(t),r=n.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions)),i=n.map(s=>s.defaultedQueryOptions.queryHash);return[r,s=>this.#c(s??r,e,i),()=>this.#m(r,n)]}#m(t,e){return e.map((n,r)=>{const i=t[r];return n.defaultedQueryOptions.notifyOnChangeProps?i:n.observer.trackResult(i,s=>{e.forEach(o=>{o.observer.trackProp(s)})})})}#c(t,e,n){if(e){const r=this.#p,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((s,o)=>s!==r[o]));return(!this.#i||this.#e!==this.#s||i||e!==this.#o)&&(this.#o=e,this.#s=this.#e,n!==void 0&&(this.#p=n),this.#i=nO(this.#i,e(t))),this.#i}return t}#d(t){const e=new Map;this.#r.forEach(r=>{const i=r.options.queryHash;if(!i)return;const s=e.get(i);s?s.push(r):e.set(i,[r])});const n=[];return t.forEach(r=>{const i=this.#t.defaultQueryOptions(r),o=e.get(i.queryHash)?.shift()??new sO(this.#t,i);n.push({defaultedQueryOptions:i,observer:o})}),n}#l(t,e){const n=this.#r.indexOf(t);n!==-1&&(this.#e=Ahe(this.#e,n,e),this.#h())}#h(){if(this.hasListeners()){const t=this.#i,e=this.#m(this.#e,this.#u),n=this.#c(e,this.#a?.combine);t!==n&&Ua.batch(()=>{this.listeners.forEach(r=>{r(this.#e)})})}}},jhe=class extends lg{constructor(t={}){super(),this.config=t,this.#t=new Map}#t;build(t,e,n){const r=e.queryKey,i=e.queryHash??tO(r,e);let s=this.get(i);return s||(s=new She({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:n,defaultOptions:t.getQueryDefaults(r)}),this.add(s)),s}add(t){this.#t.has(t.queryHash)||(this.#t.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const e=this.#t.get(t.queryHash);e&&(t.destroy(),e===t&&this.#t.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ua.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=>J8(e,n))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter(n=>J8(t,n)):e}notify(t){Ua.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){Ua.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ua.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ehe=class{#t;#e;#n;#a;#r;#i;#o;#s;constructor(t={}){this.#t=t.queryCache||new jhe,this.#e=t.mutationCache||new Phe,this.#n=t.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=iO.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Xk.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(t){return this.#t.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#e.findAll({...t,status:"pending"}).length}getQueryData(t){const e=this.defaultQueryOptions({queryKey:t});return this.#t.get(e.queryHash)?.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=this.#t.build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(Th(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#t.findAll(t).map(({queryKey:e,state:n})=>{const r=n.data;return[e,r]})}setQueryData(t,e,n){const r=this.defaultQueryOptions({queryKey:t}),s=this.#t.get(r.queryHash)?.state.data,o=uhe(e,s);if(o!==void 0)return this.#t.build(this,r).setData(o,{...n,manual:!0})}setQueriesData(t,e,n){return Ua.batch(()=>this.#t.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){const e=this.defaultQueryOptions({queryKey:t});return this.#t.get(e.queryHash)?.state}removeQueries(t){const e=this.#t;Ua.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=this.#t;return Ua.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=Ua.batch(()=>this.#t.findAll(t).map(i=>i.cancel(n)));return Promise.all(r).then(Ts).catch(Ts)}invalidateQueries(t,e={}){return Ua.batch(()=>(this.#t.findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=Ua.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(Ts)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(Ts)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=this.#t.build(this,e);return n.isStaleByTime(Th(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Ts).catch(Ts)}fetchInfiniteQuery(t){return t.behavior=o6(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Ts).catch(Ts)}ensureInfiniteQueryData(t){return t.behavior=o6(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Xk.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(Rf(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#a.values()],n={};return e.forEach(r=>{D0(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){this.#r.set(Rf(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#r.values()],n={};return e.forEach(r=>{D0(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...this.#n.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=tO(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===rO&&(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()}},tQ=w.createContext(void 0),mn=t=>{const e=w.useContext(tQ);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Dhe=({client:t,children:e})=>(w.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),a.jsx(tQ.Provider,{value:t,children:e})),nQ=w.createContext(!1),rQ=()=>w.useContext(nQ);nQ.Provider;function Fhe(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Rhe=w.createContext(Fhe()),aQ=()=>w.useContext(Rhe),iQ=(t,e,n)=>{const r=n?.state.error&&typeof t.throwOnError=="function"?aO(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},sQ=t=>{w.useEffect(()=>{t.clearReset()},[t])},oQ=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||aO(n,[t.error,r])),lQ=t=>{if(t.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},cQ=(t,e)=>t.isLoading&&t.isFetching&&!e,R3=(t,e)=>t?.suspense&&e.isPending,Qk=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function ep({queries:t,...e},n){const r=mn(),i=rQ(),s=aQ(),o=w.useMemo(()=>t.map(v=>{const b=r.defaultQueryOptions(v);return b._optimisticResults=i?"isRestoring":"optimistic",b}),[t,r,i]);o.forEach(v=>{lQ(v);const b=r.getQueryCache().get(v.queryHash);iQ(v,s,b)}),sQ(s);const[l]=w.useState(()=>new Mhe(r,o,e)),[c,d,u]=l.getOptimisticResult(o,e.combine),m=!i&&e.subscribed!==!1;w.useSyncExternalStore(w.useCallback(v=>m?l.subscribe(Ua.batchCalls(v)):Ts,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),w.useEffect(()=>{l.setQueries(o,e)},[o,e,l]);const f=c.some((v,b)=>R3(o[b],v))?c.flatMap((v,b)=>{const g=o[b];if(g){const _=new sO(r,g);if(R3(g,v))return Qk(g,_,s);cQ(v,i)&&Qk(g,_,s)}return[]}):[];if(f.length>0)throw Promise.all(f);const y=c.find((v,b)=>{const g=o[b];return g&&oQ({result:v,errorResetBoundary:s,throwOnError:g.throwOnError,query:r.getQueryCache().get(g.queryHash),suspense:g.suspense})});if(y?.error)throw y.error;return d(u())}function Lhe(t,e,n){const r=rQ(),i=aQ(),s=mn(),o=s.defaultQueryOptions(t);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=s.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",lQ(o),iQ(o,i,l),sQ(i);const c=!s.getQueryCache().get(o.queryHash),[d]=w.useState(()=>new e(s,o)),u=d.getOptimisticResult(o),m=!r&&t.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(p=>{const f=m?d.subscribe(Ua.batchCalls(p)):Ts;return d.updateResult(),f},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),w.useEffect(()=>{d.setOptions(o)},[o,d]),R3(o,u))throw Qk(o,d,i);if(oQ({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&&!Ff&&cQ(u,r)&&(c?Qk(o,d,i):l?.promise)?.catch(Ts).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?u:d.trackResult(u)}function et(t,e){return Lhe(t,sO)}function lt(t,e){const n=mn(),[r]=w.useState(()=>new The(n,t));w.useEffect(()=>{r.setOptions(t)},[r,t]);const i=w.useSyncExternalStore(w.useCallback(o=>r.subscribe(Ua.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),s=w.useCallback((o,l)=>{r.mutate(o,l).catch(Ts)},[r]);if(i.error&&aO(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:s,mutateAsync:i.mutate}}const Ohe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ihe=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase()),d6=t=>{const e=Ihe(t);return e.charAt(0).toUpperCase()+e.slice(1)},dQ=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim(),zhe=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var Uhe={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 Bhe=w.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i="",children:s,iconNode:o,...l},c)=>w.createElement("svg",{ref:c,...Uhe,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:dQ("lucide",i),...!s&&!zhe(l)&&{"aria-hidden":"true"},...l},[...o.map(([d,u])=>w.createElement(d,u)),...Array.isArray(s)?s:[s]]));const it=(t,e)=>{const n=w.forwardRef(({className:r,...i},s)=>w.createElement(Bhe,{ref:s,iconNode:e,className:dQ(`lucide-${Ohe(d6(t))}`,`lucide-${t}`,r),...i}));return n.displayName=d6(t),n};const Hhe=[["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"}]],qhe=it("air-vent",Hhe);const $he=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Qs=it("archive",$he);const Vhe=[["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"}]],Ghe=it("arrow-down-wide-narrow",Vhe);const Whe=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],bx=it("arrow-down",Whe);const Khe=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],uQ=it("arrow-left",Khe);const Yhe=[["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"}]],L3=it("arrow-right-left",Yhe);const Xhe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],O3=it("arrow-right",Xhe);const Qhe=[["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"}]],lO=it("arrow-up-down",Qhe);const Zhe=[["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"}]],Jhe=it("arrow-up-narrow-wide",Zhe);const epe=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Lf=it("arrow-up",epe);const tpe=[["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"}]],npe=it("beaker",tpe);const rpe=[["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"}]],ape=it("bell-off",rpe);const ipe=[["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"}]],Ah=it("bell",ipe);const spe=[["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"}]],ope=it("bold",spe);const lpe=[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]],cpe=it("book",lpe);const dpe=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],upe=it("bookmark",dpe);const mpe=[["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=it("box",mpe);const hpe=[["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"}]],mQ=it("briefcase",hpe);const ppe=[["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"}]],xx=it("bug",ppe);const fpe=[["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"}]],cO=it("cable",fpe);const gpe=[["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"}]],bpe=it("calculator",gpe);const xpe=[["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"}]],ype=it("calendar-days",xpe);const vpe=[["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"}]],Wr=it("calendar",vpe);const wpe=[["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"}]],yx=it("camera",wpe);const Spe=[["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"}]],_pe=it("chart-column",Spe);const kpe=[["path",{d:"M6 5h12",key:"fvfigv"}],["path",{d:"M4 12h10",key:"oujl3d"}],["path",{d:"M12 19h8",key:"baeox8"}]],Npe=it("chart-no-axes-gantt",kpe);const Cpe=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Kr=it("check",Cpe);const Ppe=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Fn=it("chevron-down",Ppe);const Tpe=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Va=it("chevron-right",Tpe);const Ape=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],ol=it("chevron-left",Ape);const Mpe=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Yl=it("chevron-up",Mpe);const jpe=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],dO=it("chevrons-left",jpe);const Epe=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],uO=it("chevrons-right",Epe);const Dpe=[["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"}]],qa=it("circle-alert",Dpe);const Fpe=[["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"}]],dj=it("circle-arrow-up",Fpe);const Rpe=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],fr=it("circle-check-big",Rpe);const Lpe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Cc=it("circle-check",Lpe);const Ope=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Ipe=it("circle-dot",Ope);const zpe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Upe=it("circle-stop",zpe);const Bpe=[["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"}]],$a=it("circle-x",Bpe);const Hpe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],R0=it("circle",Hpe);const qpe=[["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"}]],$pe=it("clipboard-list",qpe);const Vpe=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],rr=it("clock",Vpe);const Gpe=[["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"}]],Wpe=it("cloud-off",Gpe);const Kpe=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Jx=it("cloud",Kpe);const Ype=[["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"}]],Xpe=it("code-xml",Ype);const Qpe=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],ey=it("code",Qpe);const Zpe=[["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"}]],Jpe=it("coffee",Zpe);const efe=[["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"}]],tfe=it("coins",efe);const nfe=[["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"}]],rfe=it("cog",nfe);const afe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],ife=it("columns-2",afe);const sfe=[["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"}]],ofe=it("compass",sfe);const lfe=[["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"}]],Mo=it("copy",lfe);const cfe=[["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"}]],T_=it("cpu",cfe);const dfe=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]],ufe=it("cylinder",dfe);const mfe=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Ul=it("database",mfe);const hfe=[["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"}]],pfe=it("disc-3",hfe);const ffe=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],Zk=it("dollar-sign",ffe);const gfe=[["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"}]],va=it("download",gfe);const bfe=[["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"}]],SP=it("droplet",bfe);const xfe=[["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"}]],mO=it("droplets",xfe);const yfe=[["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"}]],Mh=it("ellipsis-vertical",yfe);const vfe=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]],uj=it("equal",vfe);const wfe=[["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"}]],Sfe=it("eraser",wfe);const _fe=[["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"}]],sa=it("external-link",_fe);const kfe=[["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"}]],Tw=it("eye-off",kfe);const Nfe=[["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"}]],Dc=it("eye",Nfe);const Cfe=[["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"}]],hQ=it("fan",Cfe);const Pfe=[["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"}]],yf=it("file-box",Pfe);const Tfe=[["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"}]],Jk=it("file-code",Tfe);const Afe=[["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"}]],Mfe=it("file-exclamation-point",Afe);const jfe=[["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"}]],eN=it("file-spreadsheet",jfe);const Efe=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ms=it("file-text",Efe);const Dfe=[["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"}]],_P=it("file",Dfe);const Ffe=[["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"}]],jh=it("film",Ffe);const Rfe=[["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"}]],Qp=it("flame",Rfe);const Lfe=[["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"}]],js=it("folder-kanban",Lfe);const Ofe=[["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"}]],Fc=it("folder-open",Ofe);const Ife=[["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"}]],zfe=it("folder-plus",Ife);const Ufe=[["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"}]],tN=it("folder-symlink",Ufe);const Bfe=[["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"}]],Hfe=it("folder-tree",Bfe);const qfe=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],pQ=it("folder",qfe);const $fe=[["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"}]],Vfe=it("fullscreen",$fe);const Gfe=[["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"}]],kP=it("funnel",Gfe);const Wfe=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Aw=it("gauge",Wfe);const Kfe=[["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"}]],Yfe=it("gift",Kfe);const Xfe=[["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"}]],fQ=it("git-branch",Xfe);const Qfe=[["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"}]],tx=it("git-compare",Qfe);const Zfe=[["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"}]],I3=it("github",Zfe);const Jfe=[["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"}]],yd=it("globe",Jfe);const ege=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],Eh=it("grip-vertical",ege);const tge=[["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"}]],nge=it("group",tge);const rge=[["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"}]],gQ=it("hand",rge);const age=[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]],ty=it("hard-drive",age);const ige=[["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"}]],sge=it("hash",ige);const oge=[["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"}]],lge=it("headphones",oge);const cge=[["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"}]],dge=it("heart",cge);const uge=[["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"}]],L0=it("history",uge);const mge=[["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"}]],Mw=it("house",mge);const hge=[["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"}]],Vu=it("image",hge);const pge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Ks=it("info",pge);const fge=[["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"}]],gge=it("italic",fge);const bge=[["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"}]],El=it("key",bge);const xge=[["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"}]],z3=it("keyboard",xge);const yge=[["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"}]],ea=it("layers",yge);const vge=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],jw=it("layout-grid",vge);const wge=[["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"}]],Sge=it("link-2-off",wge);const _ge=[["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"}]],Lu=it("link-2",_ge);const kge=[["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"}]],ny=it("link",kge);const Nge=[["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"}]],nN=it("list-ordered",Nge);const Cge=[["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"}]],U3=it("list-todo",Cge);const Pge=[["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"}]],Ew=it("list",Pge);const Tge=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ct=it("loader-circle",Tge);const Age=[["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"}]],s0=it("lock-open",Age);const Mge=[["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"}]],ld=it("lock",Mge);const jge=[["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"}]],u6=it("log-in",jge);const Ege=[["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"}]],B3=it("log-out",Ege);const Dge=[["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"}]],vx=it("mail",Dge);const Fge=[["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"}]],Rge=it("map",Fge);const Lge=[["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"}]],NP=it("maximize-2",Lge);const Oge=[["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"}]],Ige=it("maximize",Oge);const zge=[["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"}]],Uge=it("memory-stick",zge);const Bge=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Hge=it("menu",Bge);const qge=[["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"}]],hO=it("minimize-2",qge);const $ge=[["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"}]],bQ=it("minimize",$ge);const Vge=[["path",{d:"M5 12h14",key:"1ays0h"}]],rN=it("minus",Vge);const Gge=[["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"}]],xQ=it("monitor",Gge);const Wge=[["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"}]],aN=it("moon",Wge);const Kge=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Yge=it("move-right",Kge);const Xge=[["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"}]],H3=it("music",Xge);const Qge=[["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"}]],Na=it("package",Qge);const Zge=[["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"}]],Dw=it("palette",Zge);const Jge=[["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"}]],Fw=it("pause",Jge);const ebe=[["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"}]],Of=it("pen-line",ebe);const tbe=[["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"}]],xh=it("pen",tbe);const nbe=[["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"}]],Za=it("pencil",nbe);const rbe=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],abe=it("phone",rbe);const ibe=[["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"}]],Ds=it("play",ibe);const sbe=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],ql=it("plug",sbe);const obe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ur=it("plus",obe);const lbe=[["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"}]],Rw=it("power-off",lbe);const cbe=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],im=it("power",cbe);const dbe=[["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"}]],Pr=it("printer",dbe);const ube=[["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"}]],yQ=it("qr-code",ube);const mbe=[["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"}]],pO=it("radio",mbe);const hbe=[["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"}]],vr=it("refresh-cw",hbe);const pbe=[["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"}]],jo=it("rotate-ccw",pbe);const fbe=[["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"}]],q3=it("rotate-cw",fbe);const gbe=[["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"}]],bbe=it("ruler",gbe);const xbe=[["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"}]],cs=it("save",xbe);const ybe=[["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"}]],vbe=it("scale",ybe);const wbe=[["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"}]],iN=it("scan-search",wbe);const Sbe=[["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"}]],_be=it("scissors",Sbe);const kbe=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Sr=it("search",kbe);const Nbe=[["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"}]],Lw=it("send",Nbe);const Cbe=[["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"}]],Vp=it("server",Cbe);const Pbe=[["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"}]],Nd=it("settings-2",Pbe);const Tbe=[["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"}]],Ow=it("settings",Tbe);const Abe=[["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"}]],Mbe=it("shield-alert",Abe);const jbe=[["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"}]],Wb=it("shield",jbe);const Ebe=[["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"}]],vQ=it("shopping-cart",Ebe);const Dbe=[["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"}]],wQ=it("signal",Dbe);const Fbe=[["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"}]],Rbe=it("skip-back",Fbe);const Lbe=[["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"}]],CP=it("skip-forward",Lbe);const Obe=[["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"}]],m6=it("sliders-vertical",Obe);const Ibe=[["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"}]],wx=it("sparkles",Ibe);const zbe=[["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"}]],us=it("square-check-big",zbe);const Ube=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]],Bbe=it("square-minus",Ube);const Hbe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],eo=it("square",Hbe);const qbe=[["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"}]],If=it("star",qbe);const $be=[["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"}]],SQ=it("sticky-note",$be);const Vbe=[["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"}]],h6=it("sun",Vbe);const Gbe=[["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"}]],Wbe=it("table-properties",Gbe);const Kbe=[["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"}]],Gu=it("tag",Kbe);const Ybe=[["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"}]],_Q=it("target",Ybe);const Xbe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],kQ=it("terminal",Xbe);const Qbe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],Zbe=it("text-align-center",Qbe);const Jbe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],exe=it("text-align-end",Jbe);const txe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],nxe=it("text-align-start",txe);const rxe=[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]],PP=it("thermometer",rxe);const axe=[["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"}]],Pc=it("timer",axe);const ixe=[["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"}]],un=it("trash-2",ixe);const sxe=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],fO=it("trending-down",sxe);const oxe=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],$3=it("trending-up",oxe);const lxe=[["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"}]],Ln=it("triangle-alert",lxe);const cxe=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],dxe=it("underline",cxe);const uxe=[["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"}]],qh=it("unlink",uxe);const mxe=[["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"}]],Ca=it("upload",mxe);const hxe=[["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"}]],Wu=it("user",hxe);const pxe=[["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"}]],_u=it("users",pxe);const fxe=[["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"}]],gO=it("video",fxe);const gxe=[["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"}]],bxe=it("volume-2",gxe);const xxe=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],yxe=it("volume-x",xxe);const vxe=[["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"}]],NQ=it("wand-sparkles",vxe);const wxe=[["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"}]],CQ=it("weight",wxe);const Sxe=[["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"}]],Ku=it("wifi-off",Sxe);const _xe=[["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"}]],vf=it("wifi",_xe);const kxe=[["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"}]],PQ=it("wind",kxe);const Nxe=[["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"}]],zf=it("wrench",Nxe);const Cxe=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Bt=it("x",Cxe);const Pxe=[["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"}]],bO=it("zoom-in",Pxe);const Txe=[["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"}]],Xl=it("zap",Txe);const Axe=[["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"}]],xO=it("zoom-out",Axe),wn="/api/v1";let Pn=localStorage.getItem("auth_token");function Ib(t){Pn=t,t?localStorage.setItem("auth_token",t):localStorage.removeItem("auth_token")}function Yu(){return Pn}let sN=null;function p6(t){sN=t}function Mxe(){return sN}function Ra(t){if(!sN)return t;const e=t.includes("?")?"&":"?";return`${t}${e}token=${encodeURIComponent(sN)}`}function Gp(t){if(!t)return null;const e=t.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);if(e)try{return decodeURIComponent(e[1])}catch{}return t.match(/filename="?([^";\n]+)"?/)?.[1]||null}async function Oe(t,e={}){const n={"Content-Type":"application/json",...e.headers};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}${t}`,{...e,cache:"no-store",headers:n});if(!r.ok){const o=(await r.json().catch(()=>({}))).detail,l=typeof o=="string"?o:o?JSON.stringify(o):`HTTP ${r.status}`;throw r.status===401&&["Could not validate credentials","Token has expired","User not found or inactive","Invalid API key","API key has expired"].some(d=>l.includes(d))&&Ib(null),new Error(l)}const i=r.headers.get("content-length");if(!(r.status===204||i==="0"))return await r.json()}const pe={getAuthStatus:()=>Oe("/auth/status"),setupAuth:t=>Oe("/auth/setup",{method:"POST",body:JSON.stringify(t)}),login:t=>Oe("/auth/login",{method:"POST",body:JSON.stringify(t)}),logout:()=>Oe("/auth/logout",{method:"POST"}),getCurrentUser:()=>Oe("/auth/me"),disableAuth:()=>Oe("/auth/disable",{method:"POST"}),testSMTP:t=>Oe("/auth/smtp/test",{method:"POST",body:JSON.stringify(t)}),getSMTPSettings:()=>Oe("/auth/smtp"),saveSMTPSettings:t=>Oe("/auth/smtp",{method:"POST",body:JSON.stringify(t)}),enableAdvancedAuth:()=>Oe("/auth/advanced-auth/enable",{method:"POST"}),disableAdvancedAuth:()=>Oe("/auth/advanced-auth/disable",{method:"POST"}),getAdvancedAuthStatus:()=>Oe("/auth/advanced-auth/status"),getLDAPStatus:()=>Oe("/auth/ldap/status"),testLDAP:()=>Oe("/auth/ldap/test",{method:"POST"}),forgotPassword:t=>Oe("/auth/forgot-password",{method:"POST",body:JSON.stringify(t)}),resetUserPassword:t=>Oe("/auth/reset-password",{method:"POST",body:JSON.stringify(t)}),getUsers:()=>Oe("/users/"),getUser:t=>Oe(`/users/${t}`),createUser:t=>Oe("/users/",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>Oe(`/users/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:(t,e=!1)=>Oe(`/users/${t}?delete_items=${e}`,{method:"DELETE"}),getUserItemsCount:t=>Oe(`/users/${t}/items-count`),changePassword:(t,e)=>Oe("/users/me/change-password",{method:"POST",body:JSON.stringify({current_password:t,new_password:e})}),getUserEmailPreferences:()=>Oe("/user-notifications/preferences"),updateUserEmailPreferences:t=>Oe("/user-notifications/preferences",{method:"PUT",body:JSON.stringify(t)}),getPermissions:()=>Oe("/groups/permissions"),getGroups:()=>Oe("/groups/"),getGroup:t=>Oe(`/groups/${t}`),createGroup:t=>Oe("/groups/",{method:"POST",body:JSON.stringify(t)}),updateGroup:(t,e)=>Oe(`/groups/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteGroup:t=>Oe(`/groups/${t}`,{method:"DELETE"}),addUserToGroup:(t,e)=>Oe(`/groups/${t}/users/${e}`,{method:"POST"}),removeUserFromGroup:(t,e)=>Oe(`/groups/${t}/users/${e}`,{method:"DELETE"}),getPrinters:()=>Oe("/printers/"),getPrinter:t=>Oe(`/printers/${t}`),createPrinter:t=>Oe("/printers/",{method:"POST",body:JSON.stringify(t)}),updatePrinter:(t,e)=>Oe(`/printers/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deletePrinter:(t,e=!0)=>Oe(`/printers/${t}?delete_archives=${e}`,{method:"DELETE"}),getDeveloperModeWarnings:()=>Oe("/printers/developer-mode-warnings"),getAvailableFilaments:(t,e)=>{const n=new URLSearchParams({model:t});return e&&n.set("location",e),Oe(`/printers/available-filaments?${n}`)},getPrinterStatus:t=>Oe(`/printers/${t}/status`),refreshPrinterStatus:t=>Oe(`/printers/${t}/refresh-status`,{method:"POST"}),connectPrinter:t=>Oe(`/printers/${t}/connect`,{method:"POST"}),disconnectPrinter:t=>Oe(`/printers/${t}/disconnect`,{method:"POST"}),testExternalCamera:(t,e,n)=>Oe(`/printers/${t}/camera/external/test?url=${encodeURIComponent(e)}&camera_type=${encodeURIComponent(n)}`,{method:"POST"}),stopPrint:t=>Oe(`/printers/${t}/print/stop`,{method:"POST"}),pausePrint:t=>Oe(`/printers/${t}/print/pause`,{method:"POST"}),resumePrint:t=>Oe(`/printers/${t}/print/resume`,{method:"POST"}),clearPlate:t=>Oe(`/printers/${t}/clear-plate`,{method:"POST"}),getCurrentPrintUser:t=>Oe(`/printers/${t}/current-print-user`),setPrintSpeed:(t,e)=>Oe(`/printers/${t}/print-speed?mode=${e}`,{method:"POST"}),setChamberLight:(t,e)=>Oe(`/printers/${t}/chamber-light?on=${e}`,{method:"POST"}),startDrying:(t,e,n,r,i="",s=!1)=>Oe(`/printers/${t}/drying/start?ams_id=${e}&temp=${n}&duration=${r}&filament=${encodeURIComponent(i)}&rotate_tray=${s}`,{method:"POST"}),stopDrying:(t,e)=>Oe(`/printers/${t}/drying/stop?ams_id=${e}`,{method:"POST"}),getPrintableObjects:t=>Oe(`/printers/${t}/print/objects`),skipObjects:(t,e)=>Oe(`/printers/${t}/print/skip-objects`,{method:"POST",body:JSON.stringify(e)}),clearHMSErrors:t=>Oe(`/printers/${t}/hms/clear`,{method:"POST"}),refreshAmsSlot:(t,e,n)=>Oe(`/printers/${t}/ams/${e}/slot/${n}/refresh`,{method:"POST"}),enableMQTTLogging:t=>Oe(`/printers/${t}/logging/enable`,{method:"POST"}),disableMQTTLogging:t=>Oe(`/printers/${t}/logging/disable`,{method:"POST"}),getMQTTLogs:t=>Oe(`/printers/${t}/logging`),clearMQTTLogs:t=>Oe(`/printers/${t}/logging`,{method:"DELETE"}),getPrinterFiles:(t,e="/")=>Oe(`/printers/${t}/files?path=${encodeURIComponent(e)}`),getPrinterFileDownloadUrl:(t,e)=>`${wn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,getPrinterFileGcodeUrl:(t,e)=>`${wn}/printers/${t}/files/gcode?path=${encodeURIComponent(e)}`,getPrinterFilePlates:(t,e)=>Oe(`/printers/${t}/files/plates?path=${encodeURIComponent(e)}`),getPrinterFilePlateThumbnail:(t,e,n)=>Ra(`${wn}/printers/${t}/files/plate-thumbnail/${e}?path=${encodeURIComponent(n)}`),downloadPrinterFile:async(t,e)=>{const n={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=Gp(i)||e.split("/").pop()||"download",o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},downloadPrinterFilesAsZip:async(t,e)=>{const n={"Content-Type":"application/json"};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/printers/${t}/files/download-zip`,{method:"POST",headers:n,body:JSON.stringify({paths:e})});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${r.status}`)}return r.blob()},deletePrinterFile:(t,e)=>Oe(`/printers/${t}/files?path=${encodeURIComponent(e)}`,{method:"DELETE"}),getPrinterStorage:t=>Oe(`/printers/${t}/storage`),getArchives:(t,e,n=1e4,r=0,i,s)=>{const o=new URLSearchParams;return t&&o.set("printer_id",String(t)),e&&o.set("project_id",String(e)),o.set("limit",String(n)),o.set("offset",String(r)),i&&o.set("date_from",i),s&&o.set("date_to",s),Oe(`/archives/?${o}`)},getArchivesSlim:(t,e,n)=>{const r=new URLSearchParams;t&&r.set("date_from",t),e&&r.set("date_to",e),n!==void 0&&r.set("created_by_id",String(n));const i=r.toString();return Oe(`/archives/slim${i?`?${i}`:""}`)},getArchive:t=>Oe(`/archives/${t}`),searchArchives:(t,e)=>{const n=new URLSearchParams;return n.set("q",t),e?.printerId&&n.set("printer_id",String(e.printerId)),e?.projectId&&n.set("project_id",String(e.projectId)),e?.status&&n.set("status",e.status),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset)),Oe(`/archives/search?${n}`)},rebuildSearchIndex:()=>Oe("/archives/search/rebuild-index",{method:"POST"}),updateArchive:(t,e)=>Oe(`/archives/${t}`,{method:"PATCH",body:JSON.stringify(e)}),toggleFavorite:t=>Oe(`/archives/${t}/favorite`,{method:"POST"}),deleteArchive:t=>Oe(`/archives/${t}`,{method:"DELETE"}),getArchiveStats:t=>{const e=new URLSearchParams;t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.createdById!==void 0&&e.set("created_by_id",String(t.createdById));const n=e.toString();return Oe(`/archives/stats${n?`?${n}`:""}`)},getTags:()=>Oe("/archives/tags"),renameTag:(t,e)=>Oe(`/archives/tags/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({new_name:e})}),deleteTag:t=>Oe(`/archives/tags/${encodeURIComponent(t)}`,{method:"DELETE"}),recalculateCosts:()=>Oe("/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 Oe(`/archives/analysis/failures${n?`?${n}`:""}`)},compareArchives:t=>Oe(`/archives/compare?archive_ids=${t.join(",")}`),findSimilarArchives:(t,e=10)=>Oe(`/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={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/archives/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"archives_export.xlsx":"archives_export.csv";if(i){const l=i.match(/filename="?([^"]+)"?/);l&&(s=l[1])}return{blob:await r.blob(),filename:s}},exportStats:async t=>{const e=new URLSearchParams;t?.format&&e.set("format",t.format),t?.days&&e.set("days",String(t.days)),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.projectId&&e.set("project_id",String(t.projectId)),t?.createdById!==void 0&&e.set("created_by_id",String(t.createdById));const n={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/archives/stats/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"stats_export.xlsx":"stats_export.csv";if(i){const l=i.match(/filename="?([^"]+)"?/);l&&(s=l[1])}return{blob:await r.blob(),filename:s}},getArchiveDuplicates:t=>Oe(`/archives/${t}/duplicates`),backfillContentHashes:()=>Oe("/archives/backfill-hashes",{method:"POST"}),getArchiveThumbnail:t=>Ra(`${wn}/archives/${t}/thumbnail?v=${Date.now()}`),getArchivePlateThumbnail:(t,e)=>Ra(`${wn}/archives/${t}/plate-thumbnail/${e}`),getArchiveDownload:t=>`${wn}/archives/${t}/download`,downloadArchive:async(t,e)=>{const n={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/archives/${t}/download`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=Gp(i)||e||`archive_${t}.3mf`,o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},getArchiveGcode:t=>`${wn}/archives/${t}/gcode`,getArchivePlatePreview:t=>Ra(`${wn}/archives/${t}/plate-preview`),getArchiveTimelapse:t=>Ra(`${wn}/archives/${t}/timelapse?v=${Date.now()}`),scanArchiveTimelapse:t=>Oe(`/archives/${t}/timelapse/scan`,{method:"POST"}),selectArchiveTimelapse:(t,e)=>Oe(`/archives/${t}/timelapse/select?filename=${encodeURIComponent(e)}`,{method:"POST"}),deleteArchiveTimelapse:t=>Oe(`/archives/${t}/timelapse`,{method:"DELETE"}),uploadArchiveTimelapse:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/archives/${t}/timelapse/upload`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},getTimelapseInfo:t=>Oe(`/archives/${t}/timelapse/info`),getTimelapseThumbnails:(t,e=10)=>Oe(`/archives/${t}/timelapse/thumbnails?count=${e}`),processTimelapse:async(t,e,n)=>{const r=new FormData;r.append("trim_start",String(e.trimStart??0)),e.trimEnd!==void 0&&r.append("trim_end",String(e.trimEnd)),r.append("speed",String(e.speed??1)),r.append("save_mode",e.saveMode),e.outputFilename&&r.append("output_filename",e.outputFilename),n&&r.append("audio",n);const i={};Pn&&(i.Authorization=`Bearer ${Pn}`);const s=await fetch(`${wn}/archives/${t}/timelapse/process`,{method:"POST",headers:i,body:r});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},getArchivePhotoUrl:(t,e)=>Ra(`${wn}/archives/${t}/photos/${encodeURIComponent(e)}`),uploadArchivePhoto:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/archives/${t}/photos`,{headers:r,method:"POST",body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteArchivePhoto:(t,e)=>Oe(`/archives/${t}/photos/${encodeURIComponent(e)}`,{method:"DELETE"}),getSource3mfDownloadUrl:t=>`${wn}/archives/${t}/source`,downloadSource3mf:async t=>{const e={};Pn&&(e.Authorization=`Bearer ${Pn}`);const n=await fetch(`${wn}/archives/${t}/source`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),i=Gp(r)||`source_${t}.3mf`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(o)},getSource3mfForSlicer:(t,e)=>{const n=e.replace(/[/\\?#]/g,"_");return`${wn}/archives/${t}/source/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createSourceSlicerToken:t=>Oe(`/archives/${t}/source-slicer-token`,{method:"POST"}),getSourceSlicerDownloadUrl:(t,e,n)=>{const r=n.replace(/[/\\?#]/g,"_");return`${wn}/archives/${t}/source-dl/${e}/${encodeURIComponent(r.endsWith(".3mf")?r:r+".3mf")}`},uploadSource3mf:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/archives/${t}/source`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteSource3mf:t=>Oe(`/archives/${t}/source`,{method:"DELETE"}),getF3dDownloadUrl:t=>`${wn}/archives/${t}/f3d`,downloadF3d:async t=>{const e={};Pn&&(e.Authorization=`Bearer ${Pn}`);const n=await fetch(`${wn}/archives/${t}/f3d`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),i=Gp(r)||`archive_${t}.f3d`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(o)},uploadF3d:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/archives/${t}/f3d`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteF3d:t=>Oe(`/archives/${t}/f3d`,{method:"DELETE"}),getArchiveQRCodeUrl:(t,e=200)=>Ra(`${wn}/archives/${t}/qrcode?size=${e}`),getArchiveCapabilities:t=>Oe(`/archives/${t}/capabilities`),getArchiveProjectPage:t=>Oe(`/archives/${t}/project-page`),updateArchiveProjectPage:(t,e)=>Oe(`/archives/${t}/project-page`,{method:"PATCH",body:JSON.stringify(e)}),getArchiveProjectImageUrl:(t,e)=>Ra(`${wn}/archives/${t}/project-image/${encodeURIComponent(e)}`),getArchiveForSlicer:(t,e)=>{const n=e.replace(/[/\\?#]/g,"_");return`${wn}/archives/${t}/file/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createArchiveSlicerToken:t=>Oe(`/archives/${t}/slicer-token`,{method:"POST"}),getArchiveSlicerDownloadUrl:(t,e,n)=>{const r=n.replace(/[/\\?#]/g,"_");return`${wn}/archives/${t}/dl/${e}/${encodeURIComponent(r.endsWith(".3mf")?r:r+".3mf")}`},getArchivePlates:t=>Oe(`/archives/${t}/plates`),getArchiveFilamentRequirements:(t,e)=>Oe(`/archives/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),reprintArchive:(t,e,n)=>Oe(`/archives/${t}/reprint?printer_id=${e}`,{method:"POST",headers:n?{"Content-Type":"application/json"}:void 0,body:n?JSON.stringify(n):void 0}),uploadArchive:async(t,e)=>{const n=new FormData;n.append("file",t);const r=e?`${wn}/archives/upload?printer_id=${e}`:`${wn}/archives/upload`,i={};Pn&&(i.Authorization=`Bearer ${Pn}`);const s=await fetch(r,{method:"POST",headers:i,body:n});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},uploadArchivesBulk:async(t,e)=>{const n=new FormData;t.forEach(o=>n.append("files",o));const r=e?`${wn}/archives/upload-bulk?printer_id=${e}`:`${wn}/archives/upload-bulk`,i={};Pn&&(i.Authorization=`Bearer ${Pn}`);const s=await fetch(r,{method:"POST",headers:i,body:n});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},getPrintLog:t=>{const e=new URLSearchParams;return t?.search&&e.set("search",t.search),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.username&&e.set("created_by_username",t.username),t?.status&&e.set("status",t.status),t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.limit&&e.set("limit",String(t.limit)),t?.offset!==void 0&&e.set("offset",String(t.offset)),Oe(`/print-log/?${e}`)},getPrintLogThumbnail:t=>Ra(`${wn}/print-log/${t}/thumbnail`),clearPrintLog:()=>Oe("/print-log/",{method:"DELETE"}),getSettings:()=>Oe("/settings/"),getDefaultSidebarOrder:()=>Oe("/settings/default-sidebar-order"),updateSettings:t=>Oe("/settings/",{method:"PUT",body:JSON.stringify(t)}),getMQTTStatus:()=>Oe("/settings/mqtt/status"),resetSettings:()=>Oe("/settings/reset",{method:"POST"}),exportBackup:async()=>{const t=`${wn}/settings/backup`,e={};Pn&&(e.Authorization=`Bearer ${Pn}`);const n=await fetch(t,{headers:e});if(!n.ok){const o=await n.text();throw new Error(o||`Backup failed with status ${n.status}`)}const r=n.headers.get("Content-Disposition");let i="bambuddy-backup.zip";if(r){const o=r.match(/filename=([^;]+)/);o&&(i=o[1].trim())}return{blob:await n.blob(),filename:i}},importBackup:async t=>{const e=new FormData;e.append("file",t);const n=`${wn}/settings/restore`,r={};return Pn&&(r.Authorization=`Bearer ${Pn}`),(await fetch(n,{method:"POST",headers:r,body:e})).json()},checkFfmpeg:()=>Oe("/settings/check-ffmpeg"),getNetworkInterfaces:()=>Oe("/settings/network-interfaces"),getCloudStatus:()=>Oe("/cloud/status"),cloudLogin:(t,e,n="global")=>Oe("/cloud/login",{method:"POST",body:JSON.stringify({email:t,password:e,region:n})}),cloudVerify:(t,e,n)=>Oe("/cloud/verify",{method:"POST",body:JSON.stringify({email:t,code:e,tfa_key:n})}),cloudSetToken:t=>Oe("/cloud/token",{method:"POST",body:JSON.stringify({access_token:t})}),cloudLogout:()=>Oe("/cloud/logout",{method:"POST"}),getCloudSettings:(t="02.04.00.70")=>Oe(`/cloud/settings?version=${t}`),getBuiltinFilaments:()=>Oe("/cloud/builtin-filaments"),getFilamentIdMap:()=>Oe("/cloud/filament-id-map"),getCloudSettingDetail:t=>Oe(`/cloud/settings/${t}`),createCloudSetting:t=>Oe("/cloud/settings",{method:"POST",body:JSON.stringify(t)}),updateCloudSetting:(t,e)=>Oe(`/cloud/settings/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCloudSetting:t=>Oe(`/cloud/settings/${t}`,{method:"DELETE"}),getCloudDevices:()=>Oe("/cloud/devices"),getCloudFields:t=>Oe(`/cloud/fields/${t}`),getAllCloudFields:()=>Oe("/cloud/fields"),getFilamentInfo:t=>Oe("/cloud/filament-info",{method:"POST",body:JSON.stringify(t)}),getSmartPlugs:()=>Oe("/smart-plugs/"),getSmartPlug:t=>Oe(`/smart-plugs/${t}`),getSmartPlugByPrinter:t=>Oe(`/smart-plugs/by-printer/${t}`),getScriptPlugsByPrinter:t=>Oe(`/smart-plugs/by-printer/${t}/scripts`),createSmartPlug:t=>Oe("/smart-plugs/",{method:"POST",body:JSON.stringify(t)}),updateSmartPlug:(t,e)=>Oe(`/smart-plugs/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSmartPlug:t=>Oe(`/smart-plugs/${t}`,{method:"DELETE"}),controlSmartPlug:(t,e)=>Oe(`/smart-plugs/${t}/control`,{method:"POST",body:JSON.stringify({action:e})}),getSmartPlugStatus:t=>Oe(`/smart-plugs/${t}/status`),testSmartPlugConnection:(t,e,n)=>Oe("/smart-plugs/test-connection",{method:"POST",body:JSON.stringify({ip_address:t,username:e,password:n})}),startTasmotaScan:()=>Oe("/smart-plugs/discover/scan",{method:"POST"}),getTasmotaScanStatus:()=>Oe("/smart-plugs/discover/status"),stopTasmotaScan:()=>Oe("/smart-plugs/discover/stop",{method:"POST"}),getDiscoveredTasmotaDevices:()=>Oe("/smart-plugs/discover/devices"),testHAConnection:(t,e)=>Oe("/smart-plugs/ha/test-connection",{method:"POST",body:JSON.stringify({url:t,token:e})}),getHAEntities:t=>{const e=t?`?search=${encodeURIComponent(t)}`:"";return Oe(`/smart-plugs/ha/entities${e}`)},getHASensorEntities:()=>Oe("/smart-plugs/ha/sensors"),testRESTConnection:(t,e="GET",n)=>Oe("/smart-plugs/rest/test-connection",{method:"POST",body:JSON.stringify({url:t,method:e,headers:n})}),getQueue:(t,e,n)=>{const r=new URLSearchParams;return t&&r.set("printer_id",String(t)),e&&r.set("status",e),n&&r.set("target_model",n),Oe(`/queue/?${r}`)},getQueueItem:t=>Oe(`/queue/${t}`),addToQueue:t=>Oe("/queue/",{method:"POST",body:JSON.stringify(t)}),updateQueueItem:(t,e)=>Oe(`/queue/${t}`,{method:"PATCH",body:JSON.stringify(e)}),removeFromQueue:t=>Oe(`/queue/${t}`,{method:"DELETE"}),reorderQueue:t=>Oe("/queue/reorder",{method:"POST",body:JSON.stringify({items:t})}),cancelQueueItem:t=>Oe(`/queue/${t}/cancel`,{method:"POST"}),stopQueueItem:t=>Oe(`/queue/${t}/stop`,{method:"POST"}),startQueueItem:t=>Oe(`/queue/${t}/start`,{method:"POST"}),bulkUpdateQueue:t=>Oe("/queue/bulk",{method:"PATCH",body:JSON.stringify(t)}),getBatches:t=>{const e=t?`?status=${t}`:"";return Oe(`/queue/batches${e}`)},getBatch:t=>Oe(`/queue/batches/${t}`),cancelBatch:t=>Oe(`/queue/batches/${t}`,{method:"DELETE"}),getKProfiles:(t,e="0.4")=>Oe(`/printers/${t}/kprofiles/?nozzle_diameter=${e}`),setKProfile:(t,e)=>Oe(`/printers/${t}/kprofiles/`,{method:"POST",body:JSON.stringify(e)}),deleteKProfile:(t,e)=>Oe(`/printers/${t}/kprofiles/`,{method:"DELETE",body:JSON.stringify(e)}),setKProfilesBatch:(t,e)=>Oe(`/printers/${t}/kprofiles/batch`,{method:"POST",body:JSON.stringify(e)}),getKProfileNotes:t=>Oe(`/printers/${t}/kprofiles/notes`),setKProfileNote:(t,e,n)=>Oe(`/printers/${t}/kprofiles/notes`,{method:"PUT",body:JSON.stringify({setting_id:e,note:n})}),deleteKProfileNote:(t,e)=>Oe(`/printers/${t}/kprofiles/notes/${encodeURIComponent(e)}`,{method:"DELETE"}),getSlotPresets:t=>Oe(`/printers/${t}/slot-presets`),getSlotPreset:(t,e,n)=>Oe(`/printers/${t}/slot-presets/${e}/${n}`),saveSlotPreset:(t,e,n,r,i,s="cloud")=>Oe(`/printers/${t}/slot-presets/${e}/${n}?preset_id=${encodeURIComponent(r)}&preset_name=${encodeURIComponent(i)}&preset_source=${encodeURIComponent(s)}`,{method:"PUT"}),deleteSlotPreset:(t,e,n)=>Oe(`/printers/${t}/slot-presets/${e}/${n}`,{method:"DELETE"}),getAmsLabels:t=>Oe(`/printers/${t}/ams-labels`),saveAmsLabel:(t,e,n,r="")=>Oe(`/printers/${t}/ams-labels/${e}`,{method:"PUT",body:JSON.stringify({label:n,ams_serial:r})}),deleteAmsLabel:(t,e,n="")=>Oe(`/printers/${t}/ams-labels/${e}?ams_serial=${encodeURIComponent(n)}`,{method:"DELETE"}),configureAmsSlot:(t,e,n,r)=>{const i=new URLSearchParams({tray_info_idx:r.tray_info_idx,tray_type:r.tray_type,tray_sub_brands:r.tray_sub_brands,tray_color:r.tray_color,nozzle_temp_min:r.nozzle_temp_min.toString(),nozzle_temp_max:r.nozzle_temp_max.toString(),cali_idx:r.cali_idx.toString(),nozzle_diameter:r.nozzle_diameter});return r.setting_id&&i.set("setting_id",r.setting_id),r.kprofile_filament_id&&i.set("kprofile_filament_id",r.kprofile_filament_id),r.kprofile_setting_id&&i.set("kprofile_setting_id",r.kprofile_setting_id),r.k_value!==void 0&&r.k_value>0&&i.set("k_value",r.k_value.toString()),Oe(`/printers/${t}/slots/${e}/${n}/configure?${i}`,{method:"POST"})},resetAmsSlot:(t,e,n)=>Oe(`/printers/${t}/ams/${e}/tray/${n}/reset`,{method:"POST"}),listFilaments:()=>Oe("/filament-catalog/"),getFilament:t=>Oe(`/filament-catalog/${t}`),getFilamentsByType:t=>Oe(`/filament-catalog/by-type/${t}`),getNotificationProviders:()=>Oe("/notifications/"),getNotificationProvider:t=>Oe(`/notifications/${t}`),createNotificationProvider:t=>Oe("/notifications/",{method:"POST",body:JSON.stringify(t)}),updateNotificationProvider:(t,e)=>Oe(`/notifications/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteNotificationProvider:t=>Oe(`/notifications/${t}`,{method:"DELETE"}),testNotificationProvider:t=>Oe(`/notifications/${t}/test`,{method:"POST"}),testNotificationConfig:t=>Oe("/notifications/test-config",{method:"POST",body:JSON.stringify(t)}),testAllNotificationProviders:()=>Oe("/notifications/test-all",{method:"POST"}),getNotificationTemplates:()=>Oe("/notification-templates"),getNotificationTemplate:t=>Oe(`/notification-templates/${t}`),updateNotificationTemplate:(t,e)=>Oe(`/notification-templates/${t}`,{method:"PUT",body:JSON.stringify(e)}),resetNotificationTemplate:t=>Oe(`/notification-templates/${t}/reset`,{method:"POST"}),getTemplateVariables:()=>Oe("/notification-templates/variables"),previewTemplate:t=>Oe("/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)),Oe(`/notifications/logs?${e}`)},getNotificationLogStats:(t=7)=>Oe(`/notifications/logs/stats?days=${t}`),clearNotificationLogs:(t=30)=>Oe(`/notifications/logs?older_than_days=${t}`,{method:"DELETE"}),getSpoolmanStatus:()=>Oe("/spoolman/status"),connectSpoolman:()=>Oe("/spoolman/connect",{method:"POST"}),disconnectSpoolman:()=>Oe("/spoolman/disconnect",{method:"POST"}),syncPrinterAms:t=>Oe(`/spoolman/sync/${t}`,{method:"POST"}),syncAllPrintersAms:()=>Oe("/spoolman/sync-all",{method:"POST"}),getSpoolmanSpools:()=>Oe("/spoolman/spools"),getSpoolmanFilaments:()=>Oe("/spoolman/filaments"),getUnlinkedSpools:()=>Oe("/spoolman/spools/unlinked"),getLinkedSpools:()=>Oe("/spoolman/spools/linked"),linkSpool:(t,e)=>Oe(`/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=>Oe(`/spoolman/spools/${t}/unlink`,{method:"POST"}),getSpoolmanSettings:()=>Oe("/settings/spoolman"),updateSpoolmanSettings:t=>Oe("/settings/spoolman",{method:"PUT",body:JSON.stringify(t)}),getSpools:(t=!1)=>Oe(`/inventory/spools?include_archived=${t}`),getSpool:t=>Oe(`/inventory/spools/${t}`),createSpool:t=>Oe("/inventory/spools",{method:"POST",body:JSON.stringify(t)}),bulkCreateSpools:(t,e)=>Oe("/inventory/spools/bulk",{method:"POST",body:JSON.stringify({spool:t,quantity:e})}),updateSpool:(t,e)=>Oe(`/inventory/spools/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSpool:t=>Oe(`/inventory/spools/${t}`,{method:"DELETE"}),archiveSpool:t=>Oe(`/inventory/spools/${t}/archive`,{method:"POST"}),restoreSpool:t=>Oe(`/inventory/spools/${t}/restore`,{method:"POST"}),getSpoolKProfiles:t=>Oe(`/inventory/spools/${t}/k-profiles`),saveSpoolKProfiles:(t,e)=>Oe(`/inventory/spools/${t}/k-profiles`,{method:"PUT",body:JSON.stringify(e)}),getAssignments:t=>Oe(`/inventory/assignments${t?`?printer_id=${t}`:""}`),assignSpool:t=>Oe("/inventory/assignments",{method:"POST",body:JSON.stringify(t)}),unassignSpool:(t,e,n)=>Oe(`/inventory/assignments/${t}/${e}/${n}`,{method:"DELETE"}),getSpoolCatalog:()=>Oe("/inventory/catalog"),addCatalogEntry:t=>Oe("/inventory/catalog",{method:"POST",body:JSON.stringify(t)}),updateCatalogEntry:(t,e)=>Oe(`/inventory/catalog/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCatalogEntry:t=>Oe(`/inventory/catalog/${t}`,{method:"DELETE"}),bulkDeleteCatalogEntries:t=>Oe("/inventory/catalog/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetSpoolCatalog:()=>Oe("/inventory/catalog/reset",{method:"POST"}),getColorCatalog:()=>Oe("/inventory/colors"),addColorEntry:t=>Oe("/inventory/colors",{method:"POST",body:JSON.stringify(t)}),updateColorEntry:(t,e)=>Oe(`/inventory/colors/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteColorEntry:t=>Oe(`/inventory/colors/${t}`,{method:"DELETE"}),bulkDeleteColorEntries:t=>Oe("/inventory/colors/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetColorCatalog:()=>Oe("/inventory/colors/reset",{method:"POST"}),lookupColor:(t,e,n)=>Oe(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(t)}&color_name=${encodeURIComponent(e)}${n?`&material=${encodeURIComponent(n)}`:""}`),searchColors:(t,e)=>Oe(`/inventory/colors/search?${t?`manufacturer=${encodeURIComponent(t)}`:""}${t&&e?"&":""}${e?`material=${encodeURIComponent(e)}`:""}`),linkTagToSpool:(t,e)=>Oe(`/inventory/spools/${t}/link-tag`,{method:"PATCH",body:JSON.stringify(e)}),getSpoolUsageHistory:(t,e=50)=>Oe(`/inventory/spools/${t}/usage?limit=${e}`),getAllUsageHistory:(t=100,e)=>Oe(`/inventory/usage?limit=${t}${e?`&printer_id=${e}`:""}`),clearSpoolUsageHistory:t=>Oe(`/inventory/spools/${t}/usage`,{method:"DELETE"}),syncWeightsFromAms:()=>Oe("/inventory/sync-ams-weights",{method:"POST"}),getFilamentPresets:()=>Oe("/cloud/filaments"),getVersion:()=>Oe("/updates/version"),checkForUpdates:()=>Oe("/updates/check"),applyUpdate:()=>Oe("/updates/apply",{method:"POST"}),getUpdateStatus:()=>Oe("/updates/status"),getMaintenanceTypes:()=>Oe("/maintenance/types"),createMaintenanceType:t=>Oe("/maintenance/types",{method:"POST",body:JSON.stringify(t)}),updateMaintenanceType:(t,e)=>Oe(`/maintenance/types/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteMaintenanceType:t=>Oe(`/maintenance/types/${t}`,{method:"DELETE"}),restoreDefaultMaintenanceTypes:()=>Oe("/maintenance/types/restore-defaults",{method:"POST"}),getMaintenanceOverview:()=>Oe("/maintenance/overview"),getPrinterMaintenance:t=>Oe(`/maintenance/printers/${t}`),updateMaintenanceItem:(t,e)=>Oe(`/maintenance/items/${t}`,{method:"PATCH",body:JSON.stringify(e)}),performMaintenance:(t,e)=>Oe(`/maintenance/items/${t}/perform`,{method:"POST",body:JSON.stringify({notes:e})}),getMaintenanceHistory:t=>Oe(`/maintenance/items/${t}/history`),getMaintenanceSummary:()=>Oe("/maintenance/summary"),setPrinterHours:(t,e)=>Oe(`/maintenance/printers/${t}/hours?total_hours=${e}`,{method:"PATCH"}),assignMaintenanceType:(t,e)=>Oe(`/maintenance/printers/${t}/assign/${e}`,{method:"POST"}),removeMaintenanceItem:t=>Oe(`/maintenance/items/${t}`,{method:"DELETE"}),getCameraStreamToken:()=>Oe("/printers/camera/stream-token",{method:"POST"}),getCameraStreamUrl:(t,e=10)=>Ra(`${wn}/printers/${t}/camera/stream?fps=${e}`),getCameraSnapshotUrl:t=>Ra(`${wn}/printers/${t}/camera/snapshot`),testCameraConnection:t=>Oe(`/printers/${t}/camera/test`),getCameraStatus:t=>Oe(`/printers/${t}/camera/status`),checkPlateEmpty:(t,e)=>{const n=new URLSearchParams;return n.set("use_external",String(e?.useExternal??!1)),n.set("include_debug_image",String(e?.includeDebugImage??!1)),Oe(`/printers/${t}/camera/check-plate?${n.toString()}`)},getPlateDetectionStatus:t=>Oe(`/printers/${t}/camera/plate-detection/status`),calibratePlateDetection:(t,e)=>{const n=new URLSearchParams;return e?.label&&n.set("label",e.label),n.set("use_external",String(e?.useExternal??!1)),Oe(`/printers/${t}/camera/plate-detection/calibrate?${n.toString()}`,{method:"POST"})},deletePlateCalibration:t=>Oe(`/printers/${t}/camera/plate-detection/calibrate`,{method:"DELETE"}),getPlateReferences:t=>Oe(`/printers/${t}/camera/plate-detection/references`),getPlateReferenceThumbnailUrl:(t,e)=>Ra(`${wn}/printers/${t}/camera/plate-detection/references/${e}/thumbnail`),updatePlateReferenceLabel:(t,e,n)=>{const r=new URLSearchParams;return r.set("label",n),Oe(`/printers/${t}/camera/plate-detection/references/${e}?${r.toString()}`,{method:"PUT"})},deletePlateReference:(t,e)=>Oe(`/printers/${t}/camera/plate-detection/references/${e}`,{method:"DELETE"}),getExternalLinks:()=>Oe("/external-links/"),getExternalLink:t=>Oe(`/external-links/${t}`),createExternalLink:t=>Oe("/external-links/",{method:"POST",body:JSON.stringify(t)}),updateExternalLink:(t,e)=>Oe(`/external-links/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteExternalLink:t=>Oe(`/external-links/${t}`,{method:"DELETE"}),reorderExternalLinks:t=>Oe("/external-links/reorder",{method:"PUT",body:JSON.stringify({ids:t})}),uploadExternalLinkIcon:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/external-links/${t}/icon`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteExternalLinkIcon:t=>Oe(`/external-links/${t}/icon`,{method:"DELETE"}),getExternalLinkIconUrl:t=>Ra(`${wn}/external-links/${t}/icon`),getProjects:t=>{const e=new URLSearchParams;return t&&e.set("status",t),Oe(`/projects/?${e}`)},getProject:t=>Oe(`/projects/${t}`),createProject:t=>Oe("/projects/",{method:"POST",body:JSON.stringify(t)}),updateProject:(t,e)=>Oe(`/projects/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>Oe(`/projects/${t}`,{method:"DELETE"}),getProjectArchives:(t,e=100,n=0)=>Oe(`/projects/${t}/archives?limit=${e}&offset=${n}`),addArchivesToProject:(t,e)=>Oe(`/projects/${t}/add-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),removeArchivesFromProject:(t,e)=>Oe(`/projects/${t}/remove-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),addQueueItemsToProject:(t,e)=>Oe(`/projects/${t}/add-queue`,{method:"POST",body:JSON.stringify({queue_item_ids:e})}),uploadProjectAttachment:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Pn&&(r.Authorization=`Bearer ${Pn}`);const i=await fetch(`${wn}/projects/${t}/attachments`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},getProjectAttachmentUrl:(t,e)=>`${wn}/projects/${t}/attachments/${encodeURIComponent(e)}`,deleteProjectAttachment:(t,e)=>Oe(`/projects/${t}/attachments/${encodeURIComponent(e)}`,{method:"DELETE"}),getProjectBOM:t=>Oe(`/projects/${t}/bom`),createBOMItem:(t,e)=>Oe(`/projects/${t}/bom`,{method:"POST",body:JSON.stringify(e)}),updateBOMItem:(t,e,n)=>Oe(`/projects/${t}/bom/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteBOMItem:(t,e)=>Oe(`/projects/${t}/bom/${e}`,{method:"DELETE"}),getTemplates:()=>Oe("/projects/templates/"),createTemplateFromProject:t=>Oe(`/projects/${t}/create-template`,{method:"POST"}),createProjectFromTemplate:(t,e)=>Oe(`/projects/from-template/${t}${e?`?name=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getProjectTimeline:(t,e=50)=>Oe(`/projects/${t}/timeline?limit=${e}`),exportProjectJson:t=>Oe(`/projects/${t}/export?format=json`),importProject:t=>Oe("/projects/import",{method:"POST",body:JSON.stringify(t)}),importProjectFile:async t=>{const e=new FormData;e.append("file",t);const n={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/projects/import/file`,{method:"POST",headers:n,body:e});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${r.status}`)}return r.json()},exportProjectZip:async t=>{const e={};Pn&&(e.Authorization=`Bearer ${Pn}`);const n=await fetch(`${wn}/projects/${t}/export`,{headers:e});if(!n.ok){const o=await n.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),i=Gp(r)||`project_${t}.zip`;return{blob:await n.blob(),filename:i}},getAPIKeys:()=>Oe("/api-keys/"),createAPIKey:t=>Oe("/api-keys/",{method:"POST",body:JSON.stringify(t)}),updateAPIKey:(t,e)=>Oe(`/api-keys/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteAPIKey:t=>Oe(`/api-keys/${t}`,{method:"DELETE"}),getAMSHistory:(t,e,n=24)=>Oe(`/ams-history/${t}/${e}?hours=${n}`),getSystemInfo:()=>Oe("/system/info"),getStorageUsage:t=>{const e=new URLSearchParams;t?.refresh&&e.set("refresh","true");const n=e.toString();return Oe(`/system/storage-usage${n?`?${n}`:""}`)},getLibraryFolders:()=>Oe("/library/folders"),createLibraryFolder:t=>Oe("/library/folders",{method:"POST",body:JSON.stringify(t)}),updateLibraryFolder:(t,e)=>Oe(`/library/folders/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFolder:t=>Oe(`/library/folders/${t}`,{method:"DELETE"}),createExternalFolder:t=>Oe("/library/folders/external",{method:"POST",body:JSON.stringify(t)}),scanExternalFolder:t=>Oe(`/library/folders/${t}/scan`,{method:"POST"}),getLibraryFoldersByProject:t=>Oe(`/library/folders/by-project/${t}`),getLibraryFoldersByArchive:t=>Oe(`/library/folders/by-archive/${t}`),getLibraryFiles:(t,e=!0)=>{const n=new URLSearchParams;return t!=null&&n.set("folder_id",String(t)),n.set("include_root",String(e)),Oe(`/library/files?${n}`)},getLibraryFile:t=>Oe(`/library/files/${t}`),uploadLibraryFile:async(t,e,n=!0)=>{const r=new FormData;r.append("file",t);const i=new URLSearchParams;e&&i.set("folder_id",String(e)),i.set("generate_stl_thumbnails",String(n));const s={};Pn&&(s.Authorization=`Bearer ${Pn}`);const o=await fetch(`${wn}/library/files?${i}`,{method:"POST",headers:s,body:r});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${o.status}`)}return o.json()},extractZipFile:async(t,e,n=!0,r=!1,i=!0)=>{const s=new FormData;s.append("file",t);const o=new URLSearchParams;e&&o.set("folder_id",String(e)),o.set("preserve_structure",String(n)),o.set("create_folder_from_zip",String(r)),o.set("generate_stl_thumbnails",String(i));const l={};Pn&&(l.Authorization=`Bearer ${Pn}`);const c=await fetch(`${wn}/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)=>Oe(`/library/files/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFile:t=>Oe(`/library/files/${t}`,{method:"DELETE"}),getLibraryFileDownloadUrl:t=>`${wn}/library/files/${t}/download`,createLibrarySlicerToken:t=>Oe(`/library/files/${t}/slicer-token`,{method:"POST"}),getLibrarySlicerDownloadUrl:(t,e,n)=>`${wn}/library/files/${t}/dl/${e}/${encodeURIComponent(n)}`,downloadLibraryFile:async(t,e)=>{const n={};Pn&&(n.Authorization=`Bearer ${Pn}`);const r=await fetch(`${wn}/library/files/${t}/download`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=Gp(i)||e||`file_${t}`,o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},getLibraryFileThumbnailUrl:t=>Ra(`${wn}/library/files/${t}/thumbnail`),getLibraryFilePlateThumbnail:(t,e)=>Ra(`${wn}/library/files/${t}/plate-thumbnail/${e}`),getLibraryFileGcodeUrl:t=>`${wn}/library/files/${t}/gcode`,moveLibraryFiles:(t,e)=>Oe("/library/files/move",{method:"POST",body:JSON.stringify({file_ids:t,folder_id:e})}),bulkDeleteLibrary:(t,e)=>Oe("/library/bulk-delete",{method:"POST",body:JSON.stringify({file_ids:t,folder_ids:e})}),getLibraryStats:()=>Oe("/library/stats"),batchGenerateStlThumbnails:t=>Oe("/library/generate-stl-thumbnails",{method:"POST",body:JSON.stringify(t)}),addLibraryFilesToQueue:t=>Oe("/library/files/add-to-queue",{method:"POST",body:JSON.stringify({file_ids:t})}),printLibraryFile:(t,e,n)=>Oe(`/library/files/${t}/print?printer_id=${e}`,{method:"POST",body:n?JSON.stringify(n):void 0}),cancelBackgroundDispatchJob:t=>Oe(`/background-dispatch/${t}`,{method:"DELETE"}),getLibraryFilePlates:t=>Oe(`/library/files/${t}/plates`),getLibraryFileFilamentRequirements:(t,e)=>Oe(`/library/files/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),getGitHubBackupConfig:()=>Oe("/github-backup/config"),saveGitHubBackupConfig:t=>Oe("/github-backup/config",{method:"POST",body:JSON.stringify(t)}),updateGitHubBackupConfig:t=>Oe("/github-backup/config",{method:"PATCH",body:JSON.stringify(t)}),deleteGitHubBackupConfig:()=>Oe("/github-backup/config",{method:"DELETE"}),testGitHubConnection:(t,e)=>Oe(`/github-backup/test?repo_url=${encodeURIComponent(t)}&token=${encodeURIComponent(e)}`,{method:"POST"}),testGitHubStoredConnection:()=>Oe("/github-backup/test-stored",{method:"POST"}),triggerGitHubBackup:()=>Oe("/github-backup/run",{method:"POST"}),getGitHubBackupStatus:()=>Oe("/github-backup/status"),getGitHubBackupLogs:(t=50)=>Oe(`/github-backup/logs?limit=${t}`),clearGitHubBackupLogs:(t=10)=>Oe(`/github-backup/logs?keep_last=${t}`,{method:"DELETE"}),getLocalPresets:()=>Oe("/local-presets/"),getLocalPresetDetail:t=>Oe(`/local-presets/${t}`),importLocalPresets:t=>fetch(`${wn}/local-presets/import`,{method:"POST",headers:Pn?{Authorization:`Bearer ${Pn}`}:{},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=>Oe("/local-presets/",{method:"POST",body:JSON.stringify(t)}),updateLocalPreset:(t,e)=>Oe(`/local-presets/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLocalPreset:t=>Oe(`/local-presets/${t}`,{method:"DELETE"}),refreshBaseProfileCache:()=>Oe("/local-presets/base-cache/refresh",{method:"POST"})},Qc={getInfo:()=>Oe("/discovery/info"),getStatus:()=>Oe("/discovery/status"),startDiscovery:(t=10)=>Oe(`/discovery/start?duration=${t}`,{method:"POST"}),stopDiscovery:()=>Oe("/discovery/stop",{method:"POST"}),getDiscoveredPrinters:()=>Oe("/discovery/printers"),startSubnetScan:(t,e=1)=>Oe("/discovery/scan",{method:"POST",body:JSON.stringify({subnet:t,timeout:e})}),getScanStatus:()=>Oe("/discovery/scan/status"),stopSubnetScan:()=>Oe("/discovery/scan/stop",{method:"POST"})},jxe={getSettings:()=>Oe("/settings/virtual-printer")},oN={list:()=>Oe("/virtual-printers"),get:t=>Oe(`/virtual-printers/${t}`),create:t=>Oe("/virtual-printers",{method:"POST",body:JSON.stringify(t)}),update:(t,e)=>Oe(`/virtual-printers/${t}`,{method:"PUT",body:JSON.stringify(e)}),remove:t=>Oe(`/virtual-printers/${t}`,{method:"DELETE"})},zb={list:()=>Oe("/pending-uploads/"),getCount:()=>Oe("/pending-uploads/count"),get:t=>Oe(`/pending-uploads/${t}`),archive:(t,e)=>Oe(`/pending-uploads/${t}/archive`,{method:"POST",body:JSON.stringify(e||{})}),discard:t=>Oe(`/pending-uploads/${t}`,{method:"DELETE"}),archiveAll:()=>Oe("/pending-uploads/archive-all",{method:"POST"}),discardAll:()=>Oe("/pending-uploads/discard-all",{method:"DELETE"})},yk={checkUpdates:()=>Oe("/firmware/updates"),checkPrinterUpdate:t=>Oe(`/firmware/updates/${t}`),prepareUpload:t=>Oe(`/firmware/updates/${t}/prepare`),startUpload:t=>Oe(`/firmware/updates/${t}/upload`,{method:"POST"}),getUploadStatus:t=>Oe(`/firmware/updates/${t}/upload/status`)},nx={getDebugLoggingState:()=>Oe("/support/debug-logging"),setDebugLogging:t=>Oe("/support/debug-logging",{method:"POST",body:JSON.stringify({enabled:t})}),downloadSupportBundle:async()=>{const t={};Pn&&(t.Authorization=`Bearer ${Pn}`);const e=await fetch(`${wn}/support/bundle`,{headers:t});if(!e.ok){const l=await e.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${e.status}`)}const n=e.headers.get("Content-Disposition"),r=Gp(n)||"bambuddy-support.zip",i=await e.blob(),s=window.URL.createObjectURL(i),o=document.createElement("a");o.href=s,o.download=r,document.body.appendChild(o),o.click(),document.body.removeChild(o),window.URL.revokeObjectURL(s)},getLogs:t=>{const e=new URLSearchParams;t?.limit&&e.set("limit",t.limit.toString()),t?.level&&e.set("level",t.level),t?.search&&e.set("search",t.search);const n=e.toString();return Oe(`/support/logs${n?`?${n}`:""}`)},clearLogs:()=>Oe("/support/logs",{method:"DELETE"})},wa={getDevices:()=>Oe("/spoolbuddy/devices"),tare:t=>Oe(`/spoolbuddy/devices/${t}/calibration/tare`,{method:"POST",body:"{}"}),getCalibration:t=>Oe(`/spoolbuddy/devices/${t}/calibration`),setCalibrationFactor:(t,e,n,r)=>Oe(`/spoolbuddy/devices/${t}/calibration/set-factor`,{method:"POST",body:JSON.stringify({known_weight_grams:e,raw_adc:n,tare_raw_adc:r})}),updateSpoolWeight:(t,e)=>Oe("/spoolbuddy/scale/update-spool-weight",{method:"POST",body:JSON.stringify({spool_id:t,weight_grams:e})}),updateDisplay:(t,e,n)=>Oe(`/spoolbuddy/devices/${t}/display`,{method:"PUT",body:JSON.stringify({brightness:e,blank_timeout:n})}),updateSystemConfig:(t,e,n)=>Oe(`/spoolbuddy/devices/${t}/system/config`,{method:"POST",body:JSON.stringify({backend_url:e,...n?{api_key:n}:{}})}),checkDaemonUpdate:t=>Oe(`/spoolbuddy/devices/${t}/update-check`),triggerUpdate:t=>Oe(`/spoolbuddy/devices/${t}/update`,{method:"POST",body:"{}"}),getSSHPublicKey:()=>Oe("/spoolbuddy/ssh/public-key"),writeTag:(t,e)=>Oe("/spoolbuddy/nfc/write-tag",{method:"POST",body:JSON.stringify({device_id:t,spool_id:e})}),cancelWrite:t=>Oe(`/spoolbuddy/devices/${t}/cancel-write`,{method:"POST",body:"{}"}),systemCommand:(t,e)=>Oe(`/spoolbuddy/devices/${t}/system/command`,{method:"POST",body:JSON.stringify({command:e})}),queueDiagnostics:(t,e)=>Oe(`/spoolbuddy/diagnostics/${t}/run?diagnostic=${e}`,{method:"POST",body:"{}"}),getDiagnosticResult:(t,e)=>Oe(`/spoolbuddy/diagnostics/${t}/result?diagnostic=${e}`,{method:"GET"})},mj={submit:t=>Oe("/bug-report/submit",{method:"POST",body:JSON.stringify(t)}),startLogging:()=>Oe("/bug-report/start-logging",{method:"POST"}),stopLogging:t=>Oe(`/bug-report/stop-logging?was_debug=${t}`,{method:"POST"})},TQ=w.createContext(void 0);function Exe({children:t}){const[e,n]=w.useState(()=>{const A=localStorage.getItem("theme-mode"),T=localStorage.getItem("theme");return A||T||"dark"}),[r,i]=w.useState(()=>localStorage.getItem("dark-style")||"classic"),[s,o]=w.useState(()=>localStorage.getItem("dark-background")||"neutral"),[l,c]=w.useState(()=>localStorage.getItem("dark-accent")||"green"),[d,u]=w.useState(()=>localStorage.getItem("light-style")||"classic"),[m,p]=w.useState(()=>localStorage.getItem("light-background")||"neutral"),[f,y]=w.useState(()=>localStorage.getItem("light-accent")||"green");w.useEffect(()=>{pe.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&&(y(A.light_accent),localStorage.setItem("light-accent",A.light_accent))}).catch(()=>{})},[]),w.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-${r}`),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,r,s,l,d,m,f]);const v=()=>n(A=>A==="dark"?"light":"dark"),b=A=>n(A),g=A=>{i(A),localStorage.setItem("dark-style",A),pe.updateSettings({dark_style:A}).catch(()=>{})},_=A=>{o(A),localStorage.setItem("dark-background",A),pe.updateSettings({dark_background:A}).catch(()=>{})},k=A=>{c(A),localStorage.setItem("dark-accent",A),pe.updateSettings({dark_accent:A}).catch(()=>{})},P=A=>{u(A),localStorage.setItem("light-style",A),pe.updateSettings({light_style:A}).catch(()=>{})},N=A=>{p(A),localStorage.setItem("light-background",A),pe.updateSettings({light_background:A}).catch(()=>{})},M=A=>{y(A),localStorage.setItem("light-accent",A),pe.updateSettings({light_accent:A}).catch(()=>{})};return a.jsx(TQ.Provider,{value:{mode:e,darkStyle:r,darkBackground:s,darkAccent:l,lightStyle:d,lightBackground:m,lightAccent:f,toggleMode:v,setMode:b,setDarkStyle:g,setDarkBackground:_,setDarkAccent:k,setLightStyle:P,setLightBackground:N,setLightAccent:M},children:t})}function cg(){const t=w.useContext(TQ);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const yO=w.createContext("normal");function Dxe({density:t,children:e}){return a.jsx(yO.Provider,{value:t,children:e})}function Dt({children:t,className:e="",onClick:n,onContextMenu:r,...i}){return a.jsx("div",{className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary card-shadow ${e}`,onClick:n,onContextMenu:r,...i,children:t})}function Dn({children:t,className:e="",dense:n}){const r=w.useContext(yO)==="dense",s=n??r?"px-4 py-2.5":"px-6 py-4";return a.jsx("div",{className:`${s} border-b border-bambu-dark-tertiary ${e}`,children:t})}function Rt({children:t,className:e="",dense:n}){const r=w.useContext(yO)==="dense",s=n??r?"p-4":"p-6";return a.jsx("div",{className:`${s} ${e}`,children:t})}function Fxe(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 f6({children:t}){return a.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-bambu-dark border border-bambu-dark-tertiary rounded text-white",children:t})}function Rxe({onClose:t,navItems:e,sidebarItems:n}){const{t:r}=Lt(),i=Fxe(n,e,r);return w.useEffect(()=>{const s=o=>{o.key==="Escape"&&t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:s=>s.stopPropagation(),children:a.jsxs(Rt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(z3,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Keyboard Shortcuts"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4 space-y-6 max-h-[60vh] overflow-y-auto",children:i.map(s=>a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:s.category}),a.jsx("div",{className:"space-y-2",children:s.items.map(o=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"text-white text-sm flex items-center gap-1.5",children:[o.description,o.isExternal&&a.jsx(sa,{className:"w-3 h-3 text-bambu-gray"})]}),a.jsx("div",{className:"flex gap-1",children:o.keys.map(l=>a.jsx(f6,{children:l},l))})]},o.description))})]},s.category))}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("p",{className:"text-xs text-bambu-gray text-center",children:["Press ",a.jsx(f6,{children:"Esc"})," or click outside to close"]})})]})})})}function Ie({variant:t="primary",size:e="md",className:n="",children:r,...i}){const s="inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-bambu-dark disabled:opacity-50 disabled:cursor-not-allowed",o={primary:"bg-bambu-green hover:bg-bambu-green-light text-white focus:ring-bambu-green",secondary:"bg-bambu-dark-tertiary hover:bg-bambu-gray-dark text-white focus:ring-bambu-gray",danger:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-500",ghost:"bg-transparent hover:bg-bambu-dark-tertiary text-bambu-gray-light hover:text-white"},l={sm:"px-3 py-1.5 text-sm gap-1.5 min-h-[44px] md:min-h-0",md:"px-4 py-2 text-sm gap-2 min-h-[44px] md:min-h-0",lg:"px-6 py-3 text-base gap-2 min-h-[48px] md:min-h-0"};return a.jsx("button",{className:`${s} ${o[t]} ${l[e]} ${n}`,...i,children:r})}function kn({title:t,message:e,confirmText:n,cancelText:r,cancelVariant:i,cardClassName:s,variant:o="default",isLoading:l=!1,loadingText:c,onConfirm:d,onCancel:u}){const{t:m}=Lt(),p=n??m("common.confirm"),f=r??m("common.cancel"),y=c??m("common.loading");w.useEffect(()=>{const g=_=>{_.key==="Escape"&&!l&&u()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[u,l]);const b={danger:{icon:"text-red-400",button:"bg-red-500 hover:bg-red-600"},warning:{icon:"text-yellow-400",button:"bg-yellow-500 hover:bg-yellow-600 text-black"},default:{icon:"text-bambu-green",button:"bg-bambu-green hover:bg-bambu-green-dark"}}[o];return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l?void 0:u,children:a.jsx(Dt,{className:`w-full max-w-md ${s??""}`,onClick:g=>g.stopPropagation(),children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${b.icon}`,children:a.jsx(Ln,{className:"w-6 h-6"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t}),a.jsx("p",{className:"text-bambu-gray text-sm whitespace-pre-line",children:e})]})]}),a.jsxs("div",{className:"flex gap-3 mt-6",children:[a.jsx(Ie,{variant:i??"secondary",onClick:u,className:"flex-1",disabled:l,children:f}),a.jsx(Ie,{onClick:d,className:`flex-1 ${b.button}`,disabled:l,children:l?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),y]}):p})]})]})})})}function Lxe({plug:t}){const e=mn(),[n,r]=w.useState(null),{data:i,isLoading:s}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>pe.getSmartPlugStatus(t.id),refetchInterval:1e4}),o=lt({mutationFn:f=>pe.controlSmartPlug(t.id,f),onSuccess:()=>{e.invalidateQueries({queryKey:["smart-plug-status",t.id]})}}),l=i?.state==="ON",c=t.plug_type==="mqtt"&&i?.energy?.power!==null&&i?.energy?.power!==void 0,d=(i?.reachable??!1)||c,u=o.isPending,m=t.plug_type==="mqtt",p=()=>{n&&(o.mutate(n),r(null))};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between py-2 px-3 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`p-1.5 rounded ${m?d?"bg-teal-500/20":"bg-red-500/20":d?l?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:m?a.jsx(pO,{className:`w-4 h-4 ${d?"text-teal-400":"text-red-400"}`}):a.jsx(ql,{className:`w-4 h-4 ${d?l?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white font-medium",children:t.name}),a.jsx("div",{className:"flex items-center gap-1 text-xs",children:s?a.jsx(ct,{className:"w-3 h-3 text-bambu-gray animate-spin"}):m?d?a.jsxs(a.Fragment,{children:[a.jsx(Xl,{className:"w-3 h-3 text-teal-400"}),a.jsxs("span",{className:"text-teal-400",children:[Math.round(i?.energy?.power??0),"W"]}),a.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),a.jsx(Dc,{className:"w-3 h-3 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:"Monitor"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ku,{className:"w-3 h-3 text-status-error"}),a.jsx("span",{className:"text-status-error",children:"Waiting"})]}):d?a.jsxs(a.Fragment,{children:[a.jsx(vf,{className:"w-3 h-3 text-status-ok"}),a.jsx("span",{className:l?"text-status-ok":"text-bambu-gray",children:i?.state||"Unknown"}),i?.energy?.power!==null&&i?.energy?.power!==void 0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),a.jsx(Xl,{className:"w-3 h-3 text-yellow-400"}),a.jsxs("span",{className:"text-yellow-400",children:[Math.round(i.energy.power),"W"]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ku,{className:"w-3 h-3 text-status-error"}),a.jsx("span",{className:"text-status-error",children:"Offline"})]})})]})]}),!m&&a.jsxs("div",{className:"flex gap-1",children:[a.jsx("button",{onClick:()=>r("on"),disabled:!d||u,className:`p-1.5 rounded transition-colors ${l?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"} disabled:opacity-50 disabled:cursor-not-allowed`,title:"Turn On",children:u?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(im,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("off"),disabled:!d||u,className:`p-1.5 rounded transition-colors ${!l&&d?"bg-bambu-dark-tertiary text-white":"bg-bambu-dark text-bambu-gray hover:text-white"} disabled:opacity-50 disabled:cursor-not-allowed`,title:"Turn Off",children:u?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Rw,{className:"w-4 h-4"})})]})]}),n&&a.jsx(kn,{title:`Turn ${n==="on"?"On":"Off"} Smart Plug`,message:`Are you sure you want to turn ${n==="on"?"on":"off"} "${t.name}"?`,confirmText:n==="on"?"Turn On":"Turn Off",variant:n==="off"?"warning":"default",onConfirm:p,onCancel:()=>r(null)})]})}function g6({onClose:t}){const{t:e}=Lt(),{data:n,isLoading:r}=et({queryKey:["smart-plugs"],queryFn:pe.getSmartPlugs}),i=n?.filter(s=>s.show_in_switchbar)||[];return a.jsxs("div",{className:"absolute bottom-full left-0 mb-2 w-72 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-xl z-50",onMouseLeave:t,children:[a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary",children:a.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[a.jsx(ql,{className:"w-4 h-4 text-bambu-green"}),"Smart Switches"]})}),a.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:r?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-gray animate-spin"})}):i.length===0?a.jsxs("div",{className:"text-center py-6 px-4",children:[a.jsx(ql,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e("smartPlugs.noSwitchesInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:e("smartPlugs.enableSwitchbarHint")})]}):a.jsx("div",{className:"space-y-1",children:i.map(s=>a.jsx(Lxe,{plug:s},s.id))})})]})}const AQ=[{name:"globe",icon:yd},{name:"link",icon:ny},{name:"external-link",icon:sa},{name:"book",icon:cpe},{name:"file-text",icon:Ms},{name:"home",icon:Mw},{name:"star",icon:If},{name:"heart",icon:dge},{name:"bookmark",icon:upe},{name:"shopping-cart",icon:vQ},{name:"music",icon:H3},{name:"video",icon:gO},{name:"image",icon:Vu},{name:"camera",icon:yx},{name:"map",icon:Rge},{name:"compass",icon:ofe},{name:"coffee",icon:Jpe},{name:"gift",icon:Yfe},{name:"wrench",icon:zf},{name:"zap",icon:Xl},{name:"cloud",icon:Jx},{name:"database",icon:Ul},{name:"folder",icon:pQ},{name:"mail",icon:vx},{name:"phone",icon:abe},{name:"user",icon:Wu},{name:"users",icon:_u},{name:"server",icon:Vp},{name:"terminal",icon:kQ},{name:"code",icon:ey}];function TP(t){return AQ.find(n=>n.name===t)?.icon||ny}function Oxe({value:t,onChange:e}){const[n,r]=w.useState(!1),i=TP(t);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{type:"button",onClick:()=>r(!n),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white hover:border-bambu-gray focus:border-bambu-green focus:outline-none w-full",children:[a.jsx(i,{className:"w-5 h-5"}),a.jsx("span",{className:"text-sm text-bambu-gray flex-1 text-left",children:t})]}),n&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>r(!1)}),a.jsx("div",{className:"absolute z-50 mt-1 w-full max-h-64 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg",children:a.jsx("div",{className:"grid grid-cols-5 gap-1 p-2",children:AQ.map(({name:s,icon:o})=>a.jsx("button",{type:"button",onClick:()=>{e(s),r(!1)},className:`p-2 rounded-lg transition-colors flex items-center justify-center ${t===s?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:s,children:a.jsx(o,{className:"w-5 h-5"})},s))})})]})]})}const b6=1144;function Ixe(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<b6:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${b6-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}const MQ=w.createContext(void 0);function zxe({children:t}){const[e,n]=w.useState(null),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!0),d=w.useRef(!1),u=w.useRef(!0),m=async()=>{try{const M=new URLSearchParams(window.location.search),A=M.get("token");if(A){Ib(A),M.delete("token");const C=M.toString(),F=window.location.pathname+(C?`?${C}`:"")+window.location.hash;window.history.replaceState({},"",F)}const T=await pe.getAuthStatus();if(!u.current)return;if(i(T.auth_enabled),o(T.requires_setup),T.auth_enabled)if(Yu())try{const F=await pe.getCurrentUser();if(!u.current)return;n(F)}catch{if(Ib(null),!u.current)return;n(null)}else n(null);else n(null)}catch{if(!u.current)return;i(!1),n(null)}finally{u.current&&c(!1)}};w.useEffect(()=>(u.current=!0,m(),()=>{u.current=!1}),[]),w.useEffect(()=>{if(!l&&s&&!r){const M=window.location.pathname;M!=="/setup"&&!M.startsWith("/camera/")&&!d.current&&(d.current=!0,window.location.href="/setup")}else s||(d.current=!1)},[l,s,r]);const p=async(M,A)=>{const T=await pe.login({username:M,password:A});Ib(T.access_token),await m()},f=()=>{Ib(null),n(null),pe.logout().catch(()=>{}),window.location.href="/login"},y=async()=>{if(r&&Yu())try{const M=await pe.getCurrentUser();u.current&&n(M)}catch{Ib(null),u.current&&n(null)}},v=async()=>{await m()},b=w.useMemo(()=>new Set(e?.permissions??[]),[e?.permissions]),g=w.useMemo(()=>r?e?.is_admin??!1:!0,[r,e?.is_admin]),_=w.useCallback(M=>!r||g?!0:b.has(M),[r,g,b]),k=w.useCallback((...M)=>!r||g?!0:M.some(A=>b.has(A)),[r,g,b]),P=w.useCallback((...M)=>!r||g?!0:M.every(A=>b.has(A)),[r,g,b]),N=w.useCallback((M,A,T)=>{if(!r||g)return!0;const C=`${M}:${A}_all`,F=`${M}:${A}_own`;return b.has(C)?!0:b.has(F)?T==null?!1:T===e?.id:!1},[r,g,b,e?.id]);return a.jsx(MQ.Provider,{value:{user:e,authEnabled:r,requiresSetup:s,loading:l,isAdmin:g,login:p,logout:f,refreshUser:y,refreshAuth:v,hasPermission:_,hasAnyPermission:k,hasAllPermissions:P,canModify:N},children:t})}function _r(){const t=w.useContext(MQ);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function _o(t){if(!Number.isFinite(t)||t<=0)return"0 B";const e=["B","KB","MB","GB","TB"],n=1024,r=Math.floor(Math.log(t)/Math.log(n)),i=t/Math.pow(n,r);return r===0?`${i} ${e[r]}`:`${i.toFixed(1)} ${e[r]}`}const jQ=w.createContext(void 0);function xn(){const t=w.useContext(jQ);if(!t)throw new Error("useToast must be used within a ToastProvider");return t}const x6={success:a.jsx(fr,{className:"w-5 h-5 text-green-400"}),error:a.jsx($a,{className:"w-5 h-5 text-red-400"}),warning:a.jsx(qa,{className:"w-5 h-5 text-yellow-400"}),info:a.jsx(Ks,{className:"w-5 h-5 text-blue-400"}),loading:a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"})},Uxe={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 Bxe({children:t}){const{t:e}=Lt(),[n,r]=w.useState([]),[i,s]=w.useState(!1),[o,l]=w.useState(new Set),c=w.useRef(new Map),d="background-dispatch",u=w.useRef(null);w.useEffect(()=>{const v=c.current;return()=>{v.forEach(b=>clearTimeout(b)),v.clear()}},[]);const m=w.useCallback((v,b="success")=>{const g=Math.random().toString(36).substr(2,9);r(k=>[...k,{id:g,message:v,type:b}]);const _=setTimeout(()=>{r(k=>k.filter(P=>P.id!==g)),c.current.delete(g)},3e3);c.current.set(g,_)},[]),p=w.useCallback((v,b,g="info")=>{r(_=>_.find(P=>P.id===v)?_.map(P=>P.id===v?{...P,message:b,type:g,persistent:!0}:P):[..._,{id:v,message:b,type:g,persistent:!0}])},[]),f=w.useCallback(v=>{const b=c.current.get(v);b&&(clearTimeout(b),c.current.delete(v)),r(g=>g.filter(_=>_.id!==v))},[]),y=w.useCallback(async v=>{l(b=>{const g=new Set(b);return g.add(v),g});try{const b=await pe.cancelBackgroundDispatchJob(v);m(b.status==="cancelling"?e("backgroundDispatch.toast.cancellingUpload"):e("backgroundDispatch.toast.cancelled"),"info")}catch(b){const g=b instanceof Error?b.message:e("backgroundDispatch.toast.cancelFailed");m(g,"error")}finally{l(b=>{const g=new Set(b);return g.delete(v),g})}},[m,e]);return w.useEffect(()=>{const v=(_,k,P)=>{const N=_.findIndex(A=>A.jobId===k);if(N===-1)return[..._,{jobId:k,...P}];const M=[..._];return M[N]={...M[N],...P},M},b=_=>{switch(_){case"failed":return 0;case"processing":return 1;case"dispatched":return 2;case"completed":return 3;case"cancelled":return 4}},g=_=>{const k=_.detail||{},P=k.total??0,N=k.dispatched??0,M=k.processing??0,A=k.completed??0,T=k.failed??0,C=N+M>0,F=P>0&&A+T>=P&&!C,$=k.recent_event?.status;if($==="completed"&&A>0){const I=`first-complete:${A}:${T}`;if(u.current!==I){u.current=I;const X=P-A-T,L=X>0?e("backgroundDispatch.toast.printStartedRemaining",{completed:A,remaining:X}):T>0?e("backgroundDispatch.toast.completeWithFailures",{completed:A,failed:T}):e("backgroundDispatch.toast.completeSuccess",{completed:A});r(ee=>{const me={id:d,message:L,type:T>0?"warning":"success",persistent:!0};return ee.find(ue=>ue.id===d)?ee.map(ue=>ue.id===d?me:ue):[...ee,me]});const te=c.current.get(d);te&&clearTimeout(te);const ae=setTimeout(()=>{r(ee=>ee.filter(me=>me.id!==d)),c.current.delete(d),u.current=null},3e3);c.current.set(d,ae)}return}if(C){u.current=null,r(I=>{const L=I.find(oe=>oe.id===d)?.dispatchData?.jobs||[],te=(k.dispatched_jobs||[]).map(oe=>({jobId:oe.job_id,sourceName:oe.source_name||e("backgroundDispatch.unknownFile"),printerName:oe.printer_name||e("backgroundDispatch.unknownPrinter"),status:"dispatched"})),ee=(k.active_jobs&&k.active_jobs.length>0?k.active_jobs:k.active_job?.job_id?[k.active_job]:[]).filter(oe=>typeof oe.job_id=="number").map(oe=>({jobId:oe.job_id,sourceName:oe.source_name||e("backgroundDispatch.unknownFile"),printerName:oe.printer_name||e("backgroundDispatch.unknownPrinter"),status:"processing",message:oe.message,uploadBytes:oe.upload_bytes,uploadTotalBytes:oe.upload_total_bytes,uploadProgressPct:oe.upload_progress_pct})),me=new Set([...te,...ee].map(oe=>oe.jobId)),le=L.filter(oe=>!me.has(oe.jobId)&&["completed","failed","cancelled"].includes(oe.status));let ue=[...te,...ee,...le];if(k.recent_event?.job_id&&k.recent_event?.status){const oe=k.recent_event.status,be=oe==="cancelled"?"cancelled":oe==="cancelling"?"processing":oe,_e=k.recent_event.source_name||e("backgroundDispatch.unknownFile"),B=k.recent_event.printer_name||e("backgroundDispatch.unknownPrinter");ue=v(ue,k.recent_event.job_id,{status:be,sourceName:_e,printerName:B,message:k.recent_event.message})}ee.forEach(oe=>{ue=v(ue,oe.jobId,{status:"processing",sourceName:oe.sourceName,printerName:oe.printerName,message:oe.message,uploadBytes:oe.uploadBytes,uploadTotalBytes:oe.uploadTotalBytes,uploadProgressPct:oe.uploadProgressPct})});const K={total:P,dispatched:N,processing:M,completed:A,failed:T,jobs:[...ue].sort((oe,be)=>{const _e=b(oe.status)-b(be.status);return _e!==0?_e:oe.jobId-be.jobId})};return I.find(oe=>oe.id===d)?I.map(oe=>oe.id===d?{...oe,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:K}:oe):[...I,{id:d,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:K}]});return}if(F){const I=`${A}:${T}`;if(u.current===I)return;u.current=I;const X=T>0?e("backgroundDispatch.toast.completeWithFailures",{completed:A,failed:T}):e("backgroundDispatch.toast.completeSuccess",{completed:A});r(ae=>{const ee={id:d,message:X,type:T>0?"warning":"success",persistent:!0};return ae.find(le=>le.id===d)?ae.map(le=>le.id===d?ee:le):[...ae,ee]});const L=c.current.get(d);L&&clearTimeout(L);const te=setTimeout(()=>{r(ae=>ae.filter(ee=>ee.id!==d)),c.current.delete(d),u.current=null},3e3);c.current.set(d,te);return}if(!C&&$&&["cancelled","failed","completed","idle"].includes($)&&(r(I=>I.filter(X=>X.id!==d)),u.current=null),k.recent_event?.status==="idle"&&!C&&(r(I=>I.filter(X=>X.id!==d)),u.current=null),C||l(new Set),k.dispatched_jobs){const I=new Set(k.dispatched_jobs.map(X=>X.job_id));l(X=>{const L=new Set;return X.forEach(te=>{I.has(te)&&L.add(te)}),L})}};return window.addEventListener("background-dispatch",g),()=>window.removeEventListener("background-dispatch",g)},[e]),a.jsxs(jQ.Provider,{value:{showToast:m,showPersistentToast:p,dismissToast:f},children:[t,a.jsx("div",{className:"fixed bottom-4 right-20 z-[60] flex flex-col items-end gap-2",children:n.map(v=>a.jsx("div",{className:`rounded-lg border shadow-lg backdrop-blur-sm animate-slide-in ${Uxe[v.type]} ${v.dispatchData?"w-[420px] p-3":"flex items-center gap-3 px-4 py-3"}`,children:v.dispatchData?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"flex items-start gap-2",children:[x6[v.type],a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:e("backgroundDispatch.startingPrints")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:e("backgroundDispatch.progressSummary",{complete:v.dispatchData.completed+v.dispatchData.failed,total:v.dispatchData.total,dispatched:v.dispatchData.dispatched,processing:v.dispatchData.processing})})]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s(b=>!b),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e(i?"backgroundDispatch.expandDetails":"backgroundDispatch.collapseDetails"),children:i?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(v.id),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e("backgroundDispatch.dismissToast"),children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),!i&&a.jsx("div",{className:"mt-3 space-y-2 max-h-64 overflow-y-auto pr-1",children:v.dispatchData.jobs.map(b=>{const g={dispatched:15,processing:60,completed:100,failed:100,cancelled:100},_={dispatched:"bg-bambu-gray/60",processing:"bg-bambu-green",completed:"bg-green-500",failed:"bg-red-500",cancelled:"bg-yellow-500"};return a.jsxs("div",{className:"rounded border border-white/10 bg-black/15 p-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-xs text-white truncate",title:b.sourceName,children:b.sourceName}),a.jsxs("div",{className:"flex items-center gap-2",children:[(b.status==="dispatched"||b.status==="processing")&&a.jsx("button",{onClick:()=>{y(b.jobId)},disabled:o.has(b.jobId),className:"text-[11px] text-red-300 hover:text-red-200 disabled:opacity-50 disabled:cursor-not-allowed",title:e("backgroundDispatch.cancelDispatchJob"),children:o.has(b.jobId)?e("backgroundDispatch.cancelling"):e("backgroundDispatch.cancel")}),a.jsx("span",{className:"text-[11px] uppercase tracking-wide text-bambu-gray",children:e(`backgroundDispatch.status.${b.status}`)})]})]}),a.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:b.printerName,children:b.printerName}),b.message&&a.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:b.message,children:b.message}),b.status==="processing"&&typeof b.uploadBytes=="number"&&typeof b.uploadTotalBytes=="number"&&b.uploadTotalBytes>0&&a.jsxs("div",{className:"text-[11px] text-bambu-gray truncate",children:[_o(b.uploadBytes)," / ",_o(b.uploadTotalBytes),typeof b.uploadProgressPct=="number"?` (${b.uploadProgressPct.toFixed(1)}%)`:""]}),a.jsx("div",{className:"mt-1 h-1.5 w-full rounded bg-white/10 overflow-hidden",children:a.jsx("div",{className:`h-full ${_[b.status]} transition-all duration-300`,style:{width:`${b.status==="processing"&&typeof b.uploadProgressPct=="number"?Math.max(0,Math.min(100,b.uploadProgressPct)):g[b.status]}%`}})})]},b.jobId)})})]}):a.jsxs(a.Fragment,{children:[x6[v.type],a.jsx("span",{className:"text-white text-sm",children:v.message}),a.jsx("button",{onClick:()=>f(v.id),className:"ml-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]})},v.id))})]})}function Hxe(t="system"){const e=t==="system"?EQ():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 qxe(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 V3(t,e="system"){const n=String(t.getDate()).padStart(2,"0"),r=String(t.getMonth()+1).padStart(2,"0"),i=t.getFullYear();switch(e){case"us":return`${r}/${n}/${i}`;case"eu":return`${n}/${r}/${i}`;case"iso":return`${i}-${r}-${n}`;default:return t.toLocaleDateString()}}function y6(t,e="system"){const n=t.getHours(),r=String(t.getMinutes()).padStart(2,"0");switch(e){case"12h":{const i=n%12||12,s=n<12?"AM":"PM";return`${i}:${r} ${s}`}case"24h":return`${String(n).padStart(2,"0")}:${r}`;default:return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function $xe(t){for(const e of["/",".","-"]){const n=t.split(e);if(n.length===3)return n}return null}function EQ(){const t=new Date(2e3,11,31).toLocaleDateString();return t.startsWith("12")?"us":t.startsWith("31")?"eu":"iso"}function Vxe(t,e="system"){if(!t)return null;const n=$xe(t);if(!n)return null;const r=e==="system"?EQ():e;let i,s,o;switch(r){case"us":s=parseInt(n[0],10),i=parseInt(n[1],10),o=parseInt(n[2],10);break;case"eu":i=parseInt(n[0],10),s=parseInt(n[1],10),o=parseInt(n[2],10);break;case"iso":o=parseInt(n[0],10),s=parseInt(n[1],10),i=parseInt(n[2],10);break}return isNaN(i)||isNaN(s)||isNaN(o)||s<1||s>12||i<1||i>31||o<1900||o>2100?null:new Date(o,s-1,i)}function Gxe(t){if(!t)return null;const n=t.trim().match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);if(!n)return null;let r=parseInt(n[1],10);const i=parseInt(n[2],10),s=n[3]?.toUpperCase();return s==="PM"&&r<12&&(r+=12),s==="AM"&&r===12&&(r=0),r<0||r>23||i<0||i>59?null:{hours:r,minutes:i}}function G3(t){const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),i=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}-${n}-${r}T${i}:${s}`}function O0(t,e="system"){return e==="12h"?t.hour12=!0:e==="24h"&&(t.hour12=!1),t}function Qn(t){return t?t.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(t)?new Date(t):new Date(t+"Z"):null}function Uf(t,e){const n=Qn(t);if(!n)return"";const r={year:"numeric",month:"short",day:"numeric"};return n.toLocaleDateString(void 0,e??r)}function Bf(t,e="system",n){const r=Qn(t);if(!r)return"";const s=O0(n??{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},e);return r.toLocaleString(void 0,s)}function DQ(t,e="system",n){const i=O0({...{hour:"2-digit",minute:"2-digit"},...n},e);return t.toLocaleTimeString([],i)}function vO(t,e="system",n){const r=new Date,i=new Date(r.getTime()+t*60*1e3),s=new Date(r);s.setHours(0,0,0,0);const o=new Date(i);o.setHours(0,0,0,0);const l=O0({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 ls(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 Sx(t,e="system",n){if(!t)return n?.("time.unknown")??"-";const r=Qn(t);if(!r)return n?.("time.unknown")??"-";const i=new Date,s=r.getTime()-i.getTime(),o=s<0,l=Math.abs(s),c=Math.floor(l/6e4),d=Math.floor(l/36e5),u=Math.floor(l/864e5);return c<1?o?n?.("time.justNow")??"Just now":n?.("time.now")??"Now":d<1?o?n?.("time.minsAgo",{count:c})??`${c}m ago`:n?.("time.inMins",{count:c})??`in ${c}m`:u<1?o?n?.("time.hoursAgo",{count:d})??`${d}h ago`:n?.("time.inHours",{count:d})??`in ${d}h`:u<7?o?n?.("time.daysAgo",{count:u})??`${u}d ago`:n?.("time.inDays",{count:u})??`in ${u}d`:Bf(t,e)}function nh(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function Wxe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}const hj=1920,Kxe=.7,Yxe=300;function Xxe(t){return new Promise((e,n)=>{const r=new Image;r.onload=()=>{let{width:i,height:s}=r;if(i>hj||s>hj){const d=hj/Math.max(i,s);i=Math.round(i*d),s=Math.round(s*d)}const o=document.createElement("canvas");o.width=i,o.height=s;const l=o.getContext("2d");if(!l){n(new Error("No canvas context"));return}l.drawImage(r,0,0,i,s);const c=o.toDataURL("image/jpeg",Kxe);e(c.replace(/^data:[^;]+;base64,/,""))},r.onerror=n,r.src=URL.createObjectURL(t)})}function Qxe(t){const e=Math.floor(t/60),n=t%60;return`${e.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}function Zxe(){const{t}=Lt(),[e,n]=w.useState(!1),[r,i]=w.useState("form"),[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),[v,b]=w.useState(null),[g,_]=w.useState(""),[k,P]=w.useState(0),[N,M]=w.useState(!1),A=w.useRef(null),T=w.useRef(null),C=w.useRef(()=>{});w.useEffect(()=>{if(r!=="logging")return;if(k>=Yxe){C.current();return}const ue=setTimeout(()=>P(K=>K+1),1e3);return()=>clearTimeout(ue)},[r,k]);const F=()=>{n(!0),i("form"),o(""),c(""),u(null),y(null),b(null),_(""),P(0),M(!1)},$=()=>{n(!1)},I=w.useCallback(async ue=>{if(ue.type.startsWith("image/"))try{const K=await Xxe(ue);u(K)}catch{}},[]),X=w.useCallback(ue=>{const K=ue.clipboardData?.items;if(K){for(const ne of K)if(ne.type.startsWith("image/")){const oe=ne.getAsFile();oe&&I(oe);break}}},[I]),L=w.useCallback(ue=>{ue.preventDefault(),p(!0)},[]),te=w.useCallback(ue=>{ue.preventDefault(),p(!1)},[]),ae=w.useCallback(ue=>{ue.preventDefault(),p(!1);const K=ue.dataTransfer.files?.[0];K&&I(K)},[I]),ee=async()=>{if(s.trim())try{const ue=await mj.startLogging();M(ue.was_debug),P(0),i("logging")}catch(ue){_(ue instanceof Error?ue.message:t("bugReport.unexpectedError")),i("error")}},me=async()=>{i("stopping");try{const ue=await mj.stopLogging(N);await le(ue.logs)}catch(ue){_(ue instanceof Error?ue.message:t("bugReport.unexpectedError")),i("error")}};C.current=me;const le=async ue=>{i("submitting");try{const K=await mj.submit({description:s.trim(),email:l.trim()||void 0,screenshot_base64:d||void 0,include_support_info:!0,debug_logs:ue||void 0});K.success?(y(K.issue_url||null),b(K.issue_number||null),i("success")):(_(K.message),i("error"))}catch(K){_(K instanceof Error?K.message:t("bugReport.unexpectedError")),i("error")}};return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:F,className:"fixed bottom-4 right-4 z-40 w-12 h-12 rounded-full bg-red-500 hover:bg-red-600 text-white shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-110 flex items-center justify-center",title:t("bugReport.title"),children:a.jsx(xx,{className:"w-5 h-5"})}),e&&a.jsx("div",{id:"bug-report-modal",className:"fixed bottom-20 right-4 z-50 w-full max-w-md",onPaste:X,children:a.jsxs("div",{ref: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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10",children:[a.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2",children:[a.jsx(xx,{className:"w-5 h-5 text-red-500"}),t("bugReport.title")]}),a.jsx("button",{onClick:$,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[r==="form"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t("bugReport.description")," *"]}),a.jsx("textarea",{value:s,onChange:ue=>o(ue.target.value),placeholder:t("bugReport.descriptionPlaceholder"),rows:3,className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.email")}),a.jsx("input",{type:"email",value:l,onChange:ue=>c(ue.target.value),placeholder:t("bugReport.emailPlaceholder"),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),a.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:t("bugReport.emailPrivacy")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.screenshot")}),d?a.jsxs("div",{className:"relative",children:[a.jsx("img",{src:`data:image/jpeg;base64,${d}`,alt:t("bugReport.screenshot"),className:"w-full max-h-40 object-contain rounded-lg border border-gray-200 dark:border-gray-600"}),a.jsx("button",{onClick:()=>u(null),className:"absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full shadow",title:t("common.delete"),children:a.jsx(un,{className:"w-3 h-3"})})]}):a.jsxs("button",{type:"button",onClick:()=>T.current?.click(),onDragOver:L,onDragLeave:te,onDrop:ae,className:`w-full flex flex-col items-center gap-2 px-4 py-4 border-2 border-dashed rounded-lg transition-colors cursor-pointer ${m?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-500":"border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400 dark:hover:border-gray-500 hover:text-gray-600 dark:hover:text-gray-300"}`,children:[a.jsx(Ca,{className:"w-5 h-5"}),a.jsx("span",{className:"text-sm",children:t("bugReport.uploadOrPaste")})]}),a.jsx("input",{ref:T,type:"file",accept:"image/*",className:"hidden",onChange:ue=>{const K=ue.target.files?.[0];K&&I(K),ue.target.value=""}})]}),a.jsxs("details",{className:"text-xs bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:[a.jsx("summary",{className:"cursor-pointer font-medium text-amber-700 dark:text-amber-300 hover:text-amber-800 dark:hover:text-amber-200",children:t("bugReport.dataCollectedSummary")}),a.jsxs("div",{className:"mt-2 space-y-2 pl-2 border-l-2 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-200",children:[a.jsx("p",{className:"font-medium",children:t("bugReport.dataIncluded")}),a.jsx("p",{children:t("bugReport.dataIncludedList")}),a.jsx("p",{className:"font-medium",children:t("bugReport.dataNeverIncluded")}),a.jsx("p",{children:t("bugReport.dataNeverIncludedList")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx("button",{onClick:$,className:"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",children:t("common.cancel")}),a.jsx("button",{onClick:ee,disabled:!s.trim(),className:"px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors",children:t("bugReport.startLogging")})]})]}),r==="logging"&&a.jsxs("div",{className:"py-6 space-y-6",children:[a.jsxs("div",{className:"space-y-3 px-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Cc,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),a.jsx("span",{className:"text-sm text-green-700 dark:text-green-400",children:t("bugReport.stepEnableLogging")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"relative flex h-5 w-5 flex-shrink-0 items-center justify-center",children:[a.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),a.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-blue-500"})]}),a.jsx("span",{className:"text-sm font-medium text-blue-700 dark:text-blue-300",children:t("bugReport.stepReproduce")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(R0,{className:"w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0"}),a.jsx("span",{className:"text-sm text-gray-400 dark:text-gray-500",children:t("bugReport.stepStopLogging")})]})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("p",{className:"text-3xl font-mono text-blue-500",children:Qxe(k)}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:t("bugReport.maxDuration",{minutes:5})})]}),a.jsx("div",{className:"flex justify-center",children:a.jsx("button",{onClick:me,className:"px-6 py-2.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors",children:t("bugReport.stopAndSubmit")})})]}),(r==="stopping"||r==="submitting")&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-blue-500"}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t(r==="stopping"?"bugReport.stoppingLogs":"bugReport.submitting")})]}),r==="success"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(fr,{className:"w-12 h-12 text-green-500"}),a.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.thankYou")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("bugReport.submitted")}),f&&a.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-500 hover:text-blue-600 underline",children:[t("bugReport.viewIssue")," #",v]}),a.jsx("button",{onClick:$,className:"mt-4 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",children:t("common.close")})]}),r==="error"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(qa,{className:"w-12 h-12 text-red-500"}),a.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.submitFailed")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center",children:g}),a.jsxs("div",{className:"flex gap-2 mt-4",children:[a.jsx("button",{onClick:()=>i("form"),className:"px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors",children:t("bugReport.submit")}),a.jsx("button",{onClick:$,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 Pu=[{id:"printers",to:"/",icon:Pr,labelKey:"nav.printers"},{id:"archives",to:"/archives",icon:Qs,labelKey:"nav.archives"},{id:"queue",to:"/queue",icon:Wr,labelKey:"nav.queue"},{id:"stats",to:"/stats",icon:_pe,labelKey:"nav.stats"},{id:"profiles",to:"/profiles",icon:Jx,labelKey:"nav.profiles"},{id:"maintenance",to:"/maintenance",icon:zf,labelKey:"nav.maintenance"},{id:"projects",to:"/projects",icon:js,labelKey:"nav.projects"},{id:"inventory",to:"/inventory",icon:pfe,labelKey:"nav.inventory"},{id:"files",to:"/files",icon:Fc,labelKey:"nav.files"},{id:"notifications",to:"/notifications",icon:Ah,labelKey:"nav.notifications"},{id:"settings",to:"/settings",icon:Ow,labelKey:"nav.settings"}];function Jxe(){const t=localStorage.getItem("sidebarOrder");if(t)try{return JSON.parse(t)}catch{return Pu.map(e=>e.id)}return Pu.map(e=>e.id)}function v6(t){localStorage.setItem("sidebarOrder",JSON.stringify(t))}function A_(t){return t.startsWith("ext-")}function FQ(){return localStorage.getItem("defaultView")||"/"}function eye(t){localStorage.setItem("defaultView",t)}function tye(){const t=Eo(),e=Ic(),{mode:n,toggleMode:r}=cg(),{t:i}=Lt(),s=Ixe(),{user:o,authEnabled:l,logout:c,hasPermission:d}=_r(),{showToast:u}=xn(),[m,p]=w.useState(!1),[f,y]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[v,b]=w.useState(!1),[g,_]=w.useState(()=>localStorage.getItem("sidebarExpanded")!=="false"),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[A,T]=w.useState(!1),[C,F]=w.useState(Jxe),[$,I]=w.useState(null),[X,L]=w.useState(null),te=w.useRef(!1),[ae,ee]=w.useState(()=>sessionStorage.getItem("dismissedUpdateVersion")),[me,le]=w.useState(null),{data:ue}=et({queryKey:["version"],queryFn:pe.getVersion,staleTime:1/0}),{data:K}=et({queryKey:["settings"],queryFn:pe.getSettings,staleTime:300*1e3}),{data:ne}=et({queryKey:["default-sidebar-order"],queryFn:pe.getDefaultSidebarOrder,staleTime:300*1e3});w.useEffect(()=>{const ve=ne?.default_sidebar_order;if(!ve||l&&!o)return;const Te=o?`sidebarDefaultApplied_${o.id}`:"sidebarDefaultApplied";if(!localStorage.getItem(Te))try{const Fe=JSON.parse(ve),Ee=Array.isArray(Fe)?Fe:Fe.order;if(!Array.isArray(Ee)||Ee.length===0)return;const Se=new Set(Pu.map(qe=>qe.id)),je=Ee.filter(qe=>typeof qe=="string"&&(Se.has(qe)||A_(qe)));je.length>0&&(F(je),v6(je),localStorage.setItem(Te,"1"))}catch(Fe){console.error("Failed to apply default sidebar order:",Fe)}},[ne?.default_sidebar_order,F,o,l]);const{data:oe}=et({queryKey:["advancedAuthStatus"],queryFn:pe.getAdvancedAuthStatus,staleTime:300*1e3,enabled:l}),{data:be}=et({queryKey:["updateCheck"],queryFn:pe.checkForUpdates,enabled:K?.check_updates!==!1,staleTime:3600*1e3,refetchInterval:3600*1e3}),{data:_e}=et({queryKey:["external-links"],queryFn:pe.getExternalLinks}),{data:B}=et({queryKey:["smart-plugs"],queryFn:pe.getSmartPlugs,staleTime:30*1e3}),Y=B?.some(ve=>ve.show_in_switchbar)??!1,{data:D}=et({queryKey:["debugLogging"],queryFn:nx.getDebugLoggingState,staleTime:60*1e3,refetchInterval:60*1e3}),{data:j}=et({queryKey:["developer-mode-warnings"],queryFn:pe.getDeveloperModeWarnings,staleTime:10*1e3,refetchInterval:30*1e3,refetchOnWindowFocus:!0}),{data:z}=et({queryKey:["queue","pending"],queryFn:()=>pe.getQueue(void 0,"pending"),staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),W=z?.length??0,{data:q}=et({queryKey:["pending-uploads","count"],queryFn:zb.getCount,staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),de=q?.count??0,O=w.useMemo(()=>{const ve=new Set;return z?.forEach(Te=>{Te.printer_id&&ve.add(Te.printer_id)}),Array.from(ve)},[z]),Q=ep({queries:O.map(ve=>({queryKey:["printerStatus",ve],queryFn:()=>pe.getPrinterStatus(ve),staleTime:30*1e3}))}).some(ve=>{const Te=ve.data;return Te?(Te.state==="FINISH"||Te.state==="FAILED")&&!Te.plate_cleared:!1}),[V,J]=w.useState(null);w.useEffect(()=>{if(!D?.enabled||!D.enabled_at){J(null);return}const ve=Qn(D.enabled_at)?.getTime()??Date.now(),Te=()=>{J(Math.floor((Date.now()-ve)/1e3))};Te();const Fe=setInterval(Te,1e3);return()=>clearInterval(Fe)},[D?.enabled,D?.enabled_at]);const ie=w.useMemo(()=>new Map(Pu.map(ve=>[ve.id,ve])),[]),he=w.useMemo(()=>new Map((_e||[]).map(ve=>[`ext-${ve.id}`,ve])),[_e]),fe=(()=>{const ve=[],Te=new Set,Fe={archives:"archives:read",queue:"queue:read",stats:"stats:read",profiles:"kprofiles:read",maintenance:"maintenance:read",projects:"projects:read",inventory:"inventory:read",files:"library:read",settings:"settings:read",notifications:"notifications:user_email"},Ee=Se=>!!(l&&Se in Fe&&!d(Fe[Se])||Se==="notifications"&&(!l||!oe?.advanced_auth_enabled||K?.user_notifications_enabled===!1));for(const Se of C)Ee(Se)||(ie.has(Se)||he.has(Se))&&(ve.push(Se),Te.add(Se));for(const Se of Pu)Ee(Se.id)||Te.has(Se.id)||(ve.push(Se.id),Te.add(Se.id));for(const Se of _e||[]){const je=`ext-${Se.id}`;Te.has(je)||(ve.push(je),Te.add(je))}return ve})(),se=(ve,Te)=>{I(Te),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",Te)},U=(ve,Te)=>{ve.preventDefault(),ve.dataTransfer.dropEffect="move",L(Te)},R=()=>{L(null)},re=(ve,Te)=>{if(ve.preventDefault(),$===null||$===Te){I(null),L(null);return}const Fe=[...fe],Ee=Fe.indexOf($),Se=Fe.indexOf(Te);if(Ee===-1||Se===-1){I(null),L(null);return}Fe.splice(Ee,1),Fe.splice(Se,0,$),F(Fe),v6(Fe),I(null),L(null)},xe=()=>{I(null),L(null)},we=be?.update_available&&be.latest_version&&be.latest_version!==ae,ye=()=>{be?.latest_version&&(sessionStorage.setItem("dismissedUpdateVersion",be.latest_version),ee(be.latest_version))};w.useEffect(()=>{if(!te.current&&e.pathname==="/"){const ve=FQ();ve!=="/"&&(te.current=!0,t(ve,{replace:!0}))}},[e.pathname,t]),w.useEffect(()=>{localStorage.setItem("sidebarExpanded",String(g))},[g]),w.useEffect(()=>{s&&P(!1)},[e.pathname,s]),w.useEffect(()=>{const ve=Te=>{if(!d("printers:control"))return;const Fe=Te.detail;le({printer_id:Fe.printer_id,printer_name:Fe.printer_name,message:Fe.message})};return window.addEventListener("plate-not-empty",ve),()=>window.removeEventListener("plate-not-empty",ve)},[d]);const Ae=w.useCallback(ve=>{const Te=ve.target;if(!(Te.tagName==="INPUT"||Te.tagName==="TEXTAREA"||Te.isContentEditable)&&!ve.metaKey&&!ve.ctrlKey&&!ve.altKey){const Fe=parseInt(ve.key);if(Fe>=1&&Fe<=fe.length&&Fe<=9){const Ee=fe[Fe-1];if(ve.preventDefault(),A_(Ee)){const Se=he.get(Ee);if(Se?.open_in_new_tab)window.open(Se.url,"_blank","noopener,noreferrer");else{const je=Ee.replace("ext-","");t(`/external/${je}`)}}else{const Se=ie.get(Ee);Se&&t(Se.to)}return}switch(ve.key){case"?":ve.preventDefault(),M(!0);break;case"Escape":M(!1);break}}},[t,fe,ie,he]);return w.useEffect(()=>(document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)),[Ae]),a.jsxs("div",{className:"flex min-h-screen",children:[s&&a.jsxs("header",{className:"fixed top-0 left-0 right-0 z-40 h-14 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-4",children:[a.jsx("button",{onClick:()=>P(!0),className:"p-2 -ml-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors","aria-label":"Open menu",children:a.jsx(Hge,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-8 ml-3"})]}),s&&k&&a.jsx("div",{className:"fixed inset-0 bg-black/60 z-40 transition-opacity",onClick:()=>P(!1)}),a.jsxs("aside",{className:`bg-bambu-dark-secondary border-r border-bambu-dark-tertiary flex flex-col transition-all duration-300 ${s?`fixed inset-y-0 left-0 z-50 w-72 transform ${k?"translate-x-0":"-translate-x-full"}`:`fixed inset-y-0 left-0 z-30 ${g?"w-64":"w-16"}`}`,children:[a.jsx("div",{className:`border-b border-bambu-dark-tertiary flex items-center justify-center ${s||g?"p-4":"p-2"}`,children:a.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:s||g?"h-16 w-auto":"h-8 w-8 object-cover object-left"})}),a.jsx("nav",{className:"flex-1 p-2 overflow-y-auto",children:a.jsx("ul",{className:"space-y-2",children:fe.map(ve=>{if(A_(ve)){const Fe=he.get(ve);if(!Fe)return null;const Ee=Fe.custom_icon?null:TP(Fe.icon);return a.jsx("li",{draggable:!0,onDragStart:Se=>se(Se,ve),onDragOver:Se=>U(Se,ve),onDragLeave:R,onDrop:Se=>re(Se,ve),onDragEnd:xe,className:`relative ${$===ve?"opacity-50":""} ${X===ve&&$!==ve?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:Fe.open_in_new_tab?a.jsxs("a",{href:Fe.url,target:"_blank",rel:"noopener noreferrer",className:`flex items-center ${s||g?"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&&!g?Fe.name:void 0,children:[g&&!s&&a.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Fe.custom_icon?a.jsx("img",{src:pe.getExternalLinkIconUrl(Fe.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Ee&&a.jsx(Ee,{className:"w-5 h-5 flex-shrink-0"}),(s||g)&&a.jsx("span",{children:Fe.name})]}):a.jsxs(Gb,{to:`/external/${Fe.id}`,className:({isActive:Se})=>`flex items-center ${s||g?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Se?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!g?Fe.name:void 0,children:[g&&!s&&a.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Fe.custom_icon?a.jsx("img",{src:pe.getExternalLinkIconUrl(Fe.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Ee&&a.jsx(Ee,{className:"w-5 h-5 flex-shrink-0"}),(s||g)&&a.jsx("span",{children:Fe.name})]})},ve)}else{const Fe=ie.get(ve);if(!Fe)return null;const{to:Ee,icon:Se,labelKey:je}=Fe,qe=ve==="queue"&&W>0,Re=ve==="archives"&&de>0,Ye=qe?W:Re?de:0,ce=qe||Re,ze=ve==="printers"&&Q;return a.jsx("li",{draggable:!0,onDragStart:Ne=>se(Ne,ve),onDragOver:Ne=>U(Ne,ve),onDragLeave:R,onDrop:Ne=>re(Ne,ve),onDragEnd:xe,className:`relative ${$===ve?"opacity-50":""} ${X===ve&&$!==ve?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:a.jsxs(Gb,{to:Ee,className:({isActive:Ne})=>`flex items-center ${s||g?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Ne?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!g?i(je):void 0,children:[g&&!s&&a.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),a.jsxs("div",{className:"relative",children:[a.jsx(Se,{className:"w-5 h-5 flex-shrink-0"}),ze&&a.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-yellow-500 rounded-full border-2 border-bambu-dark-secondary"}),ce&&a.jsx("span",{className:`absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 flex items-center justify-center text-[10px] font-bold rounded-full ${Re?"bg-blue-500 text-white":"bg-yellow-500 text-black"}`,children:Ye>99?"99+":Ye})]}),(s||g)&&a.jsx("span",{children:i(je)})]})},ve)}})})}),!s&&a.jsx("button",{onClick:()=>_(!g),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(g?"nav.collapseSidebar":"nav.expandSidebar"),children:g?a.jsx(ol,{className:"w-5 h-5"}):a.jsx(Va,{className:"w-5 h-5"})}),a.jsx("div",{className:"flex-shrink-0 p-2 border-t border-bambu-dark-tertiary",children:s||g?a.jsxs("div",{className:"flex flex-col gap-2 px-2",children:[a.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[Y&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{onMouseEnter:()=>T(!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:a.jsx(ql,{className:"w-5 h-5"})}),A&&a.jsx(g6,{onClose:()=>T(!1)})]}),d("system:read")?a.jsx(Gb,{to:"/system",className:({isActive:ve})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ve?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:a.jsx(Ks,{className:"w-5 h-5"})}):a.jsx("span",{className:"p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed",title:"You do not have permission to view system information",children:a.jsx(Ks,{className:"w-5 h-5"})}),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.viewOnGithub"),children:a.jsx(I3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:()=>M(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.keyboardShortcuts"),children:a.jsx(z3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?a.jsx(h6,{className:"w-5 h-5"}):a.jsx(aN,{className:"w-5 h-5"})}),l&&o&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>p(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("changePassword.title"),children:a.jsx(El,{className:"w-5 h-5"})}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.logout",{defaultValue:"Logout"}),children:a.jsx(B3,{className:"w-5 h-5"})})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:["v",ue?.version||"..."]}),be?.update_available&&a.jsxs("button",{onClick:()=>t("/settings"),className:"flex items-center gap-1 text-xs text-bambu-green hover:text-bambu-green/80 transition-colors",title:i("nav.updateAvailable",{version:be.latest_version}),children:[a.jsx(dj,{className:"w-4 h-4"}),a.jsx("span",{children:i("nav.update")})]})]})]}):a.jsxs("div",{className:"flex flex-col items-center gap-1 overflow-y-auto max-h-[50vh]",children:[be?.update_available&&a.jsx("button",{onClick:()=>t("/settings"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-green hover:text-bambu-green/80",title:i("nav.updateAvailable",{version:be.latest_version}),children:a.jsx(dj,{className:"w-5 h-5"})}),Y&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{onMouseEnter:()=>T(!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:a.jsx(ql,{className:"w-5 h-5"})}),A&&a.jsx(g6,{onClose:()=>T(!1)})]}),d("system:read")?a.jsx(Gb,{to:"/system",className:({isActive:ve})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ve?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:a.jsx(Ks,{className:"w-5 h-5"})}):a.jsx("span",{className:"p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed",title:"You do not have permission to view system information",children:a.jsx(Ks,{className:"w-5 h-5"})}),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.viewOnGithub"),children:a.jsx(I3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:()=>M(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.keyboardShortcuts"),children:a.jsx(z3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?a.jsx(h6,{className:"w-5 h-5"}):a.jsx(aN,{className:"w-5 h-5"})}),l&&o&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>p(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("changePassword.title"),children:a.jsx(El,{className:"w-5 h-5"})}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.logout",{defaultValue:"Logout"}),children:a.jsx(B3,{className:"w-5 h-5"})})]})]})})]}),a.jsxs("main",{className:`flex-1 bg-bambu-dark overflow-auto transition-all duration-300 ${s?"mt-14":g?"ml-64":"ml-16"}`,children:[D?.enabled&&a.jsx("div",{className:"bg-amber-500/20 border-b border-amber-500/30 px-4 py-2 flex items-center justify-between",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(xx,{className:"w-4 h-4 text-amber-500 animate-pulse"}),a.jsxs("span",{className:"text-amber-200",children:[i("support.debugLoggingActive",{defaultValue:"Debug logging is active"}),V!==null&&a.jsxs("span",{className:"text-amber-300/70 ml-2",children:["(",Math.floor(V/60),"m ",V%60,"s)"]})]}),a.jsx("button",{onClick:()=>t("/system"),className:"text-amber-400 hover:text-amber-300 font-medium underline ml-2",children:i("support.manageLogs",{defaultValue:"Manage"})})]})}),j&&j.length>0&&a.jsx("div",{className:"bg-orange-500/20 border-b border-orange-500/30 px-4 py-2 flex items-center justify-between",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Mbe,{className:"w-4 h-4 text-orange-500"}),a.jsx("span",{className:"text-orange-200",children:i("printers.developerModeWarning",{names:j.map(ve=>ve.name).join(", "),defaultValue:`Developer LAN mode is not enabled on: ${j.map(ve=>ve.name).join(", ")}. Some features may not work.`})}),a.jsx("a",{href:"https://wiki.bambulab.com/en/knowledge-sharing/enable-developer-mode",target:"_blank",rel:"noopener noreferrer",className:"text-orange-400 hover:text-orange-300 font-medium underline ml-2",children:i("printers.howToEnable",{defaultValue:"How to enable"})})]})}),we&&a.jsxs("div",{className:"bg-bambu-green/20 border-b border-bambu-green/30 px-4 py-2 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(dj,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{children:i("nav.updateAvailableBanner",{version:be?.latest_version,defaultValue:`Version ${be?.latest_version} is available!`})}),a.jsx("button",{onClick:()=>t("/settings"),className:"text-bambu-green hover:text-bambu-green/80 font-medium underline",children:i("nav.viewUpdate",{defaultValue:"View update"})})]}),a.jsx("button",{onClick:ye,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:i("common.dismiss",{defaultValue:"Dismiss"}),children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsx(qX,{})]}),N&&a.jsx(Rxe,{onClose:()=>M(!1),sidebarItems:fe.map(ve=>{if(A_(ve)){const Te=he.get(ve);return Te?{type:"external",label:Te.name}:null}else{const Te=ie.get(ve);return Te?{type:"nav",label:Te.labelKey,labelKey:Te.labelKey}:null}}).filter(Boolean)}),me&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4",children:a.jsx("div",{className:"bg-bambu-dark-secondary border-2 border-yellow-500 rounded-xl shadow-2xl max-w-md w-full animate-in fade-in zoom-in duration-200",children:a.jsxs("div",{className:"p-6 text-center",children:[a.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-10 h-10 text-yellow-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),a.jsx("h2",{className:"text-xl font-bold text-yellow-400 mb-2",children:i("plateAlert.title")}),a.jsx("p",{className:"text-lg text-white mb-2",children:me.printer_name}),a.jsx("p",{className:"text-bambu-gray mb-6",children:i("plateAlert.message")}),a.jsx("button",{onClick:()=>le(null),className:"w-full py-3 px-6 bg-yellow-500 hover:bg-yellow-600 text-black font-semibold rounded-lg transition-colors",children:i("plateAlert.understand")})]})})}),m&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{p(!1),y({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(El,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("changePassword.title")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{p(!1),y({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.currentPassword")}),a.jsx("input",{type:"password",value:f.currentPassword,onChange:ve=>y({...f,currentPassword:ve.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("changePassword.currentPasswordPlaceholder"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.newPassword")}),a.jsx("input",{type:"password",value:f.newPassword,onChange:ve=>y({...f,newPassword:ve.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("changePassword.newPasswordPlaceholder"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.confirmPassword")}),a.jsx("input",{type:"password",value:f.confirmPassword,onChange:ve=>y({...f,confirmPassword:ve.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${f.confirmPassword&&f.newPassword!==f.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("changePassword.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),f.confirmPassword&&f.newPassword!==f.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("changePassword.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>{p(!1),y({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),a.jsx(Ie,{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 pe.changePassword(f.currentPassword,f.newPassword),u(i("changePassword.success"),"success"),p(!1),y({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ve){const Te=ve instanceof Error?ve.message:i("changePassword.failed");u(Te,"error")}finally{b(!1)}},disabled:v||!f.currentPassword||!f.newPassword||f.newPassword!==f.confirmPassword||f.newPassword.length<6,children:v?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("changePassword.changing")]}):a.jsxs(a.Fragment,{children:[a.jsx(El,{className:"w-4 h-4"}),i("changePassword.title")]})})]})]})]})}),a.jsx(Zxe,{})]})}const W3={"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 nye(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:Ln};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:Ln};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:qa};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:Ks}}}function K3(t,e){const n=t>>16&65535||(t>>8&255)<<8|t&255,r=e&65535;return`${n.toString(16).padStart(4,"0").toUpperCase()}_${r.toString(16).padStart(4,"0").toUpperCase()}`}function Tu(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,r=K3(e.attr,n);return W3[r]!==void 0})}function rye(){return"https://wiki.bambulab.com/en/hms/home"}function aye({printerName:t,errors:e,onClose:n,printerId:r,hasPermission:i}){const{t:s}=Lt(),{showToast:o}=xn(),l=lt({mutationFn:()=>pe.clearHMSErrors(r),onSuccess:()=>{o(s("hmsErrors.clearSuccess"),"success"),n()},onError:()=>{o(s("hmsErrors.clearFailed"),"error")}}),c=e.filter(d=>{const u=parseInt(d.code.replace("0x",""),16)||0,m=K3(d.attr,u);return W3[m]!==void 0});return w.useEffect(()=>{const d=u=>{u.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ln,{className:"w-5 h-5 text-orange-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(qa,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{children:s("hmsErrors.noErrors")})]}):a.jsx("div",{className:"space-y-3",children:c.map((d,u)=>{const{label:m,color:p,bgColor:f,Icon:y}=nye(d.severity),v=parseInt(d.code.replace("0x",""),16)||0,b=K3(d.attr,v),g=W3[b],_=rye(),k=b.replace("_","-");return a.jsx("div",{className:`p-4 rounded-lg ${f} border border-white/10`,children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(y,{className:`w-5 h-5 ${p} flex-shrink-0 mt-0.5`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`font-mono text-sm ${p}`,children:["[",k,"]"]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${f} ${p}`,children:m})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g}),a.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[a.jsx(sa,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${d.code}-${u}`)})})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&a.jsxs("button",{onClick:()=>l.mutate(),disabled:!i("printers:control")||l.isPending,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",children:[l.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}const iye=[{key:"printing",dot:"bg-bambu-green"},{key:"paused",dot:"bg-status-warning"},{key:"finished",dot:"bg-blue-400"},{key:"idle",dot:"bg-bambu-green"},{key:"error",dot:"bg-status-error"},{key:"offline",dot:"bg-gray-400"}];function sye({selectedIds:t,printers:e,onClose:n,onSelectAll:r,onSelectByLocation:i,onSelectByState:s,onAction:o,actionPending:l}){const{t:c}=Lt(),{hasPermission:d}=_r(),u=mn(),[m,p]=w.useState(!1),[f,y]=w.useState(!1),v=Array.from(t).map(F=>({id:F,status:u.getQueryData(["printerStatus",F])})),b=v.some(({status:F})=>F?.connected&&F.state==="RUNNING"),g=v.some(({status:F})=>F?.connected&&F.state==="PAUSE"),_=b||g,k=v.some(({status:F})=>F?.connected&&(F.state==="FINISH"||F.state==="FAILED")&&!F.plate_cleared),P=v.some(({status:F})=>!F?.connected||!F.hms_errors?!1:Tu(F.hms_errors).length>0),N=d("printers:control"),M=d("printers:clear_plate"),A=[...new Set(e.map(F=>F.location).filter(F=>!!F))].sort(),T={printing:0,paused:0,finished:0,idle:0,error:0,offline:0};e.forEach(F=>{const $=u.getQueryData(["printerStatus",F.id]);if(!$||!$.connected){T.offline++;return}switch($.hms_errors&&Tu($.hms_errors).length>0&&T.error++,$.state){case"RUNNING":T.printing++;break;case"PAUSE":T.paused++;break;case"FINISH":T.finished++;break;case"FAILED":T.error++;break;default:T.idle++;break}});const C={printing:c("printers.status.printing"),paused:c("printers.status.paused","Paused"),finished:c("printers.status.finished","Finished"),idle:c("printers.status.available"),error:c("printers.status.problem"),offline:c("printers.status.offline")};return a.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-3 flex-wrap",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:n,children:a.jsx(Bt,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-white font-medium text-sm",children:c("printers.bulk.selected",{count:t.size})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:r,children:c("printers.bulk.selectAll")}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>{y(!f),p(!1)},children:[c("printers.bulk.selectByState"),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${f?"rotate-180":""}`})]}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),a.jsx("div",{className:"absolute bottom-full mb-2 left-0 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:iye.filter(({key:F})=>T[F]>0).map(({key:F,dot:$})=>a.jsxs("button",{onClick:()=>{s(F),y(!1)},className:"w-full text-left px-3 py-2 text-sm text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white transition-colors flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${$}`}),C[F],a.jsx("span",{className:"ml-auto text-bambu-gray text-xs",children:T[F]})]},F))})]})]}),A.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>{p(!m),y(!1)},children:[c("printers.bulk.selectByLocation"),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${m?"rotate-180":""}`})]}),m&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),a.jsx("div",{className:"absolute bottom-full mb-2 left-0 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:A.map(F=>a.jsx("button",{onClick:()=>{i(F),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:F},F))})]})]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Ie,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>o("stop"),disabled:l||!N||!_,title:N?_?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(eo,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.stop")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>o("pause"),disabled:l||!N||!b,title:N?b?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(Fw,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.pause")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>o("resume"),disabled:l||!N||!g,title:N?g?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(Ds,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.resume")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>o("clearHMS"),disabled:l||!N||!P,title:N?P?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(ape,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearHMS")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>o("clearPlate"),disabled:l||!M||!k,title:M?k?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(Sfe,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearPlate")]})]})}const wO="181",rx={ROTATE:0,DOLLY:1,PAN:2},Kb={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},oye=0,w6=1,lye=2,RQ=1,cye=2,bu=3,$h=0,Co=1,ud=2,Ou=0,ax=1,S6=2,_6=3,k6=4,dye=5,Zp=100,uye=101,mye=102,hye=103,pye=104,fye=200,gye=201,bye=202,xye=203,Y3=204,X3=205,yye=206,vye=207,wye=208,Sye=209,_ye=210,kye=211,Nye=212,Cye=213,Pye=214,Q3=0,Z3=1,J3=2,_x=3,eF=4,tF=5,nF=6,rF=7,SO=0,Tye=1,Aye=2,Dh=0,Mye=1,jye=2,Eye=3,Dye=4,Fye=5,Rye=6,Lye=7,LQ=300,kx=301,Nx=302,aF=303,iF=304,AP=306,sF=1e3,Au=1001,oF=1002,nl=1003,Oye=1004,M_=1005,Bl=1006,pj=1007,sf=1008,Cd=1009,OQ=1010,IQ=1011,I0=1012,_O=1013,Hf=1014,Mu=1015,ry=1016,kO=1017,NO=1018,z0=1020,zQ=35902,UQ=35899,BQ=1021,HQ=1022,Tc=1023,U0=1026,B0=1027,qQ=1028,CO=1029,PO=1030,TO=1031,AO=1033,vk=33776,wk=33777,Sk=33778,_k=33779,lF=35840,cF=35841,dF=35842,uF=35843,mF=36196,hF=37492,pF=37496,fF=37808,gF=37809,bF=37810,xF=37811,yF=37812,vF=37813,wF=37814,SF=37815,_F=37816,kF=37817,NF=37818,CF=37819,PF=37820,TF=37821,AF=36492,MF=36494,jF=36495,EF=36283,DF=36284,FF=36285,RF=36286,Iye=3200,zye=3201,$Q=0,Uye=1,uh="",Qo="srgb",Cx="srgb-linear",lN="linear",Hr="srgb",Qg=7680,N6=519,Bye=512,Hye=513,qye=514,VQ=515,$ye=516,Vye=517,Gye=518,Wye=519,C6=35044,P6="300 es",pd=2e3,cN=2001;function GQ(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function dN(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Kye(){const t=dN("canvas");return t.style.display="block",t}const T6={};function A6(...t){const e="THREE."+t.shift();console.log(e,...t)}function Un(...t){const e="THREE."+t.shift();console.warn(e,...t)}function Xa(...t){const e="THREE."+t.shift();console.error(e,...t)}function H0(...t){const e=t.join(" ");e in T6||(T6[e]=!0,Un(...t))}function Yye(t,e,n){return new Promise(function(r,i){function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}}setTimeout(s,n)})}let dg=class{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(n)===-1&&r[e].push(n)}hasEventListener(e,n){const r=this._listeners;return r===void 0?!1:r[e]!==void 0&&r[e].indexOf(n)!==-1}removeEventListener(e,n){const r=this._listeners;if(r===void 0)return;const i=r[e];if(i!==void 0){const s=i.indexOf(n);s!==-1&&i.splice(s,1)}}dispatchEvent(e){const n=this._listeners;if(n===void 0)return;const r=n[e.type];if(r!==void 0){e.target=this;const i=r.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}};const ws=["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"],kk=Math.PI/180,LF=180/Math.PI;function Iw(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(ws[t&255]+ws[t>>8&255]+ws[t>>16&255]+ws[t>>24&255]+"-"+ws[e&255]+ws[e>>8&255]+"-"+ws[e>>16&15|64]+ws[e>>24&255]+"-"+ws[n&63|128]+ws[n>>8&255]+"-"+ws[n>>16&255]+ws[n>>24&255]+ws[r&255]+ws[r>>8&255]+ws[r>>16&255]+ws[r>>24&255]).toLowerCase()}function mr(t,e,n){return Math.max(e,Math.min(n,t))}function Xye(t,e){return(t%e+e)%e}function fj(t,e,n){return(1-n)*t+n*e}function uv(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 bo(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 Qye={DEG2RAD:kk};let tr=class WQ{constructor(e=0,n=0){WQ.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=mr(this.x,e.x,n.x),this.y=mr(this.y,e.y,n.y),this}clampScalar(e,n){return this.x=mr(this.x,e,n),this.y=mr(this.y,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(mr(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(mr(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},qf=class{constructor(e=0,n=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=i}static slerpFlat(e,n,r,i,s,o,l){let c=r[i+0],d=r[i+1],u=r[i+2],m=r[i+3],p=s[o+0],f=s[o+1],y=s[o+2],v=s[o+3];if(l<=0){e[n+0]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m;return}if(l>=1){e[n+0]=p,e[n+1]=f,e[n+2]=y,e[n+3]=v;return}if(m!==v||c!==p||d!==f||u!==y){let b=c*p+d*f+u*y+m*v;b<0&&(p=-p,f=-f,y=-y,v=-v,b=-b);let g=1-l;if(b<.9995){const _=Math.acos(b),k=Math.sin(_);g=Math.sin(g*_)/k,l=Math.sin(l*_)/k,c=c*g+p*l,d=d*g+f*l,u=u*g+y*l,m=m*g+v*l}else{c=c*g+p*l,d=d*g+f*l,u=u*g+y*l,m=m*g+v*l;const _=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=_,d*=_,u*=_,m*=_}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,r,i,s,o){const l=r[i],c=r[i+1],d=r[i+2],u=r[i+3],m=s[o],p=s[o+1],f=s[o+2],y=s[o+3];return e[n]=l*y+u*m+c*f-d*p,e[n+1]=c*y+u*p+d*m-l*f,e[n+2]=d*y+u*f+l*p-c*m,e[n+3]=u*y-l*m-c*p-d*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,i){return this._x=e,this._y=n,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const r=e._x,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(r/2),u=l(i/2),m=l(s/2),p=c(r/2),f=c(i/2),y=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m-p*f*y;break;case"YXZ":this._x=p*u*m+d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m+p*f*y;break;case"ZXY":this._x=p*u*m-d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m-p*f*y;break;case"ZYX":this._x=p*u*m-d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m+p*f*y;break;case"YZX":this._x=p*u*m+d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m-p*f*y;break;case"XZY":this._x=p*u*m-d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m+p*f*y;break;default:Un("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],l=n[5],c=n[9],d=n[2],u=n[6],m=n[10],p=r+l+m;if(p>0){const f=.5/Math.sqrt(p+1);this._w=.25/f,this._x=(u-c)*f,this._y=(s-d)*f,this._z=(o-i)*f}else if(r>l&&r>m){const f=2*Math.sqrt(1+r-l-m);this._w=(u-c)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+d)/f}else if(l>m){const f=2*Math.sqrt(1+l-r-m);this._w=(s-d)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(c+u)/f}else{const f=2*Math.sqrt(1+m-r-l);this._w=(o-i)/f,this._x=(s+d)/f,this._y=(c+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return r<1e-8?(r=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(mr(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,i=e._y,s=e._z,o=e._w,l=n._x,c=n._y,d=n._z,u=n._w;return this._x=r*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-r*d,this._z=s*u+o*d+r*c-i*l,this._w=o*u-r*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n<=0)return this;if(n>=1)return this.copy(e);let r=e._x,i=e._y,s=e._z,o=e._w,l=this.dot(e);l<0&&(r=-r,i=-i,s=-s,o=-o,l=-l);let c=1-n;if(l<.9995){const d=Math.acos(l),u=Math.sin(d);c=Math.sin(c*d)/u,n=Math.sin(n*d)/u,this._x=this._x*c+r*n,this._y=this._y*c+i*n,this._z=this._z*c+s*n,this._w=this._w*c+o*n,this._onChangeCallback()}else this._x=this._x*c+r*n,this._y=this._y*c+i*n,this._z=this._z*c+s*n,this._w=this._w*c+o*n,this.normalize();return this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(n),s*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},At=class KQ{constructor(e=0,n=0,r=0){KQ.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(M6.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(M6.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*r),u=2*(l*n-s*i),m=2*(s*r-o*n);return this.x=n+c*d+o*m-l*u,this.y=r+c*u+l*d-s*m,this.z=i+c*m+s*u-o*d,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=mr(this.x,e.x,n.x),this.y=mr(this.y,e.y,n.y),this.z=mr(this.z,e.z,n.z),this}clampScalar(e,n){return this.x=mr(this.x,e,n),this.y=mr(this.y,e,n),this.z=mr(this.z,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(mr(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,i=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=i*c-s*l,this.y=s*o-r*c,this.z=r*l-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return gj.copy(this).projectOnVector(e),this.sub(gj)}reflect(e){return this.sub(gj.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(mr(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,r=Math.sqrt(1-n*n);return this.x=r*Math.cos(e),this.y=n,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};const gj=new At,M6=new qf;let ir=class YQ{constructor(e,n,r,i,s,o,l,c,d){YQ.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d)}set(e,n,r,i,s,o,l,c,d){const u=this.elements;return u[0]=e,u[1]=i,u[2]=l,u[3]=n,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=d,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],d=r[1],u=r[4],m=r[7],p=r[2],f=r[5],y=r[8],v=i[0],b=i[3],g=i[6],_=i[1],k=i[4],P=i[7],N=i[2],M=i[5],A=i[8];return s[0]=o*v+l*_+c*N,s[3]=o*b+l*k+c*M,s[6]=o*g+l*P+c*A,s[1]=d*v+u*_+m*N,s[4]=d*b+u*k+m*M,s[7]=d*g+u*P+m*A,s[2]=p*v+f*_+y*N,s[5]=p*b+f*k+y*M,s[8]=p*g+f*P+y*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],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8];return n*o*u-n*l*d-r*s*u+r*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=u*o-l*d,p=l*c-u*s,f=d*s-o*c,y=n*m+r*p+i*f;if(y===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/y;return e[0]=m*v,e[1]=(i*d-u*r)*v,e[2]=(l*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*c)*v,e[5]=(i*s-l*n)*v,e[6]=f*v,e[7]=(r*c-d*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(r*c,r*d,-r*(c*o+d*l)+o+e,-i*d,i*c,-i*(-d*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(bj.makeScale(e,n)),this}rotate(e){return this.premultiply(bj.makeRotation(-e)),this}translate(e,n){return this.premultiply(bj.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<9;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}};const bj=new ir,j6=new ir().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),E6=new ir().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Zye(){const t={enabled:!0,workingColorSpace:Cx,spaces:{},convert:function(i,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Hr&&(i.r=Iu(i.r),i.g=Iu(i.g),i.b=Iu(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===Hr&&(i.r=ix(i.r),i.g=ix(i.g),i.b=ix(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?lN: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 H0("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return H0("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return t.define({[Cx]:{primaries:e,whitePoint:r,transfer:lN,toXYZ:j6,fromXYZ:E6,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Qo},outputColorSpaceConfig:{drawingBufferColorSpace:Qo}},[Qo]:{primaries:e,whitePoint:r,transfer:Hr,toXYZ:j6,fromXYZ:E6,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Qo}}}),t}const Cr=Zye();function Iu(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function ix(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let Zg,Jye=class{static getDataURL(e,n="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let r;if(e instanceof HTMLCanvasElement)r=e;else{Zg===void 0&&(Zg=dN("canvas")),Zg.width=e.width,Zg.height=e.height;const i=Zg.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),r=Zg}return r.toDataURL(n)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=dN("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=Iu(s[o]/255)*255;return r.putImageData(i,0,0),n}else if(e.data){const n=e.data.slice(0);for(let r=0;r<n.length;r++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[r]=Math.floor(Iu(n[r]/255)*255):n[r]=Iu(n[r]);return{data:n,width:e.width,height:e.height}}else return Un("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},eve=0,MO=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:eve++}),this.uuid=Iw(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const n=this.data;return typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?e.set(n.videoWidth,n.videoHeight,0):n instanceof VideoFrame?e.set(n.displayHeight,n.displayWidth,0):n!==null?e.set(n.width,n.height,n.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const r={uuid:this.uuid,url:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,l=i.length;o<l;o++)i[o].isDataTexture?s.push(xj(i[o].image)):s.push(xj(i[o]))}else s=xj(i);r.url=s}return n||(e.images[this.uuid]=r),r}};function xj(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?Jye.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(Un("Texture: Unable to serialize Texture."),{})}let tve=0;const yj=new At;let zc=class Nk extends dg{constructor(e=Nk.DEFAULT_IMAGE,n=Nk.DEFAULT_MAPPING,r=Au,i=Au,s=Bl,o=sf,l=Tc,c=Cd,d=Nk.DEFAULT_ANISOTROPY,u=uh){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:tve++}),this.uuid=Iw(),this.name="",this.source=new MO(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new tr(0,0),this.repeat=new tr(1,1),this.center=new tr(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ir,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(yj).x}get height(){return this.source.getSize(yj).y}get depth(){return this.source.getSize(yj).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const n in e){const r=e[n];if(r===void 0){Un(`Texture.setValues(): parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){Un(`Texture.setValues(): property '${n}' does not exist.`);continue}i&&r&&i.isVector2&&r.isVector2||i&&r&&i.isVector3&&r.isVector3||i&&r&&i.isMatrix3&&r.isMatrix3?i.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const r={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==LQ)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case sF:e.x=e.x-Math.floor(e.x);break;case Au:e.x=e.x<0?0:1;break;case oF: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 sF:e.y=e.y-Math.floor(e.y);break;case Au:e.y=e.y<0?0:1;break;case oF: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++}};zc.DEFAULT_IMAGE=null;zc.DEFAULT_MAPPING=LQ;zc.DEFAULT_ANISOTROPY=1;let ii=class XQ{constructor(e=0,n=0,r=0,i=1){XQ.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,i){return this.x=e,this.y=n,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],y=c[9],v=c[2],b=c[6],g=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-v)<.01&&Math.abs(y-b)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+v)<.1&&Math.abs(y+b)<.1&&Math.abs(d+f+g-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const k=(d+1)/2,P=(f+1)/2,N=(g+1)/2,M=(u+p)/4,A=(m+v)/4,T=(y+b)/4;return k>P&&k>N?k<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(k),i=M/r,s=A/r):P>N?P<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(P),r=M/i,s=T/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=A/s,i=T/s),this.set(r,i,s,n),this}let _=Math.sqrt((b-y)*(b-y)+(m-v)*(m-v)+(p-u)*(p-u));return Math.abs(_)<.001&&(_=1),this.x=(b-y)/_,this.y=(m-v)/_,this.z=(p-u)/_,this.w=Math.acos((d+f+g-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=mr(this.x,e.x,n.x),this.y=mr(this.y,e.y,n.y),this.z=mr(this.z,e.z,n.z),this.w=mr(this.w,e.w,n.w),this}clampScalar(e,n){return this.x=mr(this.x,e,n),this.y=mr(this.y,e,n),this.z=mr(this.z,e,n),this.w=mr(this.w,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(mr(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},nve=class extends dg{constructor(e=1,n=1,r={}){super(),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Bl,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},r),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=r.depth,this.scissor=new ii(0,0,e,n),this.scissorTest=!1,this.viewport=new ii(0,0,e,n);const i={width:e,height:n,depth:r.depth},s=new zc(i);this.textures=[];const o=r.count;for(let l=0;l<o;l++)this.textures[l]=s.clone(),this.textures[l].isRenderTargetTexture=!0,this.textures[l].renderTarget=this;this._setTextureOptions(r),this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.resolveDepthBuffer=r.resolveDepthBuffer,this.resolveStencilBuffer=r.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=r.depthTexture,this.samples=r.samples,this.multiview=r.multiview}_setTextureOptions(e={}){const n={minFilter:Bl,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(n.mapping=e.mapping),e.wrapS!==void 0&&(n.wrapS=e.wrapS),e.wrapT!==void 0&&(n.wrapT=e.wrapT),e.wrapR!==void 0&&(n.wrapR=e.wrapR),e.magFilter!==void 0&&(n.magFilter=e.magFilter),e.minFilter!==void 0&&(n.minFilter=e.minFilter),e.format!==void 0&&(n.format=e.format),e.type!==void 0&&(n.type=e.type),e.anisotropy!==void 0&&(n.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(n.colorSpace=e.colorSpace),e.flipY!==void 0&&(n.flipY=e.flipY),e.generateMipmaps!==void 0&&(n.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(n.internalFormat=e.internalFormat);for(let r=0;r<this.textures.length;r++)this.textures[r].setValues(n)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,n,r=1){if(this.width!==e||this.height!==n||this.depth!==r){this.width=e,this.height=n,this.depth=r;for(let i=0,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=n,this.textures[i].image.depth=r,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,n),this.scissor.set(0,0,e,n)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let n=0,r=e.textures.length;n<r;n++){this.textures[n]=e.textures[n].clone(),this.textures[n].isRenderTargetTexture=!0,this.textures[n].renderTarget=this;const i=Object.assign({},e.textures[n].image);this.textures[n].source=new MO(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"})}},$f=class extends nve{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}},QQ=class extends zc{constructor(e=null,n=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=nl,this.minFilter=nl,this.wrapR=Au,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},rve=class extends zc{constructor(e=null,n=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=nl,this.minFilter=nl,this.wrapR=Au,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Fh=class{constructor(e=new At(1/0,1/0,1/0),n=new At(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n+=3)this.expandByPoint(hc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(hc.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const r=hc.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}setFromObject(e,n=!1){return this.makeEmpty(),this.expandByObject(e,n)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,n=!1){e.updateWorldMatrix(!1,!1);const r=e.geometry;if(r!==void 0){const s=r.getAttribute("position");if(n===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,l=s.count;o<l;o++)e.isMesh===!0?e.getVertexPosition(o,hc):hc.fromBufferAttribute(s,o),hc.applyMatrix4(e.matrixWorld),this.expandByPoint(hc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),j_.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),j_.copy(r.boundingBox)),j_.applyMatrix4(e.matrixWorld),this.union(j_)}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,hc),hc.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(mv),E_.subVectors(this.max,mv),Jg.subVectors(e.a,mv),eb.subVectors(e.b,mv),tb.subVectors(e.c,mv),Um.subVectors(eb,Jg),Bm.subVectors(tb,eb),jp.subVectors(Jg,tb);let n=[0,-Um.z,Um.y,0,-Bm.z,Bm.y,0,-jp.z,jp.y,Um.z,0,-Um.x,Bm.z,0,-Bm.x,jp.z,0,-jp.x,-Um.y,Um.x,0,-Bm.y,Bm.x,0,-jp.y,jp.x,0];return!vj(n,Jg,eb,tb,E_)||(n=[1,0,0,0,1,0,0,0,1],!vj(n,Jg,eb,tb,E_))?!1:(D_.crossVectors(Um,Bm),n=[D_.x,D_.y,D_.z],vj(n,Jg,eb,tb,E_))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,hc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(hc).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:(tu[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),tu[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),tu[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),tu[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),tu[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),tu[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),tu[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),tu[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(tu),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 tu=[new At,new At,new At,new At,new At,new At,new At,new At],hc=new At,j_=new Fh,Jg=new At,eb=new At,tb=new At,Um=new At,Bm=new At,jp=new At,mv=new At,E_=new At,D_=new At,Ep=new At;function vj(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){Ep.fromArray(t,s);const l=i.x*Math.abs(Ep.x)+i.y*Math.abs(Ep.y)+i.z*Math.abs(Ep.z),c=e.dot(Ep),d=n.dot(Ep),u=r.dot(Ep);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const ave=new Fh,hv=new At,wj=new At;let MP=class{constructor(e=new At,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):ave.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const n=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=n*n}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,n){const r=this.center.distanceToSquared(e);return n.copy(e),r>this.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;hv.subVectors(e,this.center);const n=hv.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(hv,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(wj.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(hv.copy(e.center).add(wj)),this.expandByPoint(hv.copy(e.center).sub(wj))),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 nu=new At,Sj=new At,F_=new At,Hm=new At,_j=new At,R_=new At,kj=new At;let jO=class{constructor(e=new At,n=new At(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,nu)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=nu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(nu.copy(this.origin).addScaledVector(this.direction,n),nu.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){Sj.copy(e).add(n).multiplyScalar(.5),F_.copy(n).sub(e).normalize(),Hm.copy(this.origin).sub(Sj);const s=e.distanceTo(n)*.5,o=-this.direction.dot(F_),l=Hm.dot(this.direction),c=-Hm.dot(F_),d=Hm.lengthSq(),u=Math.abs(1-o*o);let m,p,f,y;if(u>0)if(m=o*c-l,p=o*l-c,y=s*u,m>=0)if(p>=-y)if(p<=y){const v=1/u;m*=v,p*=v,f=m*(m+o*p+2*l)+p*(o*m+p+2*c)+d}else p=s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p=-s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p<=-y?(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<=y?(m=0,p=Math.min(Math.max(-s,-c),s),f=p*(p+2*c)+d):(m=Math.max(0,-(o*s+l)),p=m>0?s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d);else p=o>0?-s:s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;return r&&r.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(Sj).addScaledVector(F_,p),f}intersectSphere(e,n){nu.subVectors(e.center,this.origin);const r=nu.dot(this.direction),i=nu.dot(nu)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),l=r-o,c=r+o;return c<0?null:l<0?this.at(c,n):this.at(l,n)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,i,s,o,l,c;const d=1/this.direction.x,u=1/this.direction.y,m=1/this.direction.z,p=this.origin;return d>=0?(r=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(r=(e.max.x-p.x)*d,i=(e.min.x-p.x)*d),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o<i||isNaN(i))&&(i=o),m>=0?(l=(e.min.z-p.z)*m,c=(e.max.z-p.z)*m):(l=(e.max.z-p.z)*m,c=(e.min.z-p.z)*m),r>c||l>i)||((l>r||r!==r)&&(r=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(r>=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,nu)!==null}intersectTriangle(e,n,r,i,s){_j.subVectors(n,e),R_.subVectors(r,e),kj.crossVectors(_j,R_);let o=this.direction.dot(kj),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Hm.subVectors(this.origin,e);const c=l*this.direction.dot(R_.crossVectors(Hm,R_));if(c<0)return null;const d=l*this.direction.dot(_j.cross(Hm));if(d<0||c+d>o)return null;const u=-l*Hm.dot(kj);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 OF{constructor(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b){OF.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b)}set(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b){const g=this.elements;return g[0]=e,g[4]=n,g[8]=r,g[12]=i,g[1]=s,g[5]=o,g[9]=l,g[13]=c,g[2]=d,g[6]=u,g[10]=m,g[14]=p,g[3]=f,g[7]=y,g[11]=v,g[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 OF().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,i=1/nb.setFromMatrixColumn(e,0).length(),s=1/nb.setFromMatrixColumn(e,1).length(),o=1/nb.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(i),d=Math.sin(i),u=Math.cos(s),m=Math.sin(s);if(e.order==="XYZ"){const p=o*u,f=o*m,y=l*u,v=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+y*d,n[5]=p-v*d,n[9]=-l*c,n[2]=v-p*d,n[6]=y+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,y=d*u,v=d*m;n[0]=p+v*l,n[4]=y*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-y,n[6]=v+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,y=d*u,v=d*m;n[0]=p-v*l,n[4]=-o*m,n[8]=y+f*l,n[1]=f+y*l,n[5]=o*u,n[9]=v-p*l,n[2]=-o*d,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const p=o*u,f=o*m,y=l*u,v=l*m;n[0]=c*u,n[4]=y*d-f,n[8]=p*d+v,n[1]=c*m,n[5]=v*d+p,n[9]=f*d-y,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,y=l*c,v=l*d;n[0]=c*u,n[4]=v-p*m,n[8]=y*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+y,n[10]=p-v*m}else if(e.order==="XZY"){const p=o*c,f=o*d,y=l*c,v=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+v,n[5]=o*u,n[9]=f*m-y,n[2]=y*m-f,n[6]=l*u,n[10]=v*m+p}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ive,e,sve)}lookAt(e,n,r){const i=this.elements;return Go.subVectors(e,n),Go.lengthSq()===0&&(Go.z=1),Go.normalize(),qm.crossVectors(r,Go),qm.lengthSq()===0&&(Math.abs(r.z)===1?Go.x+=1e-4:Go.z+=1e-4,Go.normalize(),qm.crossVectors(r,Go)),qm.normalize(),L_.crossVectors(Go,qm),i[0]=qm.x,i[4]=L_.x,i[8]=Go.x,i[1]=qm.y,i[5]=L_.y,i[9]=Go.y,i[2]=qm.z,i[6]=L_.z,i[10]=Go.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],d=r[12],u=r[1],m=r[5],p=r[9],f=r[13],y=r[2],v=r[6],b=r[10],g=r[14],_=r[3],k=r[7],P=r[11],N=r[15],M=i[0],A=i[4],T=i[8],C=i[12],F=i[1],$=i[5],I=i[9],X=i[13],L=i[2],te=i[6],ae=i[10],ee=i[14],me=i[3],le=i[7],ue=i[11],K=i[15];return s[0]=o*M+l*F+c*L+d*me,s[4]=o*A+l*$+c*te+d*le,s[8]=o*T+l*I+c*ae+d*ue,s[12]=o*C+l*X+c*ee+d*K,s[1]=u*M+m*F+p*L+f*me,s[5]=u*A+m*$+p*te+f*le,s[9]=u*T+m*I+p*ae+f*ue,s[13]=u*C+m*X+p*ee+f*K,s[2]=y*M+v*F+b*L+g*me,s[6]=y*A+v*$+b*te+g*le,s[10]=y*T+v*I+b*ae+g*ue,s[14]=y*C+v*X+b*ee+g*K,s[3]=_*M+k*F+P*L+N*me,s[7]=_*A+k*$+P*te+N*le,s[11]=_*T+k*I+P*ae+N*ue,s[15]=_*C+k*X+P*ee+N*K,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],i=e[8],s=e[12],o=e[1],l=e[5],c=e[9],d=e[13],u=e[2],m=e[6],p=e[10],f=e[14],y=e[3],v=e[7],b=e[11],g=e[15];return y*(+s*c*m-i*d*m-s*l*p+r*d*p+i*l*f-r*c*f)+v*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+b*(+n*d*m-n*l*f-s*o*m+r*o*f+s*l*u-r*d*u)+g*(-i*l*u-n*c*m+n*l*p+i*o*m-r*o*p+r*c*u)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=e[9],p=e[10],f=e[11],y=e[12],v=e[13],b=e[14],g=e[15],_=m*b*d-v*p*d+v*c*f-l*b*f-m*c*g+l*p*g,k=y*p*d-u*b*d-y*c*f+o*b*f+u*c*g-o*p*g,P=u*v*d-y*m*d+y*l*f-o*v*f-u*l*g+o*m*g,N=y*m*c-u*v*c-y*l*p+o*v*p+u*l*b-o*m*b,M=n*_+r*k+i*P+s*N;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/M;return e[0]=_*A,e[1]=(v*p*s-m*b*s-v*i*f+r*b*f+m*i*g-r*p*g)*A,e[2]=(l*b*s-v*c*s+v*i*d-r*b*d-l*i*g+r*c*g)*A,e[3]=(m*c*s-l*p*s-m*i*d+r*p*d+l*i*f-r*c*f)*A,e[4]=k*A,e[5]=(u*b*s-y*p*s+y*i*f-n*b*f-u*i*g+n*p*g)*A,e[6]=(y*c*s-o*b*s-y*i*d+n*b*d+o*i*g-n*c*g)*A,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*A,e[8]=P*A,e[9]=(y*m*s-u*v*s-y*r*f+n*v*f+u*r*g-n*m*g)*A,e[10]=(o*v*s-y*l*s+y*r*d-n*v*d-o*r*g+n*l*g)*A,e[11]=(u*l*s-o*m*s-u*r*d+n*m*d+o*r*f-n*l*f)*A,e[12]=N*A,e[13]=(u*v*i-y*m*i+y*r*p-n*v*p-u*r*b+n*m*b)*A,e[14]=(y*l*i-o*v*i-y*r*c+n*v*c+o*r*b-n*l*b)*A,e[15]=(o*m*i-u*l*i+u*r*c-n*m*c-o*r*p+n*l*p)*A,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),i=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+r,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+r,u*c-i*o,0,d*c-i*l,u*c+i*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,d=s+s,u=o+o,m=l+l,p=s*d,f=s*u,y=s*m,v=o*u,b=o*m,g=l*m,_=c*d,k=c*u,P=c*m,N=r.x,M=r.y,A=r.z;return i[0]=(1-(v+g))*N,i[1]=(f+P)*N,i[2]=(y-k)*N,i[3]=0,i[4]=(f-P)*M,i[5]=(1-(p+g))*M,i[6]=(b+_)*M,i[7]=0,i[8]=(y+k)*A,i[9]=(b-_)*A,i[10]=(1-(p+v))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=nb.set(i[0],i[1],i[2]).length();const o=nb.set(i[4],i[5],i[6]).length(),l=nb.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],pc.copy(this);const d=1/s,u=1/o,m=1/l;return pc.elements[0]*=d,pc.elements[1]*=d,pc.elements[2]*=d,pc.elements[4]*=u,pc.elements[5]*=u,pc.elements[6]*=u,pc.elements[8]*=m,pc.elements[9]*=m,pc.elements[10]*=m,n.setFromRotationMatrix(pc),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,i,s,o,l=pd,c=!1){const d=this.elements,u=2*s/(n-e),m=2*s/(r-i),p=(n+e)/(n-e),f=(r+i)/(r-i);let y,v;if(c)y=s/(o-s),v=o*s/(o-s);else if(l===pd)y=-(o+s)/(o-s),v=-2*o*s/(o-s);else if(l===cN)y=-o/(o-s),v=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+l);return d[0]=u,d[4]=0,d[8]=p,d[12]=0,d[1]=0,d[5]=m,d[9]=f,d[13]=0,d[2]=0,d[6]=0,d[10]=y,d[14]=v,d[3]=0,d[7]=0,d[11]=-1,d[15]=0,this}makeOrthographic(e,n,r,i,s,o,l=pd,c=!1){const d=this.elements,u=2/(n-e),m=2/(r-i),p=-(n+e)/(n-e),f=-(r+i)/(r-i);let y,v;if(c)y=1/(o-s),v=o/(o-s);else if(l===pd)y=-2/(o-s),v=-(o+s)/(o-s);else if(l===cN)y=-1/(o-s),v=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return d[0]=u,d[4]=0,d[8]=0,d[12]=p,d[1]=0,d[5]=m,d[9]=0,d[13]=f,d[2]=0,d[6]=0,d[10]=y,d[14]=v,d[3]=0,d[7]=0,d[11]=0,d[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<16;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}};const nb=new At,pc=new ci,ive=new At(0,0,0),sve=new At(1,1,1),qm=new At,L_=new At,Go=new At,D6=new ci,F6=new qf;let Vh=class ZQ{constructor(e=0,n=0,r=0,i=ZQ.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],l=i[8],c=i[1],d=i[5],u=i[9],m=i[2],p=i[6],f=i[10];switch(n){case"XYZ":this._y=Math.asin(mr(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(-mr(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(mr(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(-mr(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(mr(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(-mr(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:Un("Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return D6.makeRotationFromQuaternion(e),this.setFromRotationMatrix(D6,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return F6.setFromEuler(this),this.setFromQuaternion(F6,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}};Vh.DEFAULT_ORDER="XYZ";let JQ=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}},ove=0;const R6=new At,rb=new qf,ru=new ci,O_=new At,pv=new At,lve=new At,cve=new qf,L6=new At(1,0,0),O6=new At(0,1,0),I6=new At(0,0,1),z6={type:"added"},dve={type:"removed"},ab={type:"childadded",child:null},Nj={type:"childremoved",child:null};let ll=class Ck extends dg{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:ove++}),this.uuid=Iw(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Ck.DEFAULT_UP.clone();const e=new At,n=new Vh,r=new qf,i=new At(1,1,1);function s(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(s),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new ci},normalMatrix:{value:new ir}}),this.matrix=new ci,this.matrixWorld=new ci,this.matrixAutoUpdate=Ck.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Ck.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new JQ,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 rb.setFromAxisAngle(e,n),this.quaternion.multiply(rb),this}rotateOnWorldAxis(e,n){return rb.setFromAxisAngle(e,n),this.quaternion.premultiply(rb),this}rotateX(e){return this.rotateOnAxis(L6,e)}rotateY(e){return this.rotateOnAxis(O6,e)}rotateZ(e){return this.rotateOnAxis(I6,e)}translateOnAxis(e,n){return R6.copy(e).applyQuaternion(this.quaternion),this.position.add(R6.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(L6,e)}translateY(e){return this.translateOnAxis(O6,e)}translateZ(e){return this.translateOnAxis(I6,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ru.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?O_.copy(e):O_.set(e,n,r);const i=this.parent;this.updateWorldMatrix(!0,!1),pv.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ru.lookAt(pv,O_,this.up):ru.lookAt(O_,pv,this.up),this.quaternion.setFromRotationMatrix(ru),i&&(ru.extractRotation(i.matrixWorld),rb.setFromRotationMatrix(ru),this.quaternion.premultiply(rb.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(Xa("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(z6),ab.child=e,this.dispatchEvent(ab),ab.child=null):Xa("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.remove(arguments[r]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(dve),Nj.child=e,this.dispatchEvent(Nj),Nj.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),ru.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ru.multiply(e.parent.matrixWorld)),e.applyMatrix4(ru),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(z6),ab.child=e,this.dispatchEvent(ab),ab.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,n){if(this[e]===n)return this;for(let r=0,i=this.children.length;r<i;r++){const o=this.children[r].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,r=[]){this[e]===n&&r.push(this);const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,n,r);return r}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(pv,e,lve),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(pv,cve,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const n=this.matrixWorld.elements;return e.set(n[8],n[9],n[10]).normalize()}raycast(){}traverse(e){e(this);const n=this.children;for(let r=0,i=n.length;r<i;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,i=n.length;r<i;r++)n[r].traverseVisible(e)}traverseAncestors(e){const n=this.parent;n!==null&&(e(n),n.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const n=this.children;for(let r=0,i=n.length;r<i;r++)n[r].updateMatrixWorld(e)}updateWorldMatrix(e,n){const r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),n===!0){const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].updateWorldMatrix(!1,!0)}}toJSON(e){const n=e===void 0||typeof e=="string",r={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},r.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(l=>({...l,boundingBox:l.boundingBox?l.boundingBox.toJSON():void 0,boundingSphere:l.boundingSphere?l.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(l=>({...l})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function s(l,c){return l[c.uuid]===void 0&&(l[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const l=this.geometry.parameters;if(l!==void 0&&l.shapes!==void 0){const c=l.shapes;if(Array.isArray(c))for(let d=0,u=c.length;d<u;d++){const m=c[d];s(e.shapes,m)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,d=this.material.length;c<d;c++)l.push(s(e.materials,this.material[c]));i.material=l}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let l=0;l<this.children.length;l++)i.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];i.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),d=o(e.textures),u=o(e.images),m=o(e.shapes),p=o(e.skeletons),f=o(e.animations),y=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),d.length>0&&(r.textures=d),u.length>0&&(r.images=u),m.length>0&&(r.shapes=m),p.length>0&&(r.skeletons=p),f.length>0&&(r.animations=f),y.length>0&&(r.nodes=y)}return r.object=i,r;function o(l){const c=[];for(const d in l){const u=l[d];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r<e.children.length;r++){const i=e.children[r];this.add(i.clone())}return this}};ll.DEFAULT_UP=new At(0,1,0);ll.DEFAULT_MATRIX_AUTO_UPDATE=!0;ll.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const fc=new At,au=new At,Cj=new At,iu=new At,ib=new At,sb=new At,U6=new At,Pj=new At,Tj=new At,Aj=new At,Mj=new ii,jj=new ii,Ej=new ii;let fv=class Ub{constructor(e=new At,n=new At,r=new At){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,i){i.subVectors(r,n),fc.subVectors(e,n),i.cross(fc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){fc.subVectors(i,n),au.subVectors(r,n),Cj.subVectors(e,n);const o=fc.dot(fc),l=fc.dot(au),c=fc.dot(Cj),d=au.dot(au),u=au.dot(Cj),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,y=(o*u-l*c)*p;return s.set(1-f-y,y,f)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,iu)===null?!1:iu.x>=0&&iu.y>=0&&iu.x+iu.y<=1}static getInterpolation(e,n,r,i,s,o,l,c){return this.getBarycoord(e,n,r,i,iu)===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,iu.x),c.addScaledVector(o,iu.y),c.addScaledVector(l,iu.z),c)}static getInterpolatedAttribute(e,n,r,i,s,o){return Mj.setScalar(0),jj.setScalar(0),Ej.setScalar(0),Mj.fromBufferAttribute(e,n),jj.fromBufferAttribute(e,r),Ej.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(Mj,s.x),o.addScaledVector(jj,s.y),o.addScaledVector(Ej,s.z),o}static isFrontFacing(e,n,r,i){return fc.subVectors(r,n),au.subVectors(e,n),fc.cross(au).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return fc.subVectors(this.c,this.b),au.subVectors(this.a,this.b),fc.cross(au).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ub.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return Ub.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,r,i,s){return Ub.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return Ub.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ub.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,l;ib.subVectors(i,r),sb.subVectors(s,r),Pj.subVectors(e,r);const c=ib.dot(Pj),d=sb.dot(Pj);if(c<=0&&d<=0)return n.copy(r);Tj.subVectors(e,i);const u=ib.dot(Tj),m=sb.dot(Tj);if(u>=0&&m<=u)return n.copy(i);const p=c*m-u*d;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),n.copy(r).addScaledVector(ib,o);Aj.subVectors(e,s);const f=ib.dot(Aj),y=sb.dot(Aj);if(y>=0&&f<=y)return n.copy(s);const v=f*d-c*y;if(v<=0&&d>=0&&y<=0)return l=d/(d-y),n.copy(r).addScaledVector(sb,l);const b=u*y-f*m;if(b<=0&&m-u>=0&&f-y>=0)return U6.subVectors(s,i),l=(m-u)/(m-u+(f-y)),n.copy(i).addScaledVector(U6,l);const g=1/(b+v+p);return o=v*g,l=p*g,n.copy(r).addScaledVector(ib,o).addScaledVector(sb,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}};const eZ={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},$m={h:0,s:0,l:0},I_={h:0,s:0,l:0};function Dj(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 sr=class{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=Qo){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Cr.colorSpaceToWorking(this,n),this}setRGB(e,n,r,i=Cr.workingColorSpace){return this.r=e,this.g=n,this.b=r,Cr.colorSpaceToWorking(this,i),this}setHSL(e,n,r,i=Cr.workingColorSpace){if(e=Xye(e,1),n=mr(n,0,1),r=mr(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=Dj(o,s,e+1/3),this.g=Dj(o,s,e),this.b=Dj(o,s,e-1/3)}return Cr.colorSpaceToWorking(this,i),this}setStyle(e,n=Qo){function r(s){s!==void 0&&parseFloat(s)<1&&Un("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],l=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:Un("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);Un("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=Qo){const r=eZ[e.toLowerCase()];return r!==void 0?this.setHex(r,n):Un("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=Iu(e.r),this.g=Iu(e.g),this.b=Iu(e.b),this}copyLinearToSRGB(e){return this.r=ix(e.r),this.g=ix(e.g),this.b=ix(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Qo){return Cr.workingToColorSpace(Ss.copy(this),e),Math.round(mr(Ss.r*255,0,255))*65536+Math.round(mr(Ss.g*255,0,255))*256+Math.round(mr(Ss.b*255,0,255))}getHexString(e=Qo){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=Cr.workingColorSpace){Cr.workingToColorSpace(Ss.copy(this),n);const r=Ss.r,i=Ss.g,s=Ss.b,o=Math.max(r,i,s),l=Math.min(r,i,s);let c,d;const u=(l+o)/2;if(l===o)c=0,d=0;else{const m=o-l;switch(d=u<=.5?m/(o+l):m/(2-o-l),o){case r:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-r)/m+2;break;case s:c=(r-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=Cr.workingColorSpace){return Cr.workingToColorSpace(Ss.copy(this),n),e.r=Ss.r,e.g=Ss.g,e.b=Ss.b,e}getStyle(e=Qo){Cr.workingToColorSpace(Ss.copy(this),e);const n=Ss.r,r=Ss.g,i=Ss.b;return e!==Qo?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(i*255)})`}offsetHSL(e,n,r){return this.getHSL($m),this.setHSL($m.h+e,$m.s+n,$m.l+r)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,n){return this.r=e.r+n.r,this.g=e.g+n.g,this.b=e.b+n.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,n){return this.r+=(e.r-this.r)*n,this.g+=(e.g-this.g)*n,this.b+=(e.b-this.b)*n,this}lerpColors(e,n,r){return this.r=e.r+(n.r-e.r)*r,this.g=e.g+(n.g-e.g)*r,this.b=e.b+(n.b-e.b)*r,this}lerpHSL(e,n){this.getHSL($m),e.getHSL(I_);const r=fj($m.h,I_.h,n),i=fj($m.s,I_.s,n),s=fj($m.l,I_.l,n);return this.setHSL(r,i,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const n=this.r,r=this.g,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*i,this.g=s[1]*n+s[4]*r+s[7]*i,this.b=s[2]*n+s[5]*r+s[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,n=0){return this.r=e[n],this.g=e[n+1],this.b=e[n+2],this}toArray(e=[],n=0){return e[n]=this.r,e[n+1]=this.g,e[n+2]=this.b,e}fromBufferAttribute(e,n){return this.r=e.getX(n),this.g=e.getY(n),this.b=e.getZ(n),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const Ss=new sr;sr.NAMES=eZ;let uve=0,ay=class extends dg{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:uve++}),this.uuid=Iw(),this.name="",this.type="Material",this.blending=ax,this.side=$h,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Y3,this.blendDst=X3,this.blendEquation=Zp,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new sr(0,0,0),this.blendAlpha=0,this.depthFunc=_x,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=N6,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Qg,this.stencilZFail=Qg,this.stencilZPass=Qg,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){Un(`Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){Un(`Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(r.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(r.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==ax&&(r.blending=this.blending),this.side!==$h&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==Y3&&(r.blendSrc=this.blendSrc),this.blendDst!==X3&&(r.blendDst=this.blendDst),this.blendEquation!==Zp&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==_x&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==N6&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Qg&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Qg&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Qg&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const i=n.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},EO=class extends ay{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new sr(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 Vh,this.combine=SO,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 ri=new At,z_=new tr;let mve=0,Zs=class{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:mve++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=C6,this.updateRanges=[],this.gpuType=Mu,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[r+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,r=this.count;n<r;n++)z_.fromBufferAttribute(this,n),z_.applyMatrix3(e),this.setXY(n,z_.x,z_.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)ri.fromBufferAttribute(this,n),ri.applyMatrix3(e),this.setXYZ(n,ri.x,ri.y,ri.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)ri.fromBufferAttribute(this,n),ri.applyMatrix4(e),this.setXYZ(n,ri.x,ri.y,ri.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)ri.fromBufferAttribute(this,n),ri.applyNormalMatrix(e),this.setXYZ(n,ri.x,ri.y,ri.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)ri.fromBufferAttribute(this,n),ri.transformDirection(e),this.setXYZ(n,ri.x,ri.y,ri.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let r=this.array[e*this.itemSize+n];return this.normalized&&(r=uv(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=bo(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=uv(n,this.array)),n}setX(e,n){return this.normalized&&(n=bo(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=uv(n,this.array)),n}setY(e,n){return this.normalized&&(n=bo(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=uv(n,this.array)),n}setZ(e,n){return this.normalized&&(n=bo(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=uv(n,this.array)),n}setW(e,n){return this.normalized&&(n=bo(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=bo(n,this.array),r=bo(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,i){return e*=this.itemSize,this.normalized&&(n=bo(n,this.array),r=bo(r,this.array),i=bo(i,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e*=this.itemSize,this.normalized&&(n=bo(n,this.array),r=bo(r,this.array),i=bo(i,this.array),s=bo(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==C6&&(e.usage=this.usage),e}},tZ=class extends Zs{constructor(e,n,r){super(new Uint16Array(e),n,r)}},nZ=class extends Zs{constructor(e,n,r){super(new Uint32Array(e),n,r)}},rl=class extends Zs{constructor(e,n,r){super(new Float32Array(e),n,r)}},hve=0;const Sl=new ci,Fj=new ll,ob=new At,Wo=new Fh,gv=new Fh,Ai=new At;let Ql=class rZ extends dg{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:hve++}),this.uuid=Iw(),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(GQ(e)?nZ:tZ)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,n){return this.attributes[e]=n,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,n,r=0){this.groups.push({start:e,count:n,materialIndex:r})}clearGroups(){this.groups=[]}setDrawRange(e,n){this.drawRange.start=e,this.drawRange.count=n}applyMatrix4(e){const n=this.attributes.position;n!==void 0&&(n.applyMatrix4(e),n.needsUpdate=!0);const r=this.attributes.normal;if(r!==void 0){const s=new ir().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Sl.makeRotationFromQuaternion(e),this.applyMatrix4(Sl),this}rotateX(e){return Sl.makeRotationX(e),this.applyMatrix4(Sl),this}rotateY(e){return Sl.makeRotationY(e),this.applyMatrix4(Sl),this}rotateZ(e){return Sl.makeRotationZ(e),this.applyMatrix4(Sl),this}translate(e,n,r){return Sl.makeTranslation(e,n,r),this.applyMatrix4(Sl),this}scale(e,n,r){return Sl.makeScale(e,n,r),this.applyMatrix4(Sl),this}lookAt(e){return Fj.lookAt(e),Fj.updateMatrix(),this.applyMatrix4(Fj.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ob).negate(),this.translate(ob.x,ob.y,ob.z),this}setFromPoints(e){const n=this.getAttribute("position");if(n===void 0){const r=[];for(let i=0,s=e.length;i<s;i++){const o=e[i];r.push(o.x,o.y,o.z||0)}this.setAttribute("position",new rl(r,3))}else{const r=Math.min(e.length,n.count);for(let i=0;i<r;i++){const s=e[i];n.setXYZ(i,s.x,s.y,s.z||0)}e.length>n.count&&Un("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){Xa("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new At(-1/0,-1/0,-1/0),new At(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r<i;r++){const s=n[r];Wo.setFromBufferAttribute(s),this.morphTargetsRelative?(Ai.addVectors(this.boundingBox.min,Wo.min),this.boundingBox.expandByPoint(Ai),Ai.addVectors(this.boundingBox.max,Wo.max),this.boundingBox.expandByPoint(Ai)):(this.boundingBox.expandByPoint(Wo.min),this.boundingBox.expandByPoint(Wo.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Xa('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 MP);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Xa("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new At,1/0);return}if(e){const r=this.boundingSphere.center;if(Wo.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];gv.setFromBufferAttribute(l),this.morphTargetsRelative?(Ai.addVectors(Wo.min,gv.min),Wo.expandByPoint(Ai),Ai.addVectors(Wo.max,gv.max),Wo.expandByPoint(Ai)):(Wo.expandByPoint(gv.min),Wo.expandByPoint(gv.max))}Wo.getCenter(r);let i=0;for(let s=0,o=e.count;s<o;s++)Ai.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(Ai));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++)Ai.fromBufferAttribute(l,d),c&&(ob.fromBufferAttribute(e,d),Ai.add(ob)),i=Math.max(i,r.distanceToSquared(Ai))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Xa('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){Xa("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const r=n.position,i=n.normal,s=n.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Zs(new Float32Array(4*r.count),4));const o=this.getAttribute("tangent"),l=[],c=[];for(let T=0;T<r.count;T++)l[T]=new At,c[T]=new At;const d=new At,u=new At,m=new At,p=new tr,f=new tr,y=new tr,v=new At,b=new At;function g(T,C,F){d.fromBufferAttribute(r,T),u.fromBufferAttribute(r,C),m.fromBufferAttribute(r,F),p.fromBufferAttribute(s,T),f.fromBufferAttribute(s,C),y.fromBufferAttribute(s,F),u.sub(d),m.sub(d),f.sub(p),y.sub(p);const $=1/(f.x*y.y-y.x*f.y);isFinite($)&&(v.copy(u).multiplyScalar(y.y).addScaledVector(m,-f.y).multiplyScalar($),b.copy(m).multiplyScalar(f.x).addScaledVector(u,-y.x).multiplyScalar($),l[T].add(v),l[C].add(v),l[F].add(v),c[T].add(b),c[C].add(b),c[F].add(b))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let T=0,C=_.length;T<C;++T){const F=_[T],$=F.start,I=F.count;for(let X=$,L=$+I;X<L;X+=3)g(e.getX(X+0),e.getX(X+1),e.getX(X+2))}const k=new At,P=new At,N=new At,M=new At;function A(T){N.fromBufferAttribute(i,T),M.copy(N);const C=l[T];k.copy(C),k.sub(N.multiplyScalar(N.dot(C))).normalize(),P.crossVectors(M,C);const $=P.dot(c[T])<0?-1:1;o.setXYZW(T,k.x,k.y,k.z,$)}for(let T=0,C=_.length;T<C;++T){const F=_[T],$=F.start,I=F.count;for(let X=$,L=$+I;X<L;X+=3)A(e.getX(X+0)),A(e.getX(X+1)),A(e.getX(X+2))}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let r=this.getAttribute("normal");if(r===void 0)r=new Zs(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let p=0,f=r.count;p<f;p++)r.setXYZ(p,0,0,0);const i=new At,s=new At,o=new At,l=new At,c=new At,d=new At,u=new At,m=new At;if(e)for(let p=0,f=e.count;p<f;p+=3){const y=e.getX(p+0),v=e.getX(p+1),b=e.getX(p+2);i.fromBufferAttribute(n,y),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,b),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(r,y),c.fromBufferAttribute(r,v),d.fromBufferAttribute(r,b),l.add(u),c.add(u),d.add(u),r.setXYZ(y,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.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),r.setXYZ(p+0,u.x,u.y,u.z),r.setXYZ(p+1,u.x,u.y,u.z),r.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Ai.fromBufferAttribute(e,n),Ai.normalize(),e.setXYZ(n,Ai.x,Ai.y,Ai.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,y=0;for(let v=0,b=c.length;v<b;v++){l.isInterleavedBufferAttribute?f=c[v]*l.data.stride+l.offset:f=c[v]*u;for(let g=0;g<u;g++)p[y++]=d[f++]}return new Zs(p,u,m)}if(this.index===null)return Un("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new rZ,r=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,r);n.setAttribute(l,d)}const s=this.morphAttributes;for(const l in s){const c=[],d=s[l];for(let u=0,m=d.length;u<m;u++){const p=d[u],f=e(p,r);c.push(f)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const d=o[l];n.addGroup(d.start,d.count,d.materialIndex)}return n}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const d in c)c[d]!==void 0&&(e[d]=c[d]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const c in r){const d=r[c];e.data.attributes[c]=d.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const d=this.morphAttributes[c],u=[];for(let m=0,p=d.length;m<p;m++){const f=d[m];u.push(f.toJSON(e.data))}u.length>0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const l=this.boundingSphere;return l!==null&&(e.data.boundingSphere=l.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone());const i=e.attributes;for(const d in i){const u=i[d];this.setAttribute(d,u.clone(n))}const s=e.morphAttributes;for(const d in s){const u=[],m=s[d];for(let p=0,f=m.length;p<f;p++)u.push(m[p].clone(n));this.morphAttributes[d]=u}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let d=0,u=o.length;d<u;d++){const m=o[d];this.addGroup(m.start,m.count,m.materialIndex)}const l=e.boundingBox;l!==null&&(this.boundingBox=l.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}};const B6=new ci,Dp=new jO,U_=new MP,H6=new At,B_=new At,H_=new At,q_=new At,Rj=new At,$_=new At,q6=new At,V_=new At;let Zl=class extends ll{constructor(e=new Ql,n=new EO){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=n,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,i=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){$_.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(Rj.fromBufferAttribute(m,e),o?$_.addScaledVector(Rj,u):$_.addScaledVector(Rj.sub(n),u))}n.add($_)}return n}raycast(e,n){const r=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),U_.copy(r.boundingSphere),U_.applyMatrix4(s),Dp.copy(e.ray).recast(e.near),!(U_.containsPoint(Dp.origin)===!1&&(Dp.intersectSphere(U_,H6)===null||Dp.origin.distanceToSquared(H6)>(e.far-e.near)**2))&&(B6.copy(s).invert(),Dp.copy(e.ray).applyMatrix4(B6),!(r.boundingBox!==null&&Dp.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Dp)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,d=s.attributes.uv,u=s.attributes.uv1,m=s.attributes.normal,p=s.groups,f=s.drawRange;if(l!==null)if(Array.isArray(o))for(let y=0,v=p.length;y<v;y++){const b=p[y],g=o[b.materialIndex],_=Math.max(b.start,f.start),k=Math.min(l.count,Math.min(b.start+b.count,f.start+f.count));for(let P=_,N=k;P<N;P+=3){const M=l.getX(P),A=l.getX(P+1),T=l.getX(P+2);i=G_(this,g,e,r,d,u,m,M,A,T),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const y=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let b=y,g=v;b<g;b+=3){const _=l.getX(b),k=l.getX(b+1),P=l.getX(b+2);i=G_(this,o,e,r,d,u,m,_,k,P),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let y=0,v=p.length;y<v;y++){const b=p[y],g=o[b.materialIndex],_=Math.max(b.start,f.start),k=Math.min(c.count,Math.min(b.start+b.count,f.start+f.count));for(let P=_,N=k;P<N;P+=3){const M=P,A=P+1,T=P+2;i=G_(this,g,e,r,d,u,m,M,A,T),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const y=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let b=y,g=v;b<g;b+=3){const _=b,k=b+1,P=b+2;i=G_(this,o,e,r,d,u,m,_,k,P),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}}};function pve(t,e,n,r,i,s,o,l){let c;if(e.side===Co?c=r.intersectTriangle(o,s,i,!0,l):c=r.intersectTriangle(i,s,o,e.side===$h,l),c===null)return null;V_.copy(l),V_.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(V_);return d<n.near||d>n.far?null:{distance:d,point:V_.clone(),object:t}}function G_(t,e,n,r,i,s,o,l,c,d){t.getVertexPosition(l,B_),t.getVertexPosition(c,H_),t.getVertexPosition(d,q_);const u=pve(t,e,n,r,B_,H_,q_,q6);if(u){const m=new At;fv.getBarycoord(q6,B_,H_,q_,m),i&&(u.uv=fv.getInterpolatedAttribute(i,l,c,d,m,new tr)),s&&(u.uv1=fv.getInterpolatedAttribute(s,l,c,d,m,new tr)),o&&(u.normal=fv.getInterpolatedAttribute(o,l,c,d,m,new At),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const p={a:l,b:c,c:d,normal:new At,materialIndex:0};fv.getNormal(B_,H_,q_,p.normal),u.face=p,u.barycoord=m}return u}let DO=class aZ extends Ql{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const l=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],d=[],u=[],m=[];let p=0,f=0;y("z","y","x",-1,-1,r,n,e,o,s,0),y("z","y","x",1,-1,r,n,-e,o,s,1),y("x","z","y",1,1,e,r,n,i,o,2),y("x","z","y",1,-1,e,r,-n,i,o,3),y("x","y","z",1,-1,e,n,r,i,s,4),y("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new rl(d,3)),this.setAttribute("normal",new rl(u,3)),this.setAttribute("uv",new rl(m,2));function y(v,b,g,_,k,P,N,M,A,T,C){const F=P/A,$=N/T,I=P/2,X=N/2,L=M/2,te=A+1,ae=T+1;let ee=0,me=0;const le=new At;for(let ue=0;ue<ae;ue++){const K=ue*$-X;for(let ne=0;ne<te;ne++){const oe=ne*F-I;le[v]=oe*_,le[b]=K*k,le[g]=L,d.push(le.x,le.y,le.z),le[v]=0,le[b]=0,le[g]=M>0?1:-1,u.push(le.x,le.y,le.z),m.push(ne/A),m.push(1-ue/T),ee+=1}}for(let ue=0;ue<T;ue++)for(let K=0;K<A;K++){const ne=p+K+te*ue,oe=p+K+te*(ue+1),be=p+(K+1)+te*(ue+1),_e=p+(K+1)+te*ue;c.push(ne,oe,_e),c.push(oe,be,_e),me+=6}l.addGroup(f,me,C),f+=me,p+=ee}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new aZ(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function Px(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const i=t[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(Un("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=i.clone():Array.isArray(i)?e[n][r]=i.slice():e[n][r]=i}}return e}function Vs(t){const e={};for(let n=0;n<t.length;n++){const r=Px(t[n]);for(const i in r)e[i]=r[i]}return e}function fve(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function iZ(t){const e=t.getRenderTarget();return e===null?t.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Cr.workingColorSpace}const gve={clone:Px,merge:Vs};var bve=`void main() {
  32. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  33. }`,xve=`void main() {
  34. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  35. }`;let Xu=class extends ay{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=bve,this.fragmentShader=xve,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=Px(e.uniforms),this.uniformsGroups=fve(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const n=super.toJSON(e);n.glslVersion=this.glslVersion,n.uniforms={};for(const i in this.uniforms){const o=this.uniforms[i].value;o&&o.isTexture?n.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[i]={type:"m4",value:o.toArray()}:n.uniforms[i]={value:o}}Object.keys(this.defines).length>0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}},sZ=class extends ll{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ci,this.projectionMatrix=new ci,this.projectionMatrixInverse=new ci,this.coordinateSystem=pd,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 Vm=new At,$6=new tr,V6=new tr;let Rl=class extends sZ{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=LF*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(kk*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return LF*2*Math.atan(Math.tan(kk*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,r){Vm.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Vm.x,Vm.y).multiplyScalar(-e/Vm.z),Vm.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(Vm.x,Vm.y).multiplyScalar(-e/Vm.z)}getViewSize(e,n){return this.getViewBounds(e,$6,V6),n.subVectors(V6,$6)}setViewOffset(e,n,r,i,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(kk*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,d=o.fullHeight;s+=o.offsetX*i/c,n-=o.offsetY*r/d,i*=o.width/c,r*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-r,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}};const lb=-90,cb=1;let yve=class extends ll{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Rl(lb,cb,e,n);i.layers=this.layers,this.add(i);const s=new Rl(lb,cb,e,n);s.layers=this.layers,this.add(s);const o=new Rl(lb,cb,e,n);o.layers=this.layers,this.add(o);const l=new Rl(lb,cb,e,n);l.layers=this.layers,this.add(l);const c=new Rl(lb,cb,e,n);c.layers=this.layers,this.add(c);const d=new Rl(lb,cb,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===pd)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),l.up.set(0,1,0),l.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===cN)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),l.up.set(0,-1,0),l.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const d of n)this.add(d),d.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,d,u]=this.children,m=e.getRenderTarget(),p=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),y=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,l),e.setRenderTarget(r,3,i),e.render(n,c),e.setRenderTarget(r,4,i),e.render(n,d),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=y,r.texture.needsPMREMUpdate=!0}},oZ=class extends zc{constructor(e=[],n=kx,r,i,s,o,l,c,d,u){super(e,n,r,i,s,o,l,c,d,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},vve=class extends $f{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new oZ(i),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:`
  36. varying vec3 vWorldDirection;
  37. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  38. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  39. }
  40. void main() {
  41. vWorldDirection = transformDirection( position, modelMatrix );
  42. #include <begin_vertex>
  43. #include <project_vertex>
  44. }
  45. `,fragmentShader:`
  46. uniform sampler2D tEquirect;
  47. varying vec3 vWorldDirection;
  48. #include <common>
  49. void main() {
  50. vec3 direction = normalize( vWorldDirection );
  51. vec2 sampleUV = equirectUv( direction );
  52. gl_FragColor = texture2D( tEquirect, sampleUV );
  53. }
  54. `},i=new DO(5,5,5),s=new Xu({name:"CubemapFromEquirect",uniforms:Px(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:Co,blending:Ou});s.uniforms.tEquirect.value=n;const o=new Zl(i,s),l=n.minFilter;return n.minFilter===sf&&(n.minFilter=Bl),new yve(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n=!0,r=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}},Yb=class extends ll{constructor(){super(),this.isGroup=!0,this.type="Group"}};const wve={type:"move"};let Lj=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Yb,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 Yb,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new At,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new At),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Yb,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new At,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new At),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let i=null,s=null,o=null;const l=this._targetRay,c=this._grip,d=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(d&&e.hand){o=!0;for(const v of e.hand.values()){const b=n.getJointPose(v,r),g=this._getHandJoint(d,v);b!==null&&(g.matrix.fromArray(b.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=b.radius),g.visible=b!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,y=.005;d.inputState.pinching&&p>f+y?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-y&&(d.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(l.matrix.fromArray(i.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,i.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(i.linearVelocity)):l.hasLinearVelocity=!1,i.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(i.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(wve)))}return l!==null&&(l.visible=i!==null),c!==null&&(c.visible=s!==null),d!==null&&(d.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Yb;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}},Sve=class extends ll{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 Vh,this.environmentIntensity=1,this.environmentRotation=new Vh,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}},_ve=class extends zc{constructor(e=null,n=1,r=1,i,s,o,l,c,d=nl,u=nl,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};const Oj=new At,kve=new At,Nve=new ir;let rh=class{constructor(e=new At(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=Oj.subVectors(r,n).cross(kve.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(Oj),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||Nve.getNormalMatrix(e),i=this.coplanarPoint(Oj).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}};const Fp=new MP,Cve=new tr(.5,.5),W_=new At;let FO=class{constructor(e=new rh,n=new rh,r=new rh,i=new rh,s=new rh,o=new rh){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(i),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=pd,r=!1){const i=this.planes,s=e.elements,o=s[0],l=s[1],c=s[2],d=s[3],u=s[4],m=s[5],p=s[6],f=s[7],y=s[8],v=s[9],b=s[10],g=s[11],_=s[12],k=s[13],P=s[14],N=s[15];if(i[0].setComponents(d-o,f-u,g-y,N-_).normalize(),i[1].setComponents(d+o,f+u,g+y,N+_).normalize(),i[2].setComponents(d+l,f+m,g+v,N+k).normalize(),i[3].setComponents(d-l,f-m,g-v,N-k).normalize(),r)i[4].setComponents(c,p,b,P).normalize(),i[5].setComponents(d-c,f-p,g-b,N-P).normalize();else if(i[4].setComponents(d-c,f-p,g-b,N-P).normalize(),n===pd)i[5].setComponents(d+c,f+p,g+b,N+P).normalize();else if(n===cN)i[5].setComponents(c,p,b,P).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Fp.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Fp.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Fp)}intersectsSprite(e){Fp.center.set(0,0,0);const n=Cve.distanceTo(e.center);return Fp.radius=.7071067811865476+n,Fp.applyMatrix4(e.matrixWorld),this.intersectsSphere(Fp)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const i=n[r];if(W_.x=i.normal.x>0?e.max.x:e.min.x,W_.y=i.normal.y>0?e.max.y:e.min.y,W_.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(W_)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},lZ=class extends ay{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new sr(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 uN=new At,mN=new At,G6=new ci,bv=new jO,K_=new MP,Ij=new At,W6=new At;let Pve=class extends ll{constructor(e=new Ql,n=new lZ){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=n,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[0];for(let i=1,s=n.count;i<s;i++)uN.fromBufferAttribute(n,i-1),mN.fromBufferAttribute(n,i),r[i]=r[i-1],r[i]+=uN.distanceTo(mN);e.setAttribute("lineDistance",new rl(r,1))}else Un("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),K_.copy(r.boundingSphere),K_.applyMatrix4(i),K_.radius+=s,e.ray.intersectsSphere(K_)===!1)return;G6.copy(i).invert(),bv.copy(e.ray).applyMatrix4(G6);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=this.isLineSegments?2:1,u=r.index,p=r.attributes.position;if(u!==null){const f=Math.max(0,o.start),y=Math.min(u.count,o.start+o.count);for(let v=f,b=y-1;v<b;v+=d){const g=u.getX(v),_=u.getX(v+1),k=Y_(this,e,bv,c,g,_,v);k&&n.push(k)}if(this.isLineLoop){const v=u.getX(y-1),b=u.getX(f),g=Y_(this,e,bv,c,v,b,y-1);g&&n.push(g)}}else{const f=Math.max(0,o.start),y=Math.min(p.count,o.start+o.count);for(let v=f,b=y-1;v<b;v+=d){const g=Y_(this,e,bv,c,v,v+1,v);g&&n.push(g)}if(this.isLineLoop){const v=Y_(this,e,bv,c,y-1,f,y-1);v&&n.push(v)}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};function Y_(t,e,n,r,i,s,o){const l=t.geometry.attributes.position;if(uN.fromBufferAttribute(l,i),mN.fromBufferAttribute(l,s),n.distanceSqToSegment(uN,mN,Ij,W6)>r)return;Ij.applyMatrix4(t.matrixWorld);const d=e.ray.origin.distanceTo(Ij);if(!(d<e.near||d>e.far))return{distance:d,point:W6.clone().applyMatrix4(t.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:t}}const K6=new At,Y6=new At;let Tve=class extends Pve{constructor(e,n){super(e,n),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[];for(let i=0,s=n.count;i<s;i+=2)K6.fromBufferAttribute(n,i),Y6.fromBufferAttribute(n,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+K6.distanceTo(Y6);e.setAttribute("lineDistance",new rl(r,1))}else Un("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},cZ=class extends zc{constructor(e,n,r=Hf,i,s,o,l=nl,c=nl,d,u=U0,m=1){if(u!==U0&&u!==B0)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const p={width:e,height:n,depth:m};super(p,i,s,o,l,c,u,r,d),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new MO(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 dZ extends zc{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}let RO=class uZ extends Ql{constructor(e=1,n=1,r=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],y=[],v=[],b=[];for(let g=0;g<u;g++){const _=g*p-o;for(let k=0;k<d;k++){const P=k*m-s;y.push(P,-_,0),v.push(0,0,1),b.push(k/l),b.push(1-g/c)}}for(let g=0;g<c;g++)for(let _=0;_<l;_++){const k=_+d*g,P=_+d*(g+1),N=_+1+d*(g+1),M=_+1+d*g;f.push(k,P,M),f.push(P,N,M)}this.setIndex(f),this.setAttribute("position",new rl(y,3)),this.setAttribute("normal",new rl(v,3)),this.setAttribute("uv",new rl(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new uZ(e.width,e.height,e.widthSegments,e.heightSegments)}};class mZ extends ay{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new sr(16777215),this.specular=new sr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new sr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$Q,this.normalScale=new tr(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Vh,this.combine=SO,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 Ave=class extends ay{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Iye,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}},Mve=class extends ay{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 X6={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 jve{constructor(e,n,r){const i=this;let s=!1,o=0,l=0,c;const d=[];this.onStart=void 0,this.onLoad=e,this.onProgress=n,this.onError=r,this._abortController=null,this.itemStart=function(u){l++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,l),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,l),o===l&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,m){return d.push(u,m),this},this.removeHandler=function(u){const m=d.indexOf(u);return m!==-1&&d.splice(m,2),this},this.getHandler=function(u){for(let m=0,p=d.length;m<p;m+=2){const f=d[m],y=d[m+1];if(f.global&&(f.lastIndex=0),f.test(u))return y}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 Eve=new jve;class LO{constructor(e){this.manager=e!==void 0?e:Eve,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,n){const r=this;return new Promise(function(i,s){r.load(e,i,n,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}}LO.DEFAULT_MATERIAL_NAME="__DEFAULT";const su={};class Dve extends Error{constructor(e,n){super(e),this.response=n}}class Fve extends LO{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,n,r,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=X6.get(`file:${e}`);if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{n&&n(s),this.manager.itemEnd(e)},0),s;if(su[e]!==void 0){su[e].push({onLoad:n,onProgress:r,onError:i});return}su[e]=[],su[e].push({onLoad:n,onProgress:r,onError:i});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),l=this.mimeType,c=this.responseType;fetch(o).then(d=>{if(d.status===200||d.status===0){if(d.status===0&&Un("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||d.body===void 0||d.body.getReader===void 0)return d;const u=su[e],m=d.body.getReader(),p=d.headers.get("X-File-Size")||d.headers.get("Content-Length"),f=p?parseInt(p):0,y=f!==0;let v=0;const b=new ReadableStream({start(g){_();function _(){m.read().then(({done:k,value:P})=>{if(k)g.close();else{v+=P.byteLength;const N=new ProgressEvent("progress",{lengthComputable:y,loaded:v,total:f});for(let M=0,A=u.length;M<A;M++){const T=u[M];T.onProgress&&T.onProgress(N)}g.enqueue(P),_()}},k=>{g.error(k)})}}});return new Response(b)}else throw new Dve(`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(y=>f.decode(y))}}}).then(d=>{X6.add(`file:${e}`,d);const u=su[e];delete su[e];for(let m=0,p=u.length;m<p;m++){const f=u[m];f.onLoad&&f.onLoad(d)}}).catch(d=>{const u=su[e];if(u===void 0)throw this.manager.itemError(e),d;delete su[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 hZ=class extends ll{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new sr(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 zj=new ci,Q6=new At,Z6=new At;let Rve=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new tr(512,512),this.mapType=Cd,this.map=null,this.mapPass=null,this.matrix=new ci,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new FO,this._frameExtents=new tr(1,1),this._viewportCount=1,this._viewports=[new ii(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;Q6.setFromMatrixPosition(e.matrixWorld),n.position.copy(Q6),Z6.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(Z6),n.updateMatrixWorld(),zj.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(zj,n.coordinateSystem,n.reversedDepth),n.reversedDepth?r.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(zj)}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}},pZ=class extends sZ{constructor(e=-1,n=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=i+n,c=i-n;if(this.view!==null&&this.view.enabled){const d=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=d*this.view.offsetX,o=s+d*this.view.width,l-=u*this.view.offsetY,c=l-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}};class Lve extends Rve{constructor(){super(new pZ(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class J6 extends hZ{constructor(e,n){super(e,n),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ll.DEFAULT_UP),this.updateMatrix(),this.target=new ll,this.shadow=new Lve}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}let Ove=class extends hZ{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}},Ive=class extends Rl{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},eH=class{constructor(e=1,n=0,r=0){this.radius=e,this.phi=n,this.theta=r}set(e,n,r){return this.radius=e,this.phi=n,this.theta=r,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=mr(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,n,r){return this.radius=Math.sqrt(e*e+n*n+r*r),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,r),this.phi=Math.acos(mr(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};class zve extends Tve{constructor(e=10,n=10,r=4473924,i=8947848){r=new sr(r),i=new sr(i);const s=n/2,o=e/n,l=e/2,c=[],d=[];for(let p=0,f=0,y=-l;p<=n;p++,y+=o){c.push(-l,0,y,l,0,y),c.push(y,0,-l,y,0,l);const v=p===s?r:i;v.toArray(d,f),f+=3,v.toArray(d,f),f+=3,v.toArray(d,f),f+=3,v.toArray(d,f),f+=3}const u=new Ql;u.setAttribute("position",new rl(c,3)),u.setAttribute("color",new rl(d,3));const m=new lZ({vertexColors:!0,toneMapped:!1});super(u,m),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class Uve extends dg{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){Un("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function tH(t,e,n,r){const i=Bve(r);switch(n){case BQ:return t*e;case qQ:return t*e/i.components*i.byteLength;case CO:return t*e/i.components*i.byteLength;case PO:return t*e*2/i.components*i.byteLength;case TO:return t*e*2/i.components*i.byteLength;case HQ:return t*e*3/i.components*i.byteLength;case Tc:return t*e*4/i.components*i.byteLength;case AO:return t*e*4/i.components*i.byteLength;case vk:case wk:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case Sk:case _k:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case cF:case uF:return Math.max(t,16)*Math.max(e,8)/4;case lF:case dF:return Math.max(t,8)*Math.max(e,8)/2;case mF:case hF:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case pF:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case fF:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case gF:return Math.floor((t+4)/5)*Math.floor((e+3)/4)*16;case bF:return Math.floor((t+4)/5)*Math.floor((e+4)/5)*16;case xF:return Math.floor((t+5)/6)*Math.floor((e+4)/5)*16;case yF:return Math.floor((t+5)/6)*Math.floor((e+5)/6)*16;case vF:return Math.floor((t+7)/8)*Math.floor((e+4)/5)*16;case wF:return Math.floor((t+7)/8)*Math.floor((e+5)/6)*16;case SF:return Math.floor((t+7)/8)*Math.floor((e+7)/8)*16;case _F:return Math.floor((t+9)/10)*Math.floor((e+4)/5)*16;case kF:return Math.floor((t+9)/10)*Math.floor((e+5)/6)*16;case NF:return Math.floor((t+9)/10)*Math.floor((e+7)/8)*16;case CF:return Math.floor((t+9)/10)*Math.floor((e+9)/10)*16;case PF:return Math.floor((t+11)/12)*Math.floor((e+9)/10)*16;case TF:return Math.floor((t+11)/12)*Math.floor((e+11)/12)*16;case AF:case MF:case jF:return Math.ceil(t/4)*Math.ceil(e/4)*16;case EF:case DF:return Math.ceil(t/4)*Math.ceil(e/4)*8;case FF:case RF:return Math.ceil(t/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function Bve(t){switch(t){case Cd:case OQ:return{byteLength:1,components:1};case I0:case IQ:case ry:return{byteLength:2,components:1};case kO:case NO:return{byteLength:2,components:4};case Hf:case _O:case Mu:return{byteLength:4,components:1};case zQ:case UQ:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:wO}}));typeof window<"u"&&(window.__THREE__?Un("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=wO);function fZ(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function Hve(t){const e=new WeakMap;function n(l,c){const d=l.array,u=l.usage,m=d.byteLength,p=t.createBuffer();t.bindBuffer(c,p),t.bufferData(c,d,u),l.onUploadCallback();let f;if(d instanceof Float32Array)f=t.FLOAT;else if(typeof Float16Array<"u"&&d instanceof Float16Array)f=t.HALF_FLOAT;else if(d instanceof Uint16Array)l.isFloat16BufferAttribute?f=t.HALF_FLOAT:f=t.UNSIGNED_SHORT;else if(d instanceof Int16Array)f=t.SHORT;else if(d instanceof Uint32Array)f=t.UNSIGNED_INT;else if(d instanceof Int32Array)f=t.INT;else if(d instanceof Int8Array)f=t.BYTE;else if(d instanceof Uint8Array)f=t.UNSIGNED_BYTE;else if(d instanceof Uint8ClampedArray)f=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+d);return{buffer:p,type:f,bytesPerElement:d.BYTES_PER_ELEMENT,version:l.version,size:m}}function r(l,c,d){const u=c.array,m=c.updateRanges;if(t.bindBuffer(d,l),m.length===0)t.bufferSubData(d,0,u);else{m.sort((f,y)=>f.start-y.start);let p=0;for(let f=1;f<m.length;f++){const y=m[p],v=m[f];v.start<=y.start+y.count+1?y.count=Math.max(y.count,v.start+v.count-y.start):(++p,m[p]=v)}m.length=p+1;for(let f=0,y=m.length;f<y;f++){const v=m[f];t.bufferSubData(d,v.start*u.BYTES_PER_ELEMENT,u,v.start,v.count)}c.clearUpdateRanges()}c.onUploadCallback()}function i(l){return l.isInterleavedBufferAttribute&&(l=l.data),e.get(l)}function s(l){l.isInterleavedBufferAttribute&&(l=l.data);const c=e.get(l);c&&(t.deleteBuffer(c.buffer),e.delete(l))}function o(l,c){if(l.isInterleavedBufferAttribute&&(l=l.data),l.isGLBufferAttribute){const u=e.get(l);(!u||u.version<l.version)&&e.set(l,{buffer:l.buffer,type:l.type,bytesPerElement:l.elementSize,version:l.version});return}const d=e.get(l);if(d===void 0)e.set(l,n(l,c));else if(d.version<l.version){if(d.size!==l.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");r(d.buffer,l,c),d.version=l.version}}return{get:i,remove:s,update:o}}var qve=`#ifdef USE_ALPHAHASH
  55. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  56. #endif`,$ve=`#ifdef USE_ALPHAHASH
  57. const float ALPHA_HASH_SCALE = 0.05;
  58. float hash2D( vec2 value ) {
  59. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  60. }
  61. float hash3D( vec3 value ) {
  62. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  63. }
  64. float getAlphaHashThreshold( vec3 position ) {
  65. float maxDeriv = max(
  66. length( dFdx( position.xyz ) ),
  67. length( dFdy( position.xyz ) )
  68. );
  69. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  70. vec2 pixScales = vec2(
  71. exp2( floor( log2( pixScale ) ) ),
  72. exp2( ceil( log2( pixScale ) ) )
  73. );
  74. vec2 alpha = vec2(
  75. hash3D( floor( pixScales.x * position.xyz ) ),
  76. hash3D( floor( pixScales.y * position.xyz ) )
  77. );
  78. float lerpFactor = fract( log2( pixScale ) );
  79. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  80. float a = min( lerpFactor, 1.0 - lerpFactor );
  81. vec3 cases = vec3(
  82. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  83. ( x - 0.5 * a ) / ( 1.0 - a ),
  84. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  85. );
  86. float threshold = ( x < ( 1.0 - a ) )
  87. ? ( ( x < a ) ? cases.x : cases.y )
  88. : cases.z;
  89. return clamp( threshold , 1.0e-6, 1.0 );
  90. }
  91. #endif`,Vve=`#ifdef USE_ALPHAMAP
  92. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  93. #endif`,Gve=`#ifdef USE_ALPHAMAP
  94. uniform sampler2D alphaMap;
  95. #endif`,Wve=`#ifdef USE_ALPHATEST
  96. #ifdef ALPHA_TO_COVERAGE
  97. diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
  98. if ( diffuseColor.a == 0.0 ) discard;
  99. #else
  100. if ( diffuseColor.a < alphaTest ) discard;
  101. #endif
  102. #endif`,Kve=`#ifdef USE_ALPHATEST
  103. uniform float alphaTest;
  104. #endif`,Yve=`#ifdef USE_AOMAP
  105. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  106. reflectedLight.indirectDiffuse *= ambientOcclusion;
  107. #if defined( USE_CLEARCOAT )
  108. clearcoatSpecularIndirect *= ambientOcclusion;
  109. #endif
  110. #if defined( USE_SHEEN )
  111. sheenSpecularIndirect *= ambientOcclusion;
  112. #endif
  113. #if defined( USE_ENVMAP ) && defined( STANDARD )
  114. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  115. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  116. #endif
  117. #endif`,Xve=`#ifdef USE_AOMAP
  118. uniform sampler2D aoMap;
  119. uniform float aoMapIntensity;
  120. #endif`,Qve=`#ifdef USE_BATCHING
  121. #if ! defined( GL_ANGLE_multi_draw )
  122. #define gl_DrawID _gl_DrawID
  123. uniform int _gl_DrawID;
  124. #endif
  125. uniform highp sampler2D batchingTexture;
  126. uniform highp usampler2D batchingIdTexture;
  127. mat4 getBatchingMatrix( const in float i ) {
  128. int size = textureSize( batchingTexture, 0 ).x;
  129. int j = int( i ) * 4;
  130. int x = j % size;
  131. int y = j / size;
  132. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  133. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  134. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  135. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  136. return mat4( v1, v2, v3, v4 );
  137. }
  138. float getIndirectIndex( const in int i ) {
  139. int size = textureSize( batchingIdTexture, 0 ).x;
  140. int x = i % size;
  141. int y = i / size;
  142. return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
  143. }
  144. #endif
  145. #ifdef USE_BATCHING_COLOR
  146. uniform sampler2D batchingColorTexture;
  147. vec3 getBatchingColor( const in float i ) {
  148. int size = textureSize( batchingColorTexture, 0 ).x;
  149. int j = int( i );
  150. int x = j % size;
  151. int y = j / size;
  152. return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
  153. }
  154. #endif`,Zve=`#ifdef USE_BATCHING
  155. mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
  156. #endif`,Jve=`vec3 transformed = vec3( position );
  157. #ifdef USE_ALPHAHASH
  158. vPosition = vec3( position );
  159. #endif`,e0e=`vec3 objectNormal = vec3( normal );
  160. #ifdef USE_TANGENT
  161. vec3 objectTangent = vec3( tangent.xyz );
  162. #endif`,t0e=`float G_BlinnPhong_Implicit( ) {
  163. return 0.25;
  164. }
  165. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  166. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  167. }
  168. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  169. vec3 halfDir = normalize( lightDir + viewDir );
  170. float dotNH = saturate( dot( normal, halfDir ) );
  171. float dotVH = saturate( dot( viewDir, halfDir ) );
  172. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  173. float G = G_BlinnPhong_Implicit( );
  174. float D = D_BlinnPhong( shininess, dotNH );
  175. return F * ( G * D );
  176. } // validated`,n0e=`#ifdef USE_IRIDESCENCE
  177. const mat3 XYZ_TO_REC709 = mat3(
  178. 3.2404542, -0.9692660, 0.0556434,
  179. -1.5371385, 1.8760108, -0.2040259,
  180. -0.4985314, 0.0415560, 1.0572252
  181. );
  182. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  183. vec3 sqrtF0 = sqrt( fresnel0 );
  184. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  185. }
  186. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  187. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  188. }
  189. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  190. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  191. }
  192. vec3 evalSensitivity( float OPD, vec3 shift ) {
  193. float phase = 2.0 * PI * OPD * 1.0e-9;
  194. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  195. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  196. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  197. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  198. 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 ) );
  199. xyz /= 1.0685e-7;
  200. vec3 rgb = XYZ_TO_REC709 * xyz;
  201. return rgb;
  202. }
  203. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  204. vec3 I;
  205. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  206. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  207. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  208. if ( cosTheta2Sq < 0.0 ) {
  209. return vec3( 1.0 );
  210. }
  211. float cosTheta2 = sqrt( cosTheta2Sq );
  212. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  213. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  214. float T121 = 1.0 - R12;
  215. float phi12 = 0.0;
  216. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  217. float phi21 = PI - phi12;
  218. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  219. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  220. vec3 phi23 = vec3( 0.0 );
  221. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  222. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  223. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  224. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  225. vec3 phi = vec3( phi21 ) + phi23;
  226. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  227. vec3 r123 = sqrt( R123 );
  228. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  229. vec3 C0 = R12 + Rs;
  230. I = C0;
  231. vec3 Cm = Rs - T121;
  232. for ( int m = 1; m <= 2; ++ m ) {
  233. Cm *= r123;
  234. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  235. I += Cm * Sm;
  236. }
  237. return max( I, vec3( 0.0 ) );
  238. }
  239. #endif`,r0e=`#ifdef USE_BUMPMAP
  240. uniform sampler2D bumpMap;
  241. uniform float bumpScale;
  242. vec2 dHdxy_fwd() {
  243. vec2 dSTdx = dFdx( vBumpMapUv );
  244. vec2 dSTdy = dFdy( vBumpMapUv );
  245. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  246. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  247. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  248. return vec2( dBx, dBy );
  249. }
  250. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  251. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  252. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  253. vec3 vN = surf_norm;
  254. vec3 R1 = cross( vSigmaY, vN );
  255. vec3 R2 = cross( vN, vSigmaX );
  256. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  257. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  258. return normalize( abs( fDet ) * surf_norm - vGrad );
  259. }
  260. #endif`,a0e=`#if NUM_CLIPPING_PLANES > 0
  261. vec4 plane;
  262. #ifdef ALPHA_TO_COVERAGE
  263. float distanceToPlane, distanceGradient;
  264. float clipOpacity = 1.0;
  265. #pragma unroll_loop_start
  266. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  267. plane = clippingPlanes[ i ];
  268. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  269. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  270. clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  271. if ( clipOpacity == 0.0 ) discard;
  272. }
  273. #pragma unroll_loop_end
  274. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  275. float unionClipOpacity = 1.0;
  276. #pragma unroll_loop_start
  277. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  278. plane = clippingPlanes[ i ];
  279. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  280. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  281. unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  282. }
  283. #pragma unroll_loop_end
  284. clipOpacity *= 1.0 - unionClipOpacity;
  285. #endif
  286. diffuseColor.a *= clipOpacity;
  287. if ( diffuseColor.a == 0.0 ) discard;
  288. #else
  289. #pragma unroll_loop_start
  290. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  291. plane = clippingPlanes[ i ];
  292. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  293. }
  294. #pragma unroll_loop_end
  295. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  296. bool clipped = true;
  297. #pragma unroll_loop_start
  298. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  299. plane = clippingPlanes[ i ];
  300. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  301. }
  302. #pragma unroll_loop_end
  303. if ( clipped ) discard;
  304. #endif
  305. #endif
  306. #endif`,i0e=`#if NUM_CLIPPING_PLANES > 0
  307. varying vec3 vClipPosition;
  308. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  309. #endif`,s0e=`#if NUM_CLIPPING_PLANES > 0
  310. varying vec3 vClipPosition;
  311. #endif`,o0e=`#if NUM_CLIPPING_PLANES > 0
  312. vClipPosition = - mvPosition.xyz;
  313. #endif`,l0e=`#if defined( USE_COLOR_ALPHA )
  314. diffuseColor *= vColor;
  315. #elif defined( USE_COLOR )
  316. diffuseColor.rgb *= vColor;
  317. #endif`,c0e=`#if defined( USE_COLOR_ALPHA )
  318. varying vec4 vColor;
  319. #elif defined( USE_COLOR )
  320. varying vec3 vColor;
  321. #endif`,d0e=`#if defined( USE_COLOR_ALPHA )
  322. varying vec4 vColor;
  323. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  324. varying vec3 vColor;
  325. #endif`,u0e=`#if defined( USE_COLOR_ALPHA )
  326. vColor = vec4( 1.0 );
  327. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  328. vColor = vec3( 1.0 );
  329. #endif
  330. #ifdef USE_COLOR
  331. vColor *= color;
  332. #endif
  333. #ifdef USE_INSTANCING_COLOR
  334. vColor.xyz *= instanceColor.xyz;
  335. #endif
  336. #ifdef USE_BATCHING_COLOR
  337. vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
  338. vColor.xyz *= batchingColor.xyz;
  339. #endif`,m0e=`#define PI 3.141592653589793
  340. #define PI2 6.283185307179586
  341. #define PI_HALF 1.5707963267948966
  342. #define RECIPROCAL_PI 0.3183098861837907
  343. #define RECIPROCAL_PI2 0.15915494309189535
  344. #define EPSILON 1e-6
  345. #ifndef saturate
  346. #define saturate( a ) clamp( a, 0.0, 1.0 )
  347. #endif
  348. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  349. float pow2( const in float x ) { return x*x; }
  350. vec3 pow2( const in vec3 x ) { return x*x; }
  351. float pow3( const in float x ) { return x*x*x; }
  352. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  353. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  354. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  355. highp float rand( const in vec2 uv ) {
  356. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  357. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  358. return fract( sin( sn ) * c );
  359. }
  360. #ifdef HIGH_PRECISION
  361. float precisionSafeLength( vec3 v ) { return length( v ); }
  362. #else
  363. float precisionSafeLength( vec3 v ) {
  364. float maxComponent = max3( abs( v ) );
  365. return length( v / maxComponent ) * maxComponent;
  366. }
  367. #endif
  368. struct IncidentLight {
  369. vec3 color;
  370. vec3 direction;
  371. bool visible;
  372. };
  373. struct ReflectedLight {
  374. vec3 directDiffuse;
  375. vec3 directSpecular;
  376. vec3 indirectDiffuse;
  377. vec3 indirectSpecular;
  378. };
  379. #ifdef USE_ALPHAHASH
  380. varying vec3 vPosition;
  381. #endif
  382. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  383. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  384. }
  385. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  386. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  387. }
  388. bool isPerspectiveMatrix( mat4 m ) {
  389. return m[ 2 ][ 3 ] == - 1.0;
  390. }
  391. vec2 equirectUv( in vec3 dir ) {
  392. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  393. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  394. return vec2( u, v );
  395. }
  396. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  397. return RECIPROCAL_PI * diffuseColor;
  398. }
  399. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  400. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  401. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  402. }
  403. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  404. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  405. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  406. } // validated`,h0e=`#ifdef ENVMAP_TYPE_CUBE_UV
  407. #define cubeUV_minMipLevel 4.0
  408. #define cubeUV_minTileSize 16.0
  409. float getFace( vec3 direction ) {
  410. vec3 absDirection = abs( direction );
  411. float face = - 1.0;
  412. if ( absDirection.x > absDirection.z ) {
  413. if ( absDirection.x > absDirection.y )
  414. face = direction.x > 0.0 ? 0.0 : 3.0;
  415. else
  416. face = direction.y > 0.0 ? 1.0 : 4.0;
  417. } else {
  418. if ( absDirection.z > absDirection.y )
  419. face = direction.z > 0.0 ? 2.0 : 5.0;
  420. else
  421. face = direction.y > 0.0 ? 1.0 : 4.0;
  422. }
  423. return face;
  424. }
  425. vec2 getUV( vec3 direction, float face ) {
  426. vec2 uv;
  427. if ( face == 0.0 ) {
  428. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  429. } else if ( face == 1.0 ) {
  430. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  431. } else if ( face == 2.0 ) {
  432. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  433. } else if ( face == 3.0 ) {
  434. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  435. } else if ( face == 4.0 ) {
  436. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  437. } else {
  438. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  439. }
  440. return 0.5 * ( uv + 1.0 );
  441. }
  442. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  443. float face = getFace( direction );
  444. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  445. mipInt = max( mipInt, cubeUV_minMipLevel );
  446. float faceSize = exp2( mipInt );
  447. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  448. if ( face > 2.0 ) {
  449. uv.y += faceSize;
  450. face -= 3.0;
  451. }
  452. uv.x += face * faceSize;
  453. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  454. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  455. uv.x *= CUBEUV_TEXEL_WIDTH;
  456. uv.y *= CUBEUV_TEXEL_HEIGHT;
  457. #ifdef texture2DGradEXT
  458. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  459. #else
  460. return texture2D( envMap, uv ).rgb;
  461. #endif
  462. }
  463. #define cubeUV_r0 1.0
  464. #define cubeUV_m0 - 2.0
  465. #define cubeUV_r1 0.8
  466. #define cubeUV_m1 - 1.0
  467. #define cubeUV_r4 0.4
  468. #define cubeUV_m4 2.0
  469. #define cubeUV_r5 0.305
  470. #define cubeUV_m5 3.0
  471. #define cubeUV_r6 0.21
  472. #define cubeUV_m6 4.0
  473. float roughnessToMip( float roughness ) {
  474. float mip = 0.0;
  475. if ( roughness >= cubeUV_r1 ) {
  476. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  477. } else if ( roughness >= cubeUV_r4 ) {
  478. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  479. } else if ( roughness >= cubeUV_r5 ) {
  480. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  481. } else if ( roughness >= cubeUV_r6 ) {
  482. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  483. } else {
  484. mip = - 2.0 * log2( 1.16 * roughness ); }
  485. return mip;
  486. }
  487. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  488. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  489. float mipF = fract( mip );
  490. float mipInt = floor( mip );
  491. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  492. if ( mipF == 0.0 ) {
  493. return vec4( color0, 1.0 );
  494. } else {
  495. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  496. return vec4( mix( color0, color1, mipF ), 1.0 );
  497. }
  498. }
  499. #endif`,p0e=`vec3 transformedNormal = objectNormal;
  500. #ifdef USE_TANGENT
  501. vec3 transformedTangent = objectTangent;
  502. #endif
  503. #ifdef USE_BATCHING
  504. mat3 bm = mat3( batchingMatrix );
  505. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  506. transformedNormal = bm * transformedNormal;
  507. #ifdef USE_TANGENT
  508. transformedTangent = bm * transformedTangent;
  509. #endif
  510. #endif
  511. #ifdef USE_INSTANCING
  512. mat3 im = mat3( instanceMatrix );
  513. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  514. transformedNormal = im * transformedNormal;
  515. #ifdef USE_TANGENT
  516. transformedTangent = im * transformedTangent;
  517. #endif
  518. #endif
  519. transformedNormal = normalMatrix * transformedNormal;
  520. #ifdef FLIP_SIDED
  521. transformedNormal = - transformedNormal;
  522. #endif
  523. #ifdef USE_TANGENT
  524. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  525. #ifdef FLIP_SIDED
  526. transformedTangent = - transformedTangent;
  527. #endif
  528. #endif`,f0e=`#ifdef USE_DISPLACEMENTMAP
  529. uniform sampler2D displacementMap;
  530. uniform float displacementScale;
  531. uniform float displacementBias;
  532. #endif`,g0e=`#ifdef USE_DISPLACEMENTMAP
  533. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  534. #endif`,b0e=`#ifdef USE_EMISSIVEMAP
  535. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  536. #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
  537. emissiveColor = sRGBTransferEOTF( emissiveColor );
  538. #endif
  539. totalEmissiveRadiance *= emissiveColor.rgb;
  540. #endif`,x0e=`#ifdef USE_EMISSIVEMAP
  541. uniform sampler2D emissiveMap;
  542. #endif`,y0e="gl_FragColor = linearToOutputTexel( gl_FragColor );",v0e=`vec4 LinearTransferOETF( in vec4 value ) {
  543. return value;
  544. }
  545. vec4 sRGBTransferEOTF( in vec4 value ) {
  546. 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 );
  547. }
  548. vec4 sRGBTransferOETF( in vec4 value ) {
  549. 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 );
  550. }`,w0e=`#ifdef USE_ENVMAP
  551. #ifdef ENV_WORLDPOS
  552. vec3 cameraToFrag;
  553. if ( isOrthographic ) {
  554. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  555. } else {
  556. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  557. }
  558. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  559. #ifdef ENVMAP_MODE_REFLECTION
  560. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  561. #else
  562. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  563. #endif
  564. #else
  565. vec3 reflectVec = vReflect;
  566. #endif
  567. #ifdef ENVMAP_TYPE_CUBE
  568. vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  569. #else
  570. vec4 envColor = vec4( 0.0 );
  571. #endif
  572. #ifdef ENVMAP_BLENDING_MULTIPLY
  573. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  574. #elif defined( ENVMAP_BLENDING_MIX )
  575. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  576. #elif defined( ENVMAP_BLENDING_ADD )
  577. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  578. #endif
  579. #endif`,S0e=`#ifdef USE_ENVMAP
  580. uniform float envMapIntensity;
  581. uniform float flipEnvMap;
  582. uniform mat3 envMapRotation;
  583. #ifdef ENVMAP_TYPE_CUBE
  584. uniform samplerCube envMap;
  585. #else
  586. uniform sampler2D envMap;
  587. #endif
  588. #endif`,_0e=`#ifdef USE_ENVMAP
  589. uniform float reflectivity;
  590. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  591. #define ENV_WORLDPOS
  592. #endif
  593. #ifdef ENV_WORLDPOS
  594. varying vec3 vWorldPosition;
  595. uniform float refractionRatio;
  596. #else
  597. varying vec3 vReflect;
  598. #endif
  599. #endif`,k0e=`#ifdef USE_ENVMAP
  600. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  601. #define ENV_WORLDPOS
  602. #endif
  603. #ifdef ENV_WORLDPOS
  604. varying vec3 vWorldPosition;
  605. #else
  606. varying vec3 vReflect;
  607. uniform float refractionRatio;
  608. #endif
  609. #endif`,N0e=`#ifdef USE_ENVMAP
  610. #ifdef ENV_WORLDPOS
  611. vWorldPosition = worldPosition.xyz;
  612. #else
  613. vec3 cameraToVertex;
  614. if ( isOrthographic ) {
  615. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  616. } else {
  617. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  618. }
  619. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  620. #ifdef ENVMAP_MODE_REFLECTION
  621. vReflect = reflect( cameraToVertex, worldNormal );
  622. #else
  623. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  624. #endif
  625. #endif
  626. #endif`,C0e=`#ifdef USE_FOG
  627. vFogDepth = - mvPosition.z;
  628. #endif`,P0e=`#ifdef USE_FOG
  629. varying float vFogDepth;
  630. #endif`,T0e=`#ifdef USE_FOG
  631. #ifdef FOG_EXP2
  632. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  633. #else
  634. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  635. #endif
  636. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  637. #endif`,A0e=`#ifdef USE_FOG
  638. uniform vec3 fogColor;
  639. varying float vFogDepth;
  640. #ifdef FOG_EXP2
  641. uniform float fogDensity;
  642. #else
  643. uniform float fogNear;
  644. uniform float fogFar;
  645. #endif
  646. #endif`,M0e=`#ifdef USE_GRADIENTMAP
  647. uniform sampler2D gradientMap;
  648. #endif
  649. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  650. float dotNL = dot( normal, lightDirection );
  651. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  652. #ifdef USE_GRADIENTMAP
  653. return vec3( texture2D( gradientMap, coord ).r );
  654. #else
  655. vec2 fw = fwidth( coord ) * 0.5;
  656. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  657. #endif
  658. }`,j0e=`#ifdef USE_LIGHTMAP
  659. uniform sampler2D lightMap;
  660. uniform float lightMapIntensity;
  661. #endif`,E0e=`LambertMaterial material;
  662. material.diffuseColor = diffuseColor.rgb;
  663. material.specularStrength = specularStrength;`,D0e=`varying vec3 vViewPosition;
  664. struct LambertMaterial {
  665. vec3 diffuseColor;
  666. float specularStrength;
  667. };
  668. 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 ) {
  669. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  670. vec3 irradiance = dotNL * directLight.color;
  671. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  672. }
  673. 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 ) {
  674. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  675. }
  676. #define RE_Direct RE_Direct_Lambert
  677. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,F0e=`uniform bool receiveShadow;
  678. uniform vec3 ambientLightColor;
  679. #if defined( USE_LIGHT_PROBES )
  680. uniform vec3 lightProbe[ 9 ];
  681. #endif
  682. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  683. float x = normal.x, y = normal.y, z = normal.z;
  684. vec3 result = shCoefficients[ 0 ] * 0.886227;
  685. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  686. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  687. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  688. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  689. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  690. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  691. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  692. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  693. return result;
  694. }
  695. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  696. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  697. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  698. return irradiance;
  699. }
  700. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  701. vec3 irradiance = ambientLightColor;
  702. return irradiance;
  703. }
  704. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  705. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  706. if ( cutoffDistance > 0.0 ) {
  707. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  708. }
  709. return distanceFalloff;
  710. }
  711. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  712. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  713. }
  714. #if NUM_DIR_LIGHTS > 0
  715. struct DirectionalLight {
  716. vec3 direction;
  717. vec3 color;
  718. };
  719. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  720. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  721. light.color = directionalLight.color;
  722. light.direction = directionalLight.direction;
  723. light.visible = true;
  724. }
  725. #endif
  726. #if NUM_POINT_LIGHTS > 0
  727. struct PointLight {
  728. vec3 position;
  729. vec3 color;
  730. float distance;
  731. float decay;
  732. };
  733. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  734. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  735. vec3 lVector = pointLight.position - geometryPosition;
  736. light.direction = normalize( lVector );
  737. float lightDistance = length( lVector );
  738. light.color = pointLight.color;
  739. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  740. light.visible = ( light.color != vec3( 0.0 ) );
  741. }
  742. #endif
  743. #if NUM_SPOT_LIGHTS > 0
  744. struct SpotLight {
  745. vec3 position;
  746. vec3 direction;
  747. vec3 color;
  748. float distance;
  749. float decay;
  750. float coneCos;
  751. float penumbraCos;
  752. };
  753. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  754. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  755. vec3 lVector = spotLight.position - geometryPosition;
  756. light.direction = normalize( lVector );
  757. float angleCos = dot( light.direction, spotLight.direction );
  758. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  759. if ( spotAttenuation > 0.0 ) {
  760. float lightDistance = length( lVector );
  761. light.color = spotLight.color * spotAttenuation;
  762. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  763. light.visible = ( light.color != vec3( 0.0 ) );
  764. } else {
  765. light.color = vec3( 0.0 );
  766. light.visible = false;
  767. }
  768. }
  769. #endif
  770. #if NUM_RECT_AREA_LIGHTS > 0
  771. struct RectAreaLight {
  772. vec3 color;
  773. vec3 position;
  774. vec3 halfWidth;
  775. vec3 halfHeight;
  776. };
  777. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  778. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  779. #endif
  780. #if NUM_HEMI_LIGHTS > 0
  781. struct HemisphereLight {
  782. vec3 direction;
  783. vec3 skyColor;
  784. vec3 groundColor;
  785. };
  786. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  787. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  788. float dotNL = dot( normal, hemiLight.direction );
  789. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  790. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  791. return irradiance;
  792. }
  793. #endif`,R0e=`#ifdef USE_ENVMAP
  794. vec3 getIBLIrradiance( const in vec3 normal ) {
  795. #ifdef ENVMAP_TYPE_CUBE_UV
  796. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  797. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
  798. return PI * envMapColor.rgb * envMapIntensity;
  799. #else
  800. return vec3( 0.0 );
  801. #endif
  802. }
  803. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  804. #ifdef ENVMAP_TYPE_CUBE_UV
  805. vec3 reflectVec = reflect( - viewDir, normal );
  806. reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
  807. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  808. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
  809. return envMapColor.rgb * envMapIntensity;
  810. #else
  811. return vec3( 0.0 );
  812. #endif
  813. }
  814. #ifdef USE_ANISOTROPY
  815. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  816. #ifdef ENVMAP_TYPE_CUBE_UV
  817. vec3 bentNormal = cross( bitangent, viewDir );
  818. bentNormal = normalize( cross( bentNormal, bitangent ) );
  819. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  820. return getIBLRadiance( viewDir, bentNormal, roughness );
  821. #else
  822. return vec3( 0.0 );
  823. #endif
  824. }
  825. #endif
  826. #endif`,L0e=`ToonMaterial material;
  827. material.diffuseColor = diffuseColor.rgb;`,O0e=`varying vec3 vViewPosition;
  828. struct ToonMaterial {
  829. vec3 diffuseColor;
  830. };
  831. 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 ) {
  832. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  833. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  834. }
  835. 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 ) {
  836. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  837. }
  838. #define RE_Direct RE_Direct_Toon
  839. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,I0e=`BlinnPhongMaterial material;
  840. material.diffuseColor = diffuseColor.rgb;
  841. material.specularColor = specular;
  842. material.specularShininess = shininess;
  843. material.specularStrength = specularStrength;`,z0e=`varying vec3 vViewPosition;
  844. struct BlinnPhongMaterial {
  845. vec3 diffuseColor;
  846. vec3 specularColor;
  847. float specularShininess;
  848. float specularStrength;
  849. };
  850. 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 ) {
  851. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  852. vec3 irradiance = dotNL * directLight.color;
  853. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  854. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  855. }
  856. 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 ) {
  857. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  858. }
  859. #define RE_Direct RE_Direct_BlinnPhong
  860. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,U0e=`PhysicalMaterial material;
  861. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  862. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  863. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  864. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  865. material.roughness = min( material.roughness, 1.0 );
  866. #ifdef IOR
  867. material.ior = ior;
  868. #ifdef USE_SPECULAR
  869. float specularIntensityFactor = specularIntensity;
  870. vec3 specularColorFactor = specularColor;
  871. #ifdef USE_SPECULAR_COLORMAP
  872. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  873. #endif
  874. #ifdef USE_SPECULAR_INTENSITYMAP
  875. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  876. #endif
  877. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  878. #else
  879. float specularIntensityFactor = 1.0;
  880. vec3 specularColorFactor = vec3( 1.0 );
  881. material.specularF90 = 1.0;
  882. #endif
  883. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  884. #else
  885. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  886. material.specularF90 = 1.0;
  887. #endif
  888. #ifdef USE_CLEARCOAT
  889. material.clearcoat = clearcoat;
  890. material.clearcoatRoughness = clearcoatRoughness;
  891. material.clearcoatF0 = vec3( 0.04 );
  892. material.clearcoatF90 = 1.0;
  893. #ifdef USE_CLEARCOATMAP
  894. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  895. #endif
  896. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  897. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  898. #endif
  899. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  900. material.clearcoatRoughness += geometryRoughness;
  901. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  902. #endif
  903. #ifdef USE_DISPERSION
  904. material.dispersion = dispersion;
  905. #endif
  906. #ifdef USE_IRIDESCENCE
  907. material.iridescence = iridescence;
  908. material.iridescenceIOR = iridescenceIOR;
  909. #ifdef USE_IRIDESCENCEMAP
  910. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  911. #endif
  912. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  913. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  914. #else
  915. material.iridescenceThickness = iridescenceThicknessMaximum;
  916. #endif
  917. #endif
  918. #ifdef USE_SHEEN
  919. material.sheenColor = sheenColor;
  920. #ifdef USE_SHEEN_COLORMAP
  921. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  922. #endif
  923. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  924. #ifdef USE_SHEEN_ROUGHNESSMAP
  925. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  926. #endif
  927. #endif
  928. #ifdef USE_ANISOTROPY
  929. #ifdef USE_ANISOTROPYMAP
  930. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  931. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  932. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  933. #else
  934. vec2 anisotropyV = anisotropyVector;
  935. #endif
  936. material.anisotropy = length( anisotropyV );
  937. if( material.anisotropy == 0.0 ) {
  938. anisotropyV = vec2( 1.0, 0.0 );
  939. } else {
  940. anisotropyV /= material.anisotropy;
  941. material.anisotropy = saturate( material.anisotropy );
  942. }
  943. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  944. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  945. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  946. #endif`,B0e=`uniform sampler2D dfgLUT;
  947. struct PhysicalMaterial {
  948. vec3 diffuseColor;
  949. float roughness;
  950. vec3 specularColor;
  951. float specularF90;
  952. float dispersion;
  953. #ifdef USE_CLEARCOAT
  954. float clearcoat;
  955. float clearcoatRoughness;
  956. vec3 clearcoatF0;
  957. float clearcoatF90;
  958. #endif
  959. #ifdef USE_IRIDESCENCE
  960. float iridescence;
  961. float iridescenceIOR;
  962. float iridescenceThickness;
  963. vec3 iridescenceFresnel;
  964. vec3 iridescenceF0;
  965. #endif
  966. #ifdef USE_SHEEN
  967. vec3 sheenColor;
  968. float sheenRoughness;
  969. #endif
  970. #ifdef IOR
  971. float ior;
  972. #endif
  973. #ifdef USE_TRANSMISSION
  974. float transmission;
  975. float transmissionAlpha;
  976. float thickness;
  977. float attenuationDistance;
  978. vec3 attenuationColor;
  979. #endif
  980. #ifdef USE_ANISOTROPY
  981. float anisotropy;
  982. float alphaT;
  983. vec3 anisotropyT;
  984. vec3 anisotropyB;
  985. #endif
  986. };
  987. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  988. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  989. vec3 sheenSpecularDirect = vec3( 0.0 );
  990. vec3 sheenSpecularIndirect = vec3(0.0 );
  991. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  992. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  993. float x2 = x * x;
  994. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  995. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  996. }
  997. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  998. float a2 = pow2( alpha );
  999. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  1000. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  1001. return 0.5 / max( gv + gl, EPSILON );
  1002. }
  1003. float D_GGX( const in float alpha, const in float dotNH ) {
  1004. float a2 = pow2( alpha );
  1005. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  1006. return RECIPROCAL_PI * a2 / pow2( denom );
  1007. }
  1008. #ifdef USE_ANISOTROPY
  1009. 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 ) {
  1010. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  1011. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  1012. float v = 0.5 / ( gv + gl );
  1013. return saturate(v);
  1014. }
  1015. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  1016. float a2 = alphaT * alphaB;
  1017. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  1018. highp float v2 = dot( v, v );
  1019. float w2 = a2 / v2;
  1020. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  1021. }
  1022. #endif
  1023. #ifdef USE_CLEARCOAT
  1024. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  1025. vec3 f0 = material.clearcoatF0;
  1026. float f90 = material.clearcoatF90;
  1027. float roughness = material.clearcoatRoughness;
  1028. float alpha = pow2( roughness );
  1029. vec3 halfDir = normalize( lightDir + viewDir );
  1030. float dotNL = saturate( dot( normal, lightDir ) );
  1031. float dotNV = saturate( dot( normal, viewDir ) );
  1032. float dotNH = saturate( dot( normal, halfDir ) );
  1033. float dotVH = saturate( dot( viewDir, halfDir ) );
  1034. vec3 F = F_Schlick( f0, f90, dotVH );
  1035. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1036. float D = D_GGX( alpha, dotNH );
  1037. return F * ( V * D );
  1038. }
  1039. #endif
  1040. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1041. vec3 f0 = material.specularColor;
  1042. float f90 = material.specularF90;
  1043. float roughness = material.roughness;
  1044. float alpha = pow2( roughness );
  1045. vec3 halfDir = normalize( lightDir + viewDir );
  1046. float dotNL = saturate( dot( normal, lightDir ) );
  1047. float dotNV = saturate( dot( normal, viewDir ) );
  1048. float dotNH = saturate( dot( normal, halfDir ) );
  1049. float dotVH = saturate( dot( viewDir, halfDir ) );
  1050. vec3 F = F_Schlick( f0, f90, dotVH );
  1051. #ifdef USE_IRIDESCENCE
  1052. F = mix( F, material.iridescenceFresnel, material.iridescence );
  1053. #endif
  1054. #ifdef USE_ANISOTROPY
  1055. float dotTL = dot( material.anisotropyT, lightDir );
  1056. float dotTV = dot( material.anisotropyT, viewDir );
  1057. float dotTH = dot( material.anisotropyT, halfDir );
  1058. float dotBL = dot( material.anisotropyB, lightDir );
  1059. float dotBV = dot( material.anisotropyB, viewDir );
  1060. float dotBH = dot( material.anisotropyB, halfDir );
  1061. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  1062. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  1063. #else
  1064. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1065. float D = D_GGX( alpha, dotNH );
  1066. #endif
  1067. return F * ( V * D );
  1068. }
  1069. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  1070. const float LUT_SIZE = 64.0;
  1071. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  1072. const float LUT_BIAS = 0.5 / LUT_SIZE;
  1073. float dotNV = saturate( dot( N, V ) );
  1074. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  1075. uv = uv * LUT_SCALE + LUT_BIAS;
  1076. return uv;
  1077. }
  1078. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  1079. float l = length( f );
  1080. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  1081. }
  1082. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  1083. float x = dot( v1, v2 );
  1084. float y = abs( x );
  1085. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  1086. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  1087. float v = a / b;
  1088. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  1089. return cross( v1, v2 ) * theta_sintheta;
  1090. }
  1091. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  1092. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  1093. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  1094. vec3 lightNormal = cross( v1, v2 );
  1095. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  1096. vec3 T1, T2;
  1097. T1 = normalize( V - N * dot( V, N ) );
  1098. T2 = - cross( N, T1 );
  1099. mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
  1100. vec3 coords[ 4 ];
  1101. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  1102. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  1103. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  1104. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  1105. coords[ 0 ] = normalize( coords[ 0 ] );
  1106. coords[ 1 ] = normalize( coords[ 1 ] );
  1107. coords[ 2 ] = normalize( coords[ 2 ] );
  1108. coords[ 3 ] = normalize( coords[ 3 ] );
  1109. vec3 vectorFormFactor = vec3( 0.0 );
  1110. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  1111. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  1112. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  1113. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  1114. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  1115. return vec3( result );
  1116. }
  1117. #if defined( USE_SHEEN )
  1118. float D_Charlie( float roughness, float dotNH ) {
  1119. float alpha = pow2( roughness );
  1120. float invAlpha = 1.0 / alpha;
  1121. float cos2h = dotNH * dotNH;
  1122. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  1123. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  1124. }
  1125. float V_Neubelt( float dotNV, float dotNL ) {
  1126. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  1127. }
  1128. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  1129. vec3 halfDir = normalize( lightDir + viewDir );
  1130. float dotNL = saturate( dot( normal, lightDir ) );
  1131. float dotNV = saturate( dot( normal, viewDir ) );
  1132. float dotNH = saturate( dot( normal, halfDir ) );
  1133. float D = D_Charlie( sheenRoughness, dotNH );
  1134. float V = V_Neubelt( dotNV, dotNL );
  1135. return sheenColor * ( D * V );
  1136. }
  1137. #endif
  1138. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1139. float dotNV = saturate( dot( normal, viewDir ) );
  1140. float r2 = roughness * roughness;
  1141. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  1142. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  1143. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  1144. return saturate( DG * RECIPROCAL_PI );
  1145. }
  1146. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1147. float dotNV = saturate( dot( normal, viewDir ) );
  1148. vec2 uv = vec2( roughness, dotNV );
  1149. return texture2D( dfgLUT, uv ).rg;
  1150. }
  1151. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  1152. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1153. return specularColor * fab.x + specularF90 * fab.y;
  1154. }
  1155. #ifdef USE_IRIDESCENCE
  1156. 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 ) {
  1157. #else
  1158. 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 ) {
  1159. #endif
  1160. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1161. #ifdef USE_IRIDESCENCE
  1162. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  1163. #else
  1164. vec3 Fr = specularColor;
  1165. #endif
  1166. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  1167. float Ess = fab.x + fab.y;
  1168. float Ems = 1.0 - Ess;
  1169. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  1170. singleScatter += FssEss;
  1171. multiScatter += Fms * Ems;
  1172. }
  1173. vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1174. vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
  1175. float dotNL = saturate( dot( normal, lightDir ) );
  1176. float dotNV = saturate( dot( normal, viewDir ) );
  1177. vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness );
  1178. vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness );
  1179. vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y;
  1180. vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y;
  1181. float Ess_V = dfgV.x + dfgV.y;
  1182. float Ess_L = dfgL.x + dfgL.y;
  1183. float Ems_V = 1.0 - Ess_V;
  1184. float Ems_L = 1.0 - Ess_L;
  1185. vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619;
  1186. vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON );
  1187. float compensationFactor = Ems_V * Ems_L;
  1188. vec3 multiScatter = Fms * compensationFactor;
  1189. return singleScatter + multiScatter;
  1190. }
  1191. #if NUM_RECT_AREA_LIGHTS > 0
  1192. 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 ) {
  1193. vec3 normal = geometryNormal;
  1194. vec3 viewDir = geometryViewDir;
  1195. vec3 position = geometryPosition;
  1196. vec3 lightPos = rectAreaLight.position;
  1197. vec3 halfWidth = rectAreaLight.halfWidth;
  1198. vec3 halfHeight = rectAreaLight.halfHeight;
  1199. vec3 lightColor = rectAreaLight.color;
  1200. float roughness = material.roughness;
  1201. vec3 rectCoords[ 4 ];
  1202. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  1203. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  1204. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  1205. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  1206. vec4 t1 = texture2D( ltc_1, uv );
  1207. vec4 t2 = texture2D( ltc_2, uv );
  1208. mat3 mInv = mat3(
  1209. vec3( t1.x, 0, t1.y ),
  1210. vec3( 0, 1, 0 ),
  1211. vec3( t1.z, 0, t1.w )
  1212. );
  1213. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  1214. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  1215. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  1216. }
  1217. #endif
  1218. 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 ) {
  1219. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  1220. vec3 irradiance = dotNL * directLight.color;
  1221. #ifdef USE_CLEARCOAT
  1222. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  1223. vec3 ccIrradiance = dotNLcc * directLight.color;
  1224. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  1225. #endif
  1226. #ifdef USE_SHEEN
  1227. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  1228. #endif
  1229. reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
  1230. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1231. }
  1232. 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 ) {
  1233. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1234. }
  1235. 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) {
  1236. #ifdef USE_CLEARCOAT
  1237. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  1238. #endif
  1239. #ifdef USE_SHEEN
  1240. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  1241. #endif
  1242. vec3 singleScattering = vec3( 0.0 );
  1243. vec3 multiScattering = vec3( 0.0 );
  1244. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  1245. #ifdef USE_IRIDESCENCE
  1246. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  1247. #else
  1248. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  1249. #endif
  1250. vec3 totalScattering = singleScattering + multiScattering;
  1251. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  1252. reflectedLight.indirectSpecular += radiance * singleScattering;
  1253. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  1254. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  1255. }
  1256. #define RE_Direct RE_Direct_Physical
  1257. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  1258. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  1259. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  1260. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  1261. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  1262. }`,H0e=`
  1263. vec3 geometryPosition = - vViewPosition;
  1264. vec3 geometryNormal = normal;
  1265. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  1266. vec3 geometryClearcoatNormal = vec3( 0.0 );
  1267. #ifdef USE_CLEARCOAT
  1268. geometryClearcoatNormal = clearcoatNormal;
  1269. #endif
  1270. #ifdef USE_IRIDESCENCE
  1271. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  1272. if ( material.iridescenceThickness == 0.0 ) {
  1273. material.iridescence = 0.0;
  1274. } else {
  1275. material.iridescence = saturate( material.iridescence );
  1276. }
  1277. if ( material.iridescence > 0.0 ) {
  1278. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  1279. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  1280. }
  1281. #endif
  1282. IncidentLight directLight;
  1283. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  1284. PointLight pointLight;
  1285. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  1286. PointLightShadow pointLightShadow;
  1287. #endif
  1288. #pragma unroll_loop_start
  1289. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  1290. pointLight = pointLights[ i ];
  1291. getPointLightInfo( pointLight, geometryPosition, directLight );
  1292. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  1293. pointLightShadow = pointLightShadows[ i ];
  1294. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  1295. #endif
  1296. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1297. }
  1298. #pragma unroll_loop_end
  1299. #endif
  1300. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  1301. SpotLight spotLight;
  1302. vec4 spotColor;
  1303. vec3 spotLightCoord;
  1304. bool inSpotLightMap;
  1305. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  1306. SpotLightShadow spotLightShadow;
  1307. #endif
  1308. #pragma unroll_loop_start
  1309. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  1310. spotLight = spotLights[ i ];
  1311. getSpotLightInfo( spotLight, geometryPosition, directLight );
  1312. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1313. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  1314. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1315. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  1316. #else
  1317. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1318. #endif
  1319. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  1320. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  1321. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  1322. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  1323. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  1324. #endif
  1325. #undef SPOT_LIGHT_MAP_INDEX
  1326. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1327. spotLightShadow = spotLightShadows[ i ];
  1328. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1329. #endif
  1330. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1331. }
  1332. #pragma unroll_loop_end
  1333. #endif
  1334. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  1335. DirectionalLight directionalLight;
  1336. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  1337. DirectionalLightShadow directionalLightShadow;
  1338. #endif
  1339. #pragma unroll_loop_start
  1340. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  1341. directionalLight = directionalLights[ i ];
  1342. getDirectionalLightInfo( directionalLight, directLight );
  1343. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  1344. directionalLightShadow = directionalLightShadows[ i ];
  1345. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1346. #endif
  1347. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1348. }
  1349. #pragma unroll_loop_end
  1350. #endif
  1351. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  1352. RectAreaLight rectAreaLight;
  1353. #pragma unroll_loop_start
  1354. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  1355. rectAreaLight = rectAreaLights[ i ];
  1356. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1357. }
  1358. #pragma unroll_loop_end
  1359. #endif
  1360. #if defined( RE_IndirectDiffuse )
  1361. vec3 iblIrradiance = vec3( 0.0 );
  1362. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  1363. #if defined( USE_LIGHT_PROBES )
  1364. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  1365. #endif
  1366. #if ( NUM_HEMI_LIGHTS > 0 )
  1367. #pragma unroll_loop_start
  1368. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  1369. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  1370. }
  1371. #pragma unroll_loop_end
  1372. #endif
  1373. #endif
  1374. #if defined( RE_IndirectSpecular )
  1375. vec3 radiance = vec3( 0.0 );
  1376. vec3 clearcoatRadiance = vec3( 0.0 );
  1377. #endif`,q0e=`#if defined( RE_IndirectDiffuse )
  1378. #ifdef USE_LIGHTMAP
  1379. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  1380. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  1381. irradiance += lightMapIrradiance;
  1382. #endif
  1383. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  1384. iblIrradiance += getIBLIrradiance( geometryNormal );
  1385. #endif
  1386. #endif
  1387. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  1388. #ifdef USE_ANISOTROPY
  1389. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  1390. #else
  1391. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  1392. #endif
  1393. #ifdef USE_CLEARCOAT
  1394. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  1395. #endif
  1396. #endif`,$0e=`#if defined( RE_IndirectDiffuse )
  1397. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1398. #endif
  1399. #if defined( RE_IndirectSpecular )
  1400. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1401. #endif`,V0e=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1402. gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  1403. #endif`,G0e=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1404. uniform float logDepthBufFC;
  1405. varying float vFragDepth;
  1406. varying float vIsPerspective;
  1407. #endif`,W0e=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1408. varying float vFragDepth;
  1409. varying float vIsPerspective;
  1410. #endif`,K0e=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1411. vFragDepth = 1.0 + gl_Position.w;
  1412. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  1413. #endif`,Y0e=`#ifdef USE_MAP
  1414. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  1415. #ifdef DECODE_VIDEO_TEXTURE
  1416. sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
  1417. #endif
  1418. diffuseColor *= sampledDiffuseColor;
  1419. #endif`,X0e=`#ifdef USE_MAP
  1420. uniform sampler2D map;
  1421. #endif`,Q0e=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1422. #if defined( USE_POINTS_UV )
  1423. vec2 uv = vUv;
  1424. #else
  1425. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  1426. #endif
  1427. #endif
  1428. #ifdef USE_MAP
  1429. diffuseColor *= texture2D( map, uv );
  1430. #endif
  1431. #ifdef USE_ALPHAMAP
  1432. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  1433. #endif`,Z0e=`#if defined( USE_POINTS_UV )
  1434. varying vec2 vUv;
  1435. #else
  1436. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1437. uniform mat3 uvTransform;
  1438. #endif
  1439. #endif
  1440. #ifdef USE_MAP
  1441. uniform sampler2D map;
  1442. #endif
  1443. #ifdef USE_ALPHAMAP
  1444. uniform sampler2D alphaMap;
  1445. #endif`,J0e=`float metalnessFactor = metalness;
  1446. #ifdef USE_METALNESSMAP
  1447. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  1448. metalnessFactor *= texelMetalness.b;
  1449. #endif`,ewe=`#ifdef USE_METALNESSMAP
  1450. uniform sampler2D metalnessMap;
  1451. #endif`,twe=`#ifdef USE_INSTANCING_MORPH
  1452. float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1453. float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
  1454. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1455. morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
  1456. }
  1457. #endif`,nwe=`#if defined( USE_MORPHCOLORS )
  1458. vColor *= morphTargetBaseInfluence;
  1459. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1460. #if defined( USE_COLOR_ALPHA )
  1461. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  1462. #elif defined( USE_COLOR )
  1463. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  1464. #endif
  1465. }
  1466. #endif`,rwe=`#ifdef USE_MORPHNORMALS
  1467. objectNormal *= morphTargetBaseInfluence;
  1468. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1469. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  1470. }
  1471. #endif`,awe=`#ifdef USE_MORPHTARGETS
  1472. #ifndef USE_INSTANCING_MORPH
  1473. uniform float morphTargetBaseInfluence;
  1474. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1475. #endif
  1476. uniform sampler2DArray morphTargetsTexture;
  1477. uniform ivec2 morphTargetsTextureSize;
  1478. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  1479. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  1480. int y = texelIndex / morphTargetsTextureSize.x;
  1481. int x = texelIndex - y * morphTargetsTextureSize.x;
  1482. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  1483. return texelFetch( morphTargetsTexture, morphUV, 0 );
  1484. }
  1485. #endif`,iwe=`#ifdef USE_MORPHTARGETS
  1486. transformed *= morphTargetBaseInfluence;
  1487. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1488. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  1489. }
  1490. #endif`,swe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  1491. #ifdef FLAT_SHADED
  1492. vec3 fdx = dFdx( vViewPosition );
  1493. vec3 fdy = dFdy( vViewPosition );
  1494. vec3 normal = normalize( cross( fdx, fdy ) );
  1495. #else
  1496. vec3 normal = normalize( vNormal );
  1497. #ifdef DOUBLE_SIDED
  1498. normal *= faceDirection;
  1499. #endif
  1500. #endif
  1501. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  1502. #ifdef USE_TANGENT
  1503. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1504. #else
  1505. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  1506. #if defined( USE_NORMALMAP )
  1507. vNormalMapUv
  1508. #elif defined( USE_CLEARCOAT_NORMALMAP )
  1509. vClearcoatNormalMapUv
  1510. #else
  1511. vUv
  1512. #endif
  1513. );
  1514. #endif
  1515. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1516. tbn[0] *= faceDirection;
  1517. tbn[1] *= faceDirection;
  1518. #endif
  1519. #endif
  1520. #ifdef USE_CLEARCOAT_NORMALMAP
  1521. #ifdef USE_TANGENT
  1522. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1523. #else
  1524. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  1525. #endif
  1526. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1527. tbn2[0] *= faceDirection;
  1528. tbn2[1] *= faceDirection;
  1529. #endif
  1530. #endif
  1531. vec3 nonPerturbedNormal = normal;`,owe=`#ifdef USE_NORMALMAP_OBJECTSPACE
  1532. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1533. #ifdef FLIP_SIDED
  1534. normal = - normal;
  1535. #endif
  1536. #ifdef DOUBLE_SIDED
  1537. normal = normal * faceDirection;
  1538. #endif
  1539. normal = normalize( normalMatrix * normal );
  1540. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  1541. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1542. mapN.xy *= normalScale;
  1543. normal = normalize( tbn * mapN );
  1544. #elif defined( USE_BUMPMAP )
  1545. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  1546. #endif`,lwe=`#ifndef FLAT_SHADED
  1547. varying vec3 vNormal;
  1548. #ifdef USE_TANGENT
  1549. varying vec3 vTangent;
  1550. varying vec3 vBitangent;
  1551. #endif
  1552. #endif`,cwe=`#ifndef FLAT_SHADED
  1553. varying vec3 vNormal;
  1554. #ifdef USE_TANGENT
  1555. varying vec3 vTangent;
  1556. varying vec3 vBitangent;
  1557. #endif
  1558. #endif`,dwe=`#ifndef FLAT_SHADED
  1559. vNormal = normalize( transformedNormal );
  1560. #ifdef USE_TANGENT
  1561. vTangent = normalize( transformedTangent );
  1562. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  1563. #endif
  1564. #endif`,uwe=`#ifdef USE_NORMALMAP
  1565. uniform sampler2D normalMap;
  1566. uniform vec2 normalScale;
  1567. #endif
  1568. #ifdef USE_NORMALMAP_OBJECTSPACE
  1569. uniform mat3 normalMatrix;
  1570. #endif
  1571. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  1572. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  1573. vec3 q0 = dFdx( eye_pos.xyz );
  1574. vec3 q1 = dFdy( eye_pos.xyz );
  1575. vec2 st0 = dFdx( uv.st );
  1576. vec2 st1 = dFdy( uv.st );
  1577. vec3 N = surf_norm;
  1578. vec3 q1perp = cross( q1, N );
  1579. vec3 q0perp = cross( N, q0 );
  1580. vec3 T = q1perp * st0.x + q0perp * st1.x;
  1581. vec3 B = q1perp * st0.y + q0perp * st1.y;
  1582. float det = max( dot( T, T ), dot( B, B ) );
  1583. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  1584. return mat3( T * scale, B * scale, N );
  1585. }
  1586. #endif`,mwe=`#ifdef USE_CLEARCOAT
  1587. vec3 clearcoatNormal = nonPerturbedNormal;
  1588. #endif`,hwe=`#ifdef USE_CLEARCOAT_NORMALMAP
  1589. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  1590. clearcoatMapN.xy *= clearcoatNormalScale;
  1591. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  1592. #endif`,pwe=`#ifdef USE_CLEARCOATMAP
  1593. uniform sampler2D clearcoatMap;
  1594. #endif
  1595. #ifdef USE_CLEARCOAT_NORMALMAP
  1596. uniform sampler2D clearcoatNormalMap;
  1597. uniform vec2 clearcoatNormalScale;
  1598. #endif
  1599. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  1600. uniform sampler2D clearcoatRoughnessMap;
  1601. #endif`,fwe=`#ifdef USE_IRIDESCENCEMAP
  1602. uniform sampler2D iridescenceMap;
  1603. #endif
  1604. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  1605. uniform sampler2D iridescenceThicknessMap;
  1606. #endif`,gwe=`#ifdef OPAQUE
  1607. diffuseColor.a = 1.0;
  1608. #endif
  1609. #ifdef USE_TRANSMISSION
  1610. diffuseColor.a *= material.transmissionAlpha;
  1611. #endif
  1612. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,bwe=`vec3 packNormalToRGB( const in vec3 normal ) {
  1613. return normalize( normal ) * 0.5 + 0.5;
  1614. }
  1615. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  1616. return 2.0 * rgb.xyz - 1.0;
  1617. }
  1618. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
  1619. const float Inv255 = 1. / 255.;
  1620. const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
  1621. const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
  1622. const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
  1623. const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
  1624. vec4 packDepthToRGBA( const in float v ) {
  1625. if( v <= 0.0 )
  1626. return vec4( 0., 0., 0., 0. );
  1627. if( v >= 1.0 )
  1628. return vec4( 1., 1., 1., 1. );
  1629. float vuf;
  1630. float af = modf( v * PackFactors.a, vuf );
  1631. float bf = modf( vuf * ShiftRight8, vuf );
  1632. float gf = modf( vuf * ShiftRight8, vuf );
  1633. return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
  1634. }
  1635. vec3 packDepthToRGB( const in float v ) {
  1636. if( v <= 0.0 )
  1637. return vec3( 0., 0., 0. );
  1638. if( v >= 1.0 )
  1639. return vec3( 1., 1., 1. );
  1640. float vuf;
  1641. float bf = modf( v * PackFactors.b, vuf );
  1642. float gf = modf( vuf * ShiftRight8, vuf );
  1643. return vec3( vuf * Inv255, gf * PackUpscale, bf );
  1644. }
  1645. vec2 packDepthToRG( const in float v ) {
  1646. if( v <= 0.0 )
  1647. return vec2( 0., 0. );
  1648. if( v >= 1.0 )
  1649. return vec2( 1., 1. );
  1650. float vuf;
  1651. float gf = modf( v * 256., vuf );
  1652. return vec2( vuf * Inv255, gf );
  1653. }
  1654. float unpackRGBAToDepth( const in vec4 v ) {
  1655. return dot( v, UnpackFactors4 );
  1656. }
  1657. float unpackRGBToDepth( const in vec3 v ) {
  1658. return dot( v, UnpackFactors3 );
  1659. }
  1660. float unpackRGToDepth( const in vec2 v ) {
  1661. return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
  1662. }
  1663. vec4 pack2HalfToRGBA( const in vec2 v ) {
  1664. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  1665. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  1666. }
  1667. vec2 unpackRGBATo2Half( const in vec4 v ) {
  1668. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  1669. }
  1670. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  1671. return ( viewZ + near ) / ( near - far );
  1672. }
  1673. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1674. return depth * ( near - far ) - near;
  1675. }
  1676. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  1677. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  1678. }
  1679. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1680. return ( near * far ) / ( ( far - near ) * depth - far );
  1681. }`,xwe=`#ifdef PREMULTIPLIED_ALPHA
  1682. gl_FragColor.rgb *= gl_FragColor.a;
  1683. #endif`,ywe=`vec4 mvPosition = vec4( transformed, 1.0 );
  1684. #ifdef USE_BATCHING
  1685. mvPosition = batchingMatrix * mvPosition;
  1686. #endif
  1687. #ifdef USE_INSTANCING
  1688. mvPosition = instanceMatrix * mvPosition;
  1689. #endif
  1690. mvPosition = modelViewMatrix * mvPosition;
  1691. gl_Position = projectionMatrix * mvPosition;`,vwe=`#ifdef DITHERING
  1692. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  1693. #endif`,wwe=`#ifdef DITHERING
  1694. vec3 dithering( vec3 color ) {
  1695. float grid_position = rand( gl_FragCoord.xy );
  1696. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  1697. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  1698. return color + dither_shift_RGB;
  1699. }
  1700. #endif`,Swe=`float roughnessFactor = roughness;
  1701. #ifdef USE_ROUGHNESSMAP
  1702. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  1703. roughnessFactor *= texelRoughness.g;
  1704. #endif`,_we=`#ifdef USE_ROUGHNESSMAP
  1705. uniform sampler2D roughnessMap;
  1706. #endif`,kwe=`#if NUM_SPOT_LIGHT_COORDS > 0
  1707. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1708. #endif
  1709. #if NUM_SPOT_LIGHT_MAPS > 0
  1710. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  1711. #endif
  1712. #ifdef USE_SHADOWMAP
  1713. #if NUM_DIR_LIGHT_SHADOWS > 0
  1714. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  1715. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1716. struct DirectionalLightShadow {
  1717. float shadowIntensity;
  1718. float shadowBias;
  1719. float shadowNormalBias;
  1720. float shadowRadius;
  1721. vec2 shadowMapSize;
  1722. };
  1723. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1724. #endif
  1725. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1726. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  1727. struct SpotLightShadow {
  1728. float shadowIntensity;
  1729. float shadowBias;
  1730. float shadowNormalBias;
  1731. float shadowRadius;
  1732. vec2 shadowMapSize;
  1733. };
  1734. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1735. #endif
  1736. #if NUM_POINT_LIGHT_SHADOWS > 0
  1737. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  1738. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1739. struct PointLightShadow {
  1740. float shadowIntensity;
  1741. float shadowBias;
  1742. float shadowNormalBias;
  1743. float shadowRadius;
  1744. vec2 shadowMapSize;
  1745. float shadowCameraNear;
  1746. float shadowCameraFar;
  1747. };
  1748. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1749. #endif
  1750. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  1751. float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
  1752. #ifdef USE_REVERSED_DEPTH_BUFFER
  1753. return step( depth, compare );
  1754. #else
  1755. return step( compare, depth );
  1756. #endif
  1757. }
  1758. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  1759. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  1760. }
  1761. float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
  1762. float occlusion = 1.0;
  1763. vec2 distribution = texture2DDistribution( shadow, uv );
  1764. #ifdef USE_REVERSED_DEPTH_BUFFER
  1765. float hard_shadow = step( distribution.x, compare );
  1766. #else
  1767. float hard_shadow = step( compare, distribution.x );
  1768. #endif
  1769. if ( hard_shadow != 1.0 ) {
  1770. float distance = compare - distribution.x;
  1771. float variance = max( 0.00000, distribution.y * distribution.y );
  1772. 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 );
  1773. }
  1774. return occlusion;
  1775. }
  1776. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  1777. float shadow = 1.0;
  1778. shadowCoord.xyz /= shadowCoord.w;
  1779. shadowCoord.z += shadowBias;
  1780. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  1781. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  1782. if ( frustumTest ) {
  1783. #if defined( SHADOWMAP_TYPE_PCF )
  1784. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1785. float dx0 = - texelSize.x * shadowRadius;
  1786. float dy0 = - texelSize.y * shadowRadius;
  1787. float dx1 = + texelSize.x * shadowRadius;
  1788. float dy1 = + texelSize.y * shadowRadius;
  1789. float dx2 = dx0 / 2.0;
  1790. float dy2 = dy0 / 2.0;
  1791. float dx3 = dx1 / 2.0;
  1792. float dy3 = dy1 / 2.0;
  1793. shadow = (
  1794. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  1795. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  1796. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  1797. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  1798. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  1799. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  1800. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  1801. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  1802. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  1803. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  1804. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  1805. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  1806. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  1807. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  1808. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  1809. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  1810. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  1811. ) * ( 1.0 / 17.0 );
  1812. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  1813. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1814. float dx = texelSize.x;
  1815. float dy = texelSize.y;
  1816. vec2 uv = shadowCoord.xy;
  1817. vec2 f = fract( uv * shadowMapSize + 0.5 );
  1818. uv -= f * texelSize;
  1819. shadow = (
  1820. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  1821. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  1822. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  1823. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  1824. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  1825. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  1826. f.x ) +
  1827. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  1828. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  1829. f.x ) +
  1830. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  1831. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  1832. f.y ) +
  1833. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  1834. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  1835. f.y ) +
  1836. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  1837. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  1838. f.x ),
  1839. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  1840. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  1841. f.x ),
  1842. f.y )
  1843. ) * ( 1.0 / 9.0 );
  1844. #elif defined( SHADOWMAP_TYPE_VSM )
  1845. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  1846. #else
  1847. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  1848. #endif
  1849. }
  1850. return mix( 1.0, shadow, shadowIntensity );
  1851. }
  1852. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  1853. vec3 absV = abs( v );
  1854. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  1855. absV *= scaleToCube;
  1856. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  1857. vec2 planar = v.xy;
  1858. float almostATexel = 1.5 * texelSizeY;
  1859. float almostOne = 1.0 - almostATexel;
  1860. if ( absV.z >= almostOne ) {
  1861. if ( v.z > 0.0 )
  1862. planar.x = 4.0 - v.x;
  1863. } else if ( absV.x >= almostOne ) {
  1864. float signX = sign( v.x );
  1865. planar.x = v.z * signX + 2.0 * signX;
  1866. } else if ( absV.y >= almostOne ) {
  1867. float signY = sign( v.y );
  1868. planar.x = v.x + 2.0 * signY + 2.0;
  1869. planar.y = v.z * signY - 2.0;
  1870. }
  1871. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  1872. }
  1873. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  1874. float shadow = 1.0;
  1875. vec3 lightToPosition = shadowCoord.xyz;
  1876. float lightToPositionLength = length( lightToPosition );
  1877. if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
  1878. float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  1879. vec3 bd3D = normalize( lightToPosition );
  1880. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  1881. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  1882. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  1883. shadow = (
  1884. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  1885. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  1886. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  1887. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  1888. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  1889. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  1890. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  1891. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  1892. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  1893. ) * ( 1.0 / 9.0 );
  1894. #else
  1895. shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  1896. #endif
  1897. }
  1898. return mix( 1.0, shadow, shadowIntensity );
  1899. }
  1900. #endif`,Nwe=`#if NUM_SPOT_LIGHT_COORDS > 0
  1901. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  1902. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1903. #endif
  1904. #ifdef USE_SHADOWMAP
  1905. #if NUM_DIR_LIGHT_SHADOWS > 0
  1906. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  1907. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1908. struct DirectionalLightShadow {
  1909. float shadowIntensity;
  1910. float shadowBias;
  1911. float shadowNormalBias;
  1912. float shadowRadius;
  1913. vec2 shadowMapSize;
  1914. };
  1915. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1916. #endif
  1917. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1918. struct SpotLightShadow {
  1919. float shadowIntensity;
  1920. float shadowBias;
  1921. float shadowNormalBias;
  1922. float shadowRadius;
  1923. vec2 shadowMapSize;
  1924. };
  1925. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1926. #endif
  1927. #if NUM_POINT_LIGHT_SHADOWS > 0
  1928. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  1929. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1930. struct PointLightShadow {
  1931. float shadowIntensity;
  1932. float shadowBias;
  1933. float shadowNormalBias;
  1934. float shadowRadius;
  1935. vec2 shadowMapSize;
  1936. float shadowCameraNear;
  1937. float shadowCameraFar;
  1938. };
  1939. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1940. #endif
  1941. #endif`,Cwe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  1942. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  1943. vec4 shadowWorldPosition;
  1944. #endif
  1945. #if defined( USE_SHADOWMAP )
  1946. #if NUM_DIR_LIGHT_SHADOWS > 0
  1947. #pragma unroll_loop_start
  1948. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1949. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  1950. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  1951. }
  1952. #pragma unroll_loop_end
  1953. #endif
  1954. #if NUM_POINT_LIGHT_SHADOWS > 0
  1955. #pragma unroll_loop_start
  1956. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  1957. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  1958. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  1959. }
  1960. #pragma unroll_loop_end
  1961. #endif
  1962. #endif
  1963. #if NUM_SPOT_LIGHT_COORDS > 0
  1964. #pragma unroll_loop_start
  1965. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  1966. shadowWorldPosition = worldPosition;
  1967. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1968. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  1969. #endif
  1970. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  1971. }
  1972. #pragma unroll_loop_end
  1973. #endif`,Pwe=`float getShadowMask() {
  1974. float shadow = 1.0;
  1975. #ifdef USE_SHADOWMAP
  1976. #if NUM_DIR_LIGHT_SHADOWS > 0
  1977. DirectionalLightShadow directionalLight;
  1978. #pragma unroll_loop_start
  1979. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1980. directionalLight = directionalLightShadows[ i ];
  1981. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1982. }
  1983. #pragma unroll_loop_end
  1984. #endif
  1985. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1986. SpotLightShadow spotLight;
  1987. #pragma unroll_loop_start
  1988. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  1989. spotLight = spotLightShadows[ i ];
  1990. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1991. }
  1992. #pragma unroll_loop_end
  1993. #endif
  1994. #if NUM_POINT_LIGHT_SHADOWS > 0
  1995. PointLightShadow pointLight;
  1996. #pragma unroll_loop_start
  1997. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  1998. pointLight = pointLightShadows[ i ];
  1999. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  2000. }
  2001. #pragma unroll_loop_end
  2002. #endif
  2003. #endif
  2004. return shadow;
  2005. }`,Twe=`#ifdef USE_SKINNING
  2006. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  2007. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  2008. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  2009. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  2010. #endif`,Awe=`#ifdef USE_SKINNING
  2011. uniform mat4 bindMatrix;
  2012. uniform mat4 bindMatrixInverse;
  2013. uniform highp sampler2D boneTexture;
  2014. mat4 getBoneMatrix( const in float i ) {
  2015. int size = textureSize( boneTexture, 0 ).x;
  2016. int j = int( i ) * 4;
  2017. int x = j % size;
  2018. int y = j / size;
  2019. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  2020. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  2021. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  2022. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  2023. return mat4( v1, v2, v3, v4 );
  2024. }
  2025. #endif`,Mwe=`#ifdef USE_SKINNING
  2026. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  2027. vec4 skinned = vec4( 0.0 );
  2028. skinned += boneMatX * skinVertex * skinWeight.x;
  2029. skinned += boneMatY * skinVertex * skinWeight.y;
  2030. skinned += boneMatZ * skinVertex * skinWeight.z;
  2031. skinned += boneMatW * skinVertex * skinWeight.w;
  2032. transformed = ( bindMatrixInverse * skinned ).xyz;
  2033. #endif`,jwe=`#ifdef USE_SKINNING
  2034. mat4 skinMatrix = mat4( 0.0 );
  2035. skinMatrix += skinWeight.x * boneMatX;
  2036. skinMatrix += skinWeight.y * boneMatY;
  2037. skinMatrix += skinWeight.z * boneMatZ;
  2038. skinMatrix += skinWeight.w * boneMatW;
  2039. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  2040. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  2041. #ifdef USE_TANGENT
  2042. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  2043. #endif
  2044. #endif`,Ewe=`float specularStrength;
  2045. #ifdef USE_SPECULARMAP
  2046. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  2047. specularStrength = texelSpecular.r;
  2048. #else
  2049. specularStrength = 1.0;
  2050. #endif`,Dwe=`#ifdef USE_SPECULARMAP
  2051. uniform sampler2D specularMap;
  2052. #endif`,Fwe=`#if defined( TONE_MAPPING )
  2053. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  2054. #endif`,Rwe=`#ifndef saturate
  2055. #define saturate( a ) clamp( a, 0.0, 1.0 )
  2056. #endif
  2057. uniform float toneMappingExposure;
  2058. vec3 LinearToneMapping( vec3 color ) {
  2059. return saturate( toneMappingExposure * color );
  2060. }
  2061. vec3 ReinhardToneMapping( vec3 color ) {
  2062. color *= toneMappingExposure;
  2063. return saturate( color / ( vec3( 1.0 ) + color ) );
  2064. }
  2065. vec3 CineonToneMapping( vec3 color ) {
  2066. color *= toneMappingExposure;
  2067. color = max( vec3( 0.0 ), color - 0.004 );
  2068. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  2069. }
  2070. vec3 RRTAndODTFit( vec3 v ) {
  2071. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  2072. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  2073. return a / b;
  2074. }
  2075. vec3 ACESFilmicToneMapping( vec3 color ) {
  2076. const mat3 ACESInputMat = mat3(
  2077. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  2078. vec3( 0.04823, 0.01566, 0.83777 )
  2079. );
  2080. const mat3 ACESOutputMat = mat3(
  2081. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  2082. vec3( -0.07367, -0.00605, 1.07602 )
  2083. );
  2084. color *= toneMappingExposure / 0.6;
  2085. color = ACESInputMat * color;
  2086. color = RRTAndODTFit( color );
  2087. color = ACESOutputMat * color;
  2088. return saturate( color );
  2089. }
  2090. const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
  2091. vec3( 1.6605, - 0.1246, - 0.0182 ),
  2092. vec3( - 0.5876, 1.1329, - 0.1006 ),
  2093. vec3( - 0.0728, - 0.0083, 1.1187 )
  2094. );
  2095. const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
  2096. vec3( 0.6274, 0.0691, 0.0164 ),
  2097. vec3( 0.3293, 0.9195, 0.0880 ),
  2098. vec3( 0.0433, 0.0113, 0.8956 )
  2099. );
  2100. vec3 agxDefaultContrastApprox( vec3 x ) {
  2101. vec3 x2 = x * x;
  2102. vec3 x4 = x2 * x2;
  2103. return + 15.5 * x4 * x2
  2104. - 40.14 * x4 * x
  2105. + 31.96 * x4
  2106. - 6.868 * x2 * x
  2107. + 0.4298 * x2
  2108. + 0.1191 * x
  2109. - 0.00232;
  2110. }
  2111. vec3 AgXToneMapping( vec3 color ) {
  2112. const mat3 AgXInsetMatrix = mat3(
  2113. vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
  2114. vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
  2115. vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
  2116. );
  2117. const mat3 AgXOutsetMatrix = mat3(
  2118. vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
  2119. vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
  2120. vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
  2121. );
  2122. const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
  2123. color *= toneMappingExposure;
  2124. color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
  2125. color = AgXInsetMatrix * color;
  2126. color = max( color, 1e-10 ); color = log2( color );
  2127. color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
  2128. color = clamp( color, 0.0, 1.0 );
  2129. color = agxDefaultContrastApprox( color );
  2130. color = AgXOutsetMatrix * color;
  2131. color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
  2132. color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
  2133. color = clamp( color, 0.0, 1.0 );
  2134. return color;
  2135. }
  2136. vec3 NeutralToneMapping( vec3 color ) {
  2137. const float StartCompression = 0.8 - 0.04;
  2138. const float Desaturation = 0.15;
  2139. color *= toneMappingExposure;
  2140. float x = min( color.r, min( color.g, color.b ) );
  2141. float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
  2142. color -= offset;
  2143. float peak = max( color.r, max( color.g, color.b ) );
  2144. if ( peak < StartCompression ) return color;
  2145. float d = 1. - StartCompression;
  2146. float newPeak = 1. - d * d / ( peak + d - StartCompression );
  2147. color *= newPeak / peak;
  2148. float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
  2149. return mix( color, vec3( newPeak ), g );
  2150. }
  2151. vec3 CustomToneMapping( vec3 color ) { return color; }`,Lwe=`#ifdef USE_TRANSMISSION
  2152. material.transmission = transmission;
  2153. material.transmissionAlpha = 1.0;
  2154. material.thickness = thickness;
  2155. material.attenuationDistance = attenuationDistance;
  2156. material.attenuationColor = attenuationColor;
  2157. #ifdef USE_TRANSMISSIONMAP
  2158. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  2159. #endif
  2160. #ifdef USE_THICKNESSMAP
  2161. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  2162. #endif
  2163. vec3 pos = vWorldPosition;
  2164. vec3 v = normalize( cameraPosition - pos );
  2165. vec3 n = inverseTransformDirection( normal, viewMatrix );
  2166. vec4 transmitted = getIBLVolumeRefraction(
  2167. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  2168. pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
  2169. material.attenuationColor, material.attenuationDistance );
  2170. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  2171. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  2172. #endif`,Owe=`#ifdef USE_TRANSMISSION
  2173. uniform float transmission;
  2174. uniform float thickness;
  2175. uniform float attenuationDistance;
  2176. uniform vec3 attenuationColor;
  2177. #ifdef USE_TRANSMISSIONMAP
  2178. uniform sampler2D transmissionMap;
  2179. #endif
  2180. #ifdef USE_THICKNESSMAP
  2181. uniform sampler2D thicknessMap;
  2182. #endif
  2183. uniform vec2 transmissionSamplerSize;
  2184. uniform sampler2D transmissionSamplerMap;
  2185. uniform mat4 modelMatrix;
  2186. uniform mat4 projectionMatrix;
  2187. varying vec3 vWorldPosition;
  2188. float w0( float a ) {
  2189. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  2190. }
  2191. float w1( float a ) {
  2192. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  2193. }
  2194. float w2( float a ){
  2195. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  2196. }
  2197. float w3( float a ) {
  2198. return ( 1.0 / 6.0 ) * ( a * a * a );
  2199. }
  2200. float g0( float a ) {
  2201. return w0( a ) + w1( a );
  2202. }
  2203. float g1( float a ) {
  2204. return w2( a ) + w3( a );
  2205. }
  2206. float h0( float a ) {
  2207. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  2208. }
  2209. float h1( float a ) {
  2210. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  2211. }
  2212. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  2213. uv = uv * texelSize.zw + 0.5;
  2214. vec2 iuv = floor( uv );
  2215. vec2 fuv = fract( uv );
  2216. float g0x = g0( fuv.x );
  2217. float g1x = g1( fuv.x );
  2218. float h0x = h0( fuv.x );
  2219. float h1x = h1( fuv.x );
  2220. float h0y = h0( fuv.y );
  2221. float h1y = h1( fuv.y );
  2222. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2223. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2224. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2225. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2226. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  2227. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  2228. }
  2229. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  2230. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  2231. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  2232. vec2 fLodSizeInv = 1.0 / fLodSize;
  2233. vec2 cLodSizeInv = 1.0 / cLodSize;
  2234. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  2235. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  2236. return mix( fSample, cSample, fract( lod ) );
  2237. }
  2238. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  2239. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  2240. vec3 modelScale;
  2241. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  2242. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  2243. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  2244. return normalize( refractionVector ) * thickness * modelScale;
  2245. }
  2246. float applyIorToRoughness( const in float roughness, const in float ior ) {
  2247. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  2248. }
  2249. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  2250. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  2251. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  2252. }
  2253. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  2254. if ( isinf( attenuationDistance ) ) {
  2255. return vec3( 1.0 );
  2256. } else {
  2257. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  2258. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  2259. }
  2260. }
  2261. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  2262. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  2263. const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
  2264. const in vec3 attenuationColor, const in float attenuationDistance ) {
  2265. vec4 transmittedLight;
  2266. vec3 transmittance;
  2267. #ifdef USE_DISPERSION
  2268. float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
  2269. vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
  2270. for ( int i = 0; i < 3; i ++ ) {
  2271. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
  2272. vec3 refractedRayExit = position + transmissionRay;
  2273. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2274. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2275. refractionCoords += 1.0;
  2276. refractionCoords /= 2.0;
  2277. vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
  2278. transmittedLight[ i ] = transmissionSample[ i ];
  2279. transmittedLight.a += transmissionSample.a;
  2280. transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
  2281. }
  2282. transmittedLight.a /= 3.0;
  2283. #else
  2284. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  2285. vec3 refractedRayExit = position + transmissionRay;
  2286. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2287. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2288. refractionCoords += 1.0;
  2289. refractionCoords /= 2.0;
  2290. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  2291. transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  2292. #endif
  2293. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  2294. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  2295. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  2296. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  2297. }
  2298. #endif`,Iwe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2299. varying vec2 vUv;
  2300. #endif
  2301. #ifdef USE_MAP
  2302. varying vec2 vMapUv;
  2303. #endif
  2304. #ifdef USE_ALPHAMAP
  2305. varying vec2 vAlphaMapUv;
  2306. #endif
  2307. #ifdef USE_LIGHTMAP
  2308. varying vec2 vLightMapUv;
  2309. #endif
  2310. #ifdef USE_AOMAP
  2311. varying vec2 vAoMapUv;
  2312. #endif
  2313. #ifdef USE_BUMPMAP
  2314. varying vec2 vBumpMapUv;
  2315. #endif
  2316. #ifdef USE_NORMALMAP
  2317. varying vec2 vNormalMapUv;
  2318. #endif
  2319. #ifdef USE_EMISSIVEMAP
  2320. varying vec2 vEmissiveMapUv;
  2321. #endif
  2322. #ifdef USE_METALNESSMAP
  2323. varying vec2 vMetalnessMapUv;
  2324. #endif
  2325. #ifdef USE_ROUGHNESSMAP
  2326. varying vec2 vRoughnessMapUv;
  2327. #endif
  2328. #ifdef USE_ANISOTROPYMAP
  2329. varying vec2 vAnisotropyMapUv;
  2330. #endif
  2331. #ifdef USE_CLEARCOATMAP
  2332. varying vec2 vClearcoatMapUv;
  2333. #endif
  2334. #ifdef USE_CLEARCOAT_NORMALMAP
  2335. varying vec2 vClearcoatNormalMapUv;
  2336. #endif
  2337. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2338. varying vec2 vClearcoatRoughnessMapUv;
  2339. #endif
  2340. #ifdef USE_IRIDESCENCEMAP
  2341. varying vec2 vIridescenceMapUv;
  2342. #endif
  2343. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2344. varying vec2 vIridescenceThicknessMapUv;
  2345. #endif
  2346. #ifdef USE_SHEEN_COLORMAP
  2347. varying vec2 vSheenColorMapUv;
  2348. #endif
  2349. #ifdef USE_SHEEN_ROUGHNESSMAP
  2350. varying vec2 vSheenRoughnessMapUv;
  2351. #endif
  2352. #ifdef USE_SPECULARMAP
  2353. varying vec2 vSpecularMapUv;
  2354. #endif
  2355. #ifdef USE_SPECULAR_COLORMAP
  2356. varying vec2 vSpecularColorMapUv;
  2357. #endif
  2358. #ifdef USE_SPECULAR_INTENSITYMAP
  2359. varying vec2 vSpecularIntensityMapUv;
  2360. #endif
  2361. #ifdef USE_TRANSMISSIONMAP
  2362. uniform mat3 transmissionMapTransform;
  2363. varying vec2 vTransmissionMapUv;
  2364. #endif
  2365. #ifdef USE_THICKNESSMAP
  2366. uniform mat3 thicknessMapTransform;
  2367. varying vec2 vThicknessMapUv;
  2368. #endif`,zwe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2369. varying vec2 vUv;
  2370. #endif
  2371. #ifdef USE_MAP
  2372. uniform mat3 mapTransform;
  2373. varying vec2 vMapUv;
  2374. #endif
  2375. #ifdef USE_ALPHAMAP
  2376. uniform mat3 alphaMapTransform;
  2377. varying vec2 vAlphaMapUv;
  2378. #endif
  2379. #ifdef USE_LIGHTMAP
  2380. uniform mat3 lightMapTransform;
  2381. varying vec2 vLightMapUv;
  2382. #endif
  2383. #ifdef USE_AOMAP
  2384. uniform mat3 aoMapTransform;
  2385. varying vec2 vAoMapUv;
  2386. #endif
  2387. #ifdef USE_BUMPMAP
  2388. uniform mat3 bumpMapTransform;
  2389. varying vec2 vBumpMapUv;
  2390. #endif
  2391. #ifdef USE_NORMALMAP
  2392. uniform mat3 normalMapTransform;
  2393. varying vec2 vNormalMapUv;
  2394. #endif
  2395. #ifdef USE_DISPLACEMENTMAP
  2396. uniform mat3 displacementMapTransform;
  2397. varying vec2 vDisplacementMapUv;
  2398. #endif
  2399. #ifdef USE_EMISSIVEMAP
  2400. uniform mat3 emissiveMapTransform;
  2401. varying vec2 vEmissiveMapUv;
  2402. #endif
  2403. #ifdef USE_METALNESSMAP
  2404. uniform mat3 metalnessMapTransform;
  2405. varying vec2 vMetalnessMapUv;
  2406. #endif
  2407. #ifdef USE_ROUGHNESSMAP
  2408. uniform mat3 roughnessMapTransform;
  2409. varying vec2 vRoughnessMapUv;
  2410. #endif
  2411. #ifdef USE_ANISOTROPYMAP
  2412. uniform mat3 anisotropyMapTransform;
  2413. varying vec2 vAnisotropyMapUv;
  2414. #endif
  2415. #ifdef USE_CLEARCOATMAP
  2416. uniform mat3 clearcoatMapTransform;
  2417. varying vec2 vClearcoatMapUv;
  2418. #endif
  2419. #ifdef USE_CLEARCOAT_NORMALMAP
  2420. uniform mat3 clearcoatNormalMapTransform;
  2421. varying vec2 vClearcoatNormalMapUv;
  2422. #endif
  2423. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2424. uniform mat3 clearcoatRoughnessMapTransform;
  2425. varying vec2 vClearcoatRoughnessMapUv;
  2426. #endif
  2427. #ifdef USE_SHEEN_COLORMAP
  2428. uniform mat3 sheenColorMapTransform;
  2429. varying vec2 vSheenColorMapUv;
  2430. #endif
  2431. #ifdef USE_SHEEN_ROUGHNESSMAP
  2432. uniform mat3 sheenRoughnessMapTransform;
  2433. varying vec2 vSheenRoughnessMapUv;
  2434. #endif
  2435. #ifdef USE_IRIDESCENCEMAP
  2436. uniform mat3 iridescenceMapTransform;
  2437. varying vec2 vIridescenceMapUv;
  2438. #endif
  2439. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2440. uniform mat3 iridescenceThicknessMapTransform;
  2441. varying vec2 vIridescenceThicknessMapUv;
  2442. #endif
  2443. #ifdef USE_SPECULARMAP
  2444. uniform mat3 specularMapTransform;
  2445. varying vec2 vSpecularMapUv;
  2446. #endif
  2447. #ifdef USE_SPECULAR_COLORMAP
  2448. uniform mat3 specularColorMapTransform;
  2449. varying vec2 vSpecularColorMapUv;
  2450. #endif
  2451. #ifdef USE_SPECULAR_INTENSITYMAP
  2452. uniform mat3 specularIntensityMapTransform;
  2453. varying vec2 vSpecularIntensityMapUv;
  2454. #endif
  2455. #ifdef USE_TRANSMISSIONMAP
  2456. uniform mat3 transmissionMapTransform;
  2457. varying vec2 vTransmissionMapUv;
  2458. #endif
  2459. #ifdef USE_THICKNESSMAP
  2460. uniform mat3 thicknessMapTransform;
  2461. varying vec2 vThicknessMapUv;
  2462. #endif`,Uwe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2463. vUv = vec3( uv, 1 ).xy;
  2464. #endif
  2465. #ifdef USE_MAP
  2466. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  2467. #endif
  2468. #ifdef USE_ALPHAMAP
  2469. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  2470. #endif
  2471. #ifdef USE_LIGHTMAP
  2472. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  2473. #endif
  2474. #ifdef USE_AOMAP
  2475. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  2476. #endif
  2477. #ifdef USE_BUMPMAP
  2478. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  2479. #endif
  2480. #ifdef USE_NORMALMAP
  2481. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  2482. #endif
  2483. #ifdef USE_DISPLACEMENTMAP
  2484. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  2485. #endif
  2486. #ifdef USE_EMISSIVEMAP
  2487. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  2488. #endif
  2489. #ifdef USE_METALNESSMAP
  2490. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  2491. #endif
  2492. #ifdef USE_ROUGHNESSMAP
  2493. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  2494. #endif
  2495. #ifdef USE_ANISOTROPYMAP
  2496. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  2497. #endif
  2498. #ifdef USE_CLEARCOATMAP
  2499. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  2500. #endif
  2501. #ifdef USE_CLEARCOAT_NORMALMAP
  2502. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  2503. #endif
  2504. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2505. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  2506. #endif
  2507. #ifdef USE_IRIDESCENCEMAP
  2508. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  2509. #endif
  2510. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2511. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  2512. #endif
  2513. #ifdef USE_SHEEN_COLORMAP
  2514. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  2515. #endif
  2516. #ifdef USE_SHEEN_ROUGHNESSMAP
  2517. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  2518. #endif
  2519. #ifdef USE_SPECULARMAP
  2520. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  2521. #endif
  2522. #ifdef USE_SPECULAR_COLORMAP
  2523. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  2524. #endif
  2525. #ifdef USE_SPECULAR_INTENSITYMAP
  2526. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  2527. #endif
  2528. #ifdef USE_TRANSMISSIONMAP
  2529. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  2530. #endif
  2531. #ifdef USE_THICKNESSMAP
  2532. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  2533. #endif`,Bwe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  2534. vec4 worldPosition = vec4( transformed, 1.0 );
  2535. #ifdef USE_BATCHING
  2536. worldPosition = batchingMatrix * worldPosition;
  2537. #endif
  2538. #ifdef USE_INSTANCING
  2539. worldPosition = instanceMatrix * worldPosition;
  2540. #endif
  2541. worldPosition = modelMatrix * worldPosition;
  2542. #endif`;const Hwe=`varying vec2 vUv;
  2543. uniform mat3 uvTransform;
  2544. void main() {
  2545. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  2546. gl_Position = vec4( position.xy, 1.0, 1.0 );
  2547. }`,qwe=`uniform sampler2D t2D;
  2548. uniform float backgroundIntensity;
  2549. varying vec2 vUv;
  2550. void main() {
  2551. vec4 texColor = texture2D( t2D, vUv );
  2552. #ifdef DECODE_VIDEO_TEXTURE
  2553. 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 );
  2554. #endif
  2555. texColor.rgb *= backgroundIntensity;
  2556. gl_FragColor = texColor;
  2557. #include <tonemapping_fragment>
  2558. #include <colorspace_fragment>
  2559. }`,$we=`varying vec3 vWorldDirection;
  2560. #include <common>
  2561. void main() {
  2562. vWorldDirection = transformDirection( position, modelMatrix );
  2563. #include <begin_vertex>
  2564. #include <project_vertex>
  2565. gl_Position.z = gl_Position.w;
  2566. }`,Vwe=`#ifdef ENVMAP_TYPE_CUBE
  2567. uniform samplerCube envMap;
  2568. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2569. uniform sampler2D envMap;
  2570. #endif
  2571. uniform float flipEnvMap;
  2572. uniform float backgroundBlurriness;
  2573. uniform float backgroundIntensity;
  2574. uniform mat3 backgroundRotation;
  2575. varying vec3 vWorldDirection;
  2576. #include <cube_uv_reflection_fragment>
  2577. void main() {
  2578. #ifdef ENVMAP_TYPE_CUBE
  2579. vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  2580. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2581. vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
  2582. #else
  2583. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  2584. #endif
  2585. texColor.rgb *= backgroundIntensity;
  2586. gl_FragColor = texColor;
  2587. #include <tonemapping_fragment>
  2588. #include <colorspace_fragment>
  2589. }`,Gwe=`varying vec3 vWorldDirection;
  2590. #include <common>
  2591. void main() {
  2592. vWorldDirection = transformDirection( position, modelMatrix );
  2593. #include <begin_vertex>
  2594. #include <project_vertex>
  2595. gl_Position.z = gl_Position.w;
  2596. }`,Wwe=`uniform samplerCube tCube;
  2597. uniform float tFlip;
  2598. uniform float opacity;
  2599. varying vec3 vWorldDirection;
  2600. void main() {
  2601. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  2602. gl_FragColor = texColor;
  2603. gl_FragColor.a *= opacity;
  2604. #include <tonemapping_fragment>
  2605. #include <colorspace_fragment>
  2606. }`,Kwe=`#include <common>
  2607. #include <batching_pars_vertex>
  2608. #include <uv_pars_vertex>
  2609. #include <displacementmap_pars_vertex>
  2610. #include <morphtarget_pars_vertex>
  2611. #include <skinning_pars_vertex>
  2612. #include <logdepthbuf_pars_vertex>
  2613. #include <clipping_planes_pars_vertex>
  2614. varying vec2 vHighPrecisionZW;
  2615. void main() {
  2616. #include <uv_vertex>
  2617. #include <batching_vertex>
  2618. #include <skinbase_vertex>
  2619. #include <morphinstance_vertex>
  2620. #ifdef USE_DISPLACEMENTMAP
  2621. #include <beginnormal_vertex>
  2622. #include <morphnormal_vertex>
  2623. #include <skinnormal_vertex>
  2624. #endif
  2625. #include <begin_vertex>
  2626. #include <morphtarget_vertex>
  2627. #include <skinning_vertex>
  2628. #include <displacementmap_vertex>
  2629. #include <project_vertex>
  2630. #include <logdepthbuf_vertex>
  2631. #include <clipping_planes_vertex>
  2632. vHighPrecisionZW = gl_Position.zw;
  2633. }`,Ywe=`#if DEPTH_PACKING == 3200
  2634. uniform float opacity;
  2635. #endif
  2636. #include <common>
  2637. #include <packing>
  2638. #include <uv_pars_fragment>
  2639. #include <map_pars_fragment>
  2640. #include <alphamap_pars_fragment>
  2641. #include <alphatest_pars_fragment>
  2642. #include <alphahash_pars_fragment>
  2643. #include <logdepthbuf_pars_fragment>
  2644. #include <clipping_planes_pars_fragment>
  2645. varying vec2 vHighPrecisionZW;
  2646. void main() {
  2647. vec4 diffuseColor = vec4( 1.0 );
  2648. #include <clipping_planes_fragment>
  2649. #if DEPTH_PACKING == 3200
  2650. diffuseColor.a = opacity;
  2651. #endif
  2652. #include <map_fragment>
  2653. #include <alphamap_fragment>
  2654. #include <alphatest_fragment>
  2655. #include <alphahash_fragment>
  2656. #include <logdepthbuf_fragment>
  2657. #ifdef USE_REVERSED_DEPTH_BUFFER
  2658. float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
  2659. #else
  2660. float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
  2661. #endif
  2662. #if DEPTH_PACKING == 3200
  2663. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  2664. #elif DEPTH_PACKING == 3201
  2665. gl_FragColor = packDepthToRGBA( fragCoordZ );
  2666. #elif DEPTH_PACKING == 3202
  2667. gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
  2668. #elif DEPTH_PACKING == 3203
  2669. gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
  2670. #endif
  2671. }`,Xwe=`#define DISTANCE
  2672. varying vec3 vWorldPosition;
  2673. #include <common>
  2674. #include <batching_pars_vertex>
  2675. #include <uv_pars_vertex>
  2676. #include <displacementmap_pars_vertex>
  2677. #include <morphtarget_pars_vertex>
  2678. #include <skinning_pars_vertex>
  2679. #include <clipping_planes_pars_vertex>
  2680. void main() {
  2681. #include <uv_vertex>
  2682. #include <batching_vertex>
  2683. #include <skinbase_vertex>
  2684. #include <morphinstance_vertex>
  2685. #ifdef USE_DISPLACEMENTMAP
  2686. #include <beginnormal_vertex>
  2687. #include <morphnormal_vertex>
  2688. #include <skinnormal_vertex>
  2689. #endif
  2690. #include <begin_vertex>
  2691. #include <morphtarget_vertex>
  2692. #include <skinning_vertex>
  2693. #include <displacementmap_vertex>
  2694. #include <project_vertex>
  2695. #include <worldpos_vertex>
  2696. #include <clipping_planes_vertex>
  2697. vWorldPosition = worldPosition.xyz;
  2698. }`,Qwe=`#define DISTANCE
  2699. uniform vec3 referencePosition;
  2700. uniform float nearDistance;
  2701. uniform float farDistance;
  2702. varying vec3 vWorldPosition;
  2703. #include <common>
  2704. #include <packing>
  2705. #include <uv_pars_fragment>
  2706. #include <map_pars_fragment>
  2707. #include <alphamap_pars_fragment>
  2708. #include <alphatest_pars_fragment>
  2709. #include <alphahash_pars_fragment>
  2710. #include <clipping_planes_pars_fragment>
  2711. void main () {
  2712. vec4 diffuseColor = vec4( 1.0 );
  2713. #include <clipping_planes_fragment>
  2714. #include <map_fragment>
  2715. #include <alphamap_fragment>
  2716. #include <alphatest_fragment>
  2717. #include <alphahash_fragment>
  2718. float dist = length( vWorldPosition - referencePosition );
  2719. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  2720. dist = saturate( dist );
  2721. gl_FragColor = packDepthToRGBA( dist );
  2722. }`,Zwe=`varying vec3 vWorldDirection;
  2723. #include <common>
  2724. void main() {
  2725. vWorldDirection = transformDirection( position, modelMatrix );
  2726. #include <begin_vertex>
  2727. #include <project_vertex>
  2728. }`,Jwe=`uniform sampler2D tEquirect;
  2729. varying vec3 vWorldDirection;
  2730. #include <common>
  2731. void main() {
  2732. vec3 direction = normalize( vWorldDirection );
  2733. vec2 sampleUV = equirectUv( direction );
  2734. gl_FragColor = texture2D( tEquirect, sampleUV );
  2735. #include <tonemapping_fragment>
  2736. #include <colorspace_fragment>
  2737. }`,eSe=`uniform float scale;
  2738. attribute float lineDistance;
  2739. varying float vLineDistance;
  2740. #include <common>
  2741. #include <uv_pars_vertex>
  2742. #include <color_pars_vertex>
  2743. #include <fog_pars_vertex>
  2744. #include <morphtarget_pars_vertex>
  2745. #include <logdepthbuf_pars_vertex>
  2746. #include <clipping_planes_pars_vertex>
  2747. void main() {
  2748. vLineDistance = scale * lineDistance;
  2749. #include <uv_vertex>
  2750. #include <color_vertex>
  2751. #include <morphinstance_vertex>
  2752. #include <morphcolor_vertex>
  2753. #include <begin_vertex>
  2754. #include <morphtarget_vertex>
  2755. #include <project_vertex>
  2756. #include <logdepthbuf_vertex>
  2757. #include <clipping_planes_vertex>
  2758. #include <fog_vertex>
  2759. }`,tSe=`uniform vec3 diffuse;
  2760. uniform float opacity;
  2761. uniform float dashSize;
  2762. uniform float totalSize;
  2763. varying float vLineDistance;
  2764. #include <common>
  2765. #include <color_pars_fragment>
  2766. #include <uv_pars_fragment>
  2767. #include <map_pars_fragment>
  2768. #include <fog_pars_fragment>
  2769. #include <logdepthbuf_pars_fragment>
  2770. #include <clipping_planes_pars_fragment>
  2771. void main() {
  2772. vec4 diffuseColor = vec4( diffuse, opacity );
  2773. #include <clipping_planes_fragment>
  2774. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  2775. discard;
  2776. }
  2777. vec3 outgoingLight = vec3( 0.0 );
  2778. #include <logdepthbuf_fragment>
  2779. #include <map_fragment>
  2780. #include <color_fragment>
  2781. outgoingLight = diffuseColor.rgb;
  2782. #include <opaque_fragment>
  2783. #include <tonemapping_fragment>
  2784. #include <colorspace_fragment>
  2785. #include <fog_fragment>
  2786. #include <premultiplied_alpha_fragment>
  2787. }`,nSe=`#include <common>
  2788. #include <batching_pars_vertex>
  2789. #include <uv_pars_vertex>
  2790. #include <envmap_pars_vertex>
  2791. #include <color_pars_vertex>
  2792. #include <fog_pars_vertex>
  2793. #include <morphtarget_pars_vertex>
  2794. #include <skinning_pars_vertex>
  2795. #include <logdepthbuf_pars_vertex>
  2796. #include <clipping_planes_pars_vertex>
  2797. void main() {
  2798. #include <uv_vertex>
  2799. #include <color_vertex>
  2800. #include <morphinstance_vertex>
  2801. #include <morphcolor_vertex>
  2802. #include <batching_vertex>
  2803. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  2804. #include <beginnormal_vertex>
  2805. #include <morphnormal_vertex>
  2806. #include <skinbase_vertex>
  2807. #include <skinnormal_vertex>
  2808. #include <defaultnormal_vertex>
  2809. #endif
  2810. #include <begin_vertex>
  2811. #include <morphtarget_vertex>
  2812. #include <skinning_vertex>
  2813. #include <project_vertex>
  2814. #include <logdepthbuf_vertex>
  2815. #include <clipping_planes_vertex>
  2816. #include <worldpos_vertex>
  2817. #include <envmap_vertex>
  2818. #include <fog_vertex>
  2819. }`,rSe=`uniform vec3 diffuse;
  2820. uniform float opacity;
  2821. #ifndef FLAT_SHADED
  2822. varying vec3 vNormal;
  2823. #endif
  2824. #include <common>
  2825. #include <dithering_pars_fragment>
  2826. #include <color_pars_fragment>
  2827. #include <uv_pars_fragment>
  2828. #include <map_pars_fragment>
  2829. #include <alphamap_pars_fragment>
  2830. #include <alphatest_pars_fragment>
  2831. #include <alphahash_pars_fragment>
  2832. #include <aomap_pars_fragment>
  2833. #include <lightmap_pars_fragment>
  2834. #include <envmap_common_pars_fragment>
  2835. #include <envmap_pars_fragment>
  2836. #include <fog_pars_fragment>
  2837. #include <specularmap_pars_fragment>
  2838. #include <logdepthbuf_pars_fragment>
  2839. #include <clipping_planes_pars_fragment>
  2840. void main() {
  2841. vec4 diffuseColor = vec4( diffuse, opacity );
  2842. #include <clipping_planes_fragment>
  2843. #include <logdepthbuf_fragment>
  2844. #include <map_fragment>
  2845. #include <color_fragment>
  2846. #include <alphamap_fragment>
  2847. #include <alphatest_fragment>
  2848. #include <alphahash_fragment>
  2849. #include <specularmap_fragment>
  2850. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2851. #ifdef USE_LIGHTMAP
  2852. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  2853. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  2854. #else
  2855. reflectedLight.indirectDiffuse += vec3( 1.0 );
  2856. #endif
  2857. #include <aomap_fragment>
  2858. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  2859. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  2860. #include <envmap_fragment>
  2861. #include <opaque_fragment>
  2862. #include <tonemapping_fragment>
  2863. #include <colorspace_fragment>
  2864. #include <fog_fragment>
  2865. #include <premultiplied_alpha_fragment>
  2866. #include <dithering_fragment>
  2867. }`,aSe=`#define LAMBERT
  2868. varying vec3 vViewPosition;
  2869. #include <common>
  2870. #include <batching_pars_vertex>
  2871. #include <uv_pars_vertex>
  2872. #include <displacementmap_pars_vertex>
  2873. #include <envmap_pars_vertex>
  2874. #include <color_pars_vertex>
  2875. #include <fog_pars_vertex>
  2876. #include <normal_pars_vertex>
  2877. #include <morphtarget_pars_vertex>
  2878. #include <skinning_pars_vertex>
  2879. #include <shadowmap_pars_vertex>
  2880. #include <logdepthbuf_pars_vertex>
  2881. #include <clipping_planes_pars_vertex>
  2882. void main() {
  2883. #include <uv_vertex>
  2884. #include <color_vertex>
  2885. #include <morphinstance_vertex>
  2886. #include <morphcolor_vertex>
  2887. #include <batching_vertex>
  2888. #include <beginnormal_vertex>
  2889. #include <morphnormal_vertex>
  2890. #include <skinbase_vertex>
  2891. #include <skinnormal_vertex>
  2892. #include <defaultnormal_vertex>
  2893. #include <normal_vertex>
  2894. #include <begin_vertex>
  2895. #include <morphtarget_vertex>
  2896. #include <skinning_vertex>
  2897. #include <displacementmap_vertex>
  2898. #include <project_vertex>
  2899. #include <logdepthbuf_vertex>
  2900. #include <clipping_planes_vertex>
  2901. vViewPosition = - mvPosition.xyz;
  2902. #include <worldpos_vertex>
  2903. #include <envmap_vertex>
  2904. #include <shadowmap_vertex>
  2905. #include <fog_vertex>
  2906. }`,iSe=`#define LAMBERT
  2907. uniform vec3 diffuse;
  2908. uniform vec3 emissive;
  2909. uniform float opacity;
  2910. #include <common>
  2911. #include <packing>
  2912. #include <dithering_pars_fragment>
  2913. #include <color_pars_fragment>
  2914. #include <uv_pars_fragment>
  2915. #include <map_pars_fragment>
  2916. #include <alphamap_pars_fragment>
  2917. #include <alphatest_pars_fragment>
  2918. #include <alphahash_pars_fragment>
  2919. #include <aomap_pars_fragment>
  2920. #include <lightmap_pars_fragment>
  2921. #include <emissivemap_pars_fragment>
  2922. #include <envmap_common_pars_fragment>
  2923. #include <envmap_pars_fragment>
  2924. #include <fog_pars_fragment>
  2925. #include <bsdfs>
  2926. #include <lights_pars_begin>
  2927. #include <normal_pars_fragment>
  2928. #include <lights_lambert_pars_fragment>
  2929. #include <shadowmap_pars_fragment>
  2930. #include <bumpmap_pars_fragment>
  2931. #include <normalmap_pars_fragment>
  2932. #include <specularmap_pars_fragment>
  2933. #include <logdepthbuf_pars_fragment>
  2934. #include <clipping_planes_pars_fragment>
  2935. void main() {
  2936. vec4 diffuseColor = vec4( diffuse, opacity );
  2937. #include <clipping_planes_fragment>
  2938. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2939. vec3 totalEmissiveRadiance = emissive;
  2940. #include <logdepthbuf_fragment>
  2941. #include <map_fragment>
  2942. #include <color_fragment>
  2943. #include <alphamap_fragment>
  2944. #include <alphatest_fragment>
  2945. #include <alphahash_fragment>
  2946. #include <specularmap_fragment>
  2947. #include <normal_fragment_begin>
  2948. #include <normal_fragment_maps>
  2949. #include <emissivemap_fragment>
  2950. #include <lights_lambert_fragment>
  2951. #include <lights_fragment_begin>
  2952. #include <lights_fragment_maps>
  2953. #include <lights_fragment_end>
  2954. #include <aomap_fragment>
  2955. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  2956. #include <envmap_fragment>
  2957. #include <opaque_fragment>
  2958. #include <tonemapping_fragment>
  2959. #include <colorspace_fragment>
  2960. #include <fog_fragment>
  2961. #include <premultiplied_alpha_fragment>
  2962. #include <dithering_fragment>
  2963. }`,sSe=`#define MATCAP
  2964. varying vec3 vViewPosition;
  2965. #include <common>
  2966. #include <batching_pars_vertex>
  2967. #include <uv_pars_vertex>
  2968. #include <color_pars_vertex>
  2969. #include <displacementmap_pars_vertex>
  2970. #include <fog_pars_vertex>
  2971. #include <normal_pars_vertex>
  2972. #include <morphtarget_pars_vertex>
  2973. #include <skinning_pars_vertex>
  2974. #include <logdepthbuf_pars_vertex>
  2975. #include <clipping_planes_pars_vertex>
  2976. void main() {
  2977. #include <uv_vertex>
  2978. #include <color_vertex>
  2979. #include <morphinstance_vertex>
  2980. #include <morphcolor_vertex>
  2981. #include <batching_vertex>
  2982. #include <beginnormal_vertex>
  2983. #include <morphnormal_vertex>
  2984. #include <skinbase_vertex>
  2985. #include <skinnormal_vertex>
  2986. #include <defaultnormal_vertex>
  2987. #include <normal_vertex>
  2988. #include <begin_vertex>
  2989. #include <morphtarget_vertex>
  2990. #include <skinning_vertex>
  2991. #include <displacementmap_vertex>
  2992. #include <project_vertex>
  2993. #include <logdepthbuf_vertex>
  2994. #include <clipping_planes_vertex>
  2995. #include <fog_vertex>
  2996. vViewPosition = - mvPosition.xyz;
  2997. }`,oSe=`#define MATCAP
  2998. uniform vec3 diffuse;
  2999. uniform float opacity;
  3000. uniform sampler2D matcap;
  3001. varying vec3 vViewPosition;
  3002. #include <common>
  3003. #include <dithering_pars_fragment>
  3004. #include <color_pars_fragment>
  3005. #include <uv_pars_fragment>
  3006. #include <map_pars_fragment>
  3007. #include <alphamap_pars_fragment>
  3008. #include <alphatest_pars_fragment>
  3009. #include <alphahash_pars_fragment>
  3010. #include <fog_pars_fragment>
  3011. #include <normal_pars_fragment>
  3012. #include <bumpmap_pars_fragment>
  3013. #include <normalmap_pars_fragment>
  3014. #include <logdepthbuf_pars_fragment>
  3015. #include <clipping_planes_pars_fragment>
  3016. void main() {
  3017. vec4 diffuseColor = vec4( diffuse, opacity );
  3018. #include <clipping_planes_fragment>
  3019. #include <logdepthbuf_fragment>
  3020. #include <map_fragment>
  3021. #include <color_fragment>
  3022. #include <alphamap_fragment>
  3023. #include <alphatest_fragment>
  3024. #include <alphahash_fragment>
  3025. #include <normal_fragment_begin>
  3026. #include <normal_fragment_maps>
  3027. vec3 viewDir = normalize( vViewPosition );
  3028. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  3029. vec3 y = cross( viewDir, x );
  3030. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  3031. #ifdef USE_MATCAP
  3032. vec4 matcapColor = texture2D( matcap, uv );
  3033. #else
  3034. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  3035. #endif
  3036. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  3037. #include <opaque_fragment>
  3038. #include <tonemapping_fragment>
  3039. #include <colorspace_fragment>
  3040. #include <fog_fragment>
  3041. #include <premultiplied_alpha_fragment>
  3042. #include <dithering_fragment>
  3043. }`,lSe=`#define NORMAL
  3044. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3045. varying vec3 vViewPosition;
  3046. #endif
  3047. #include <common>
  3048. #include <batching_pars_vertex>
  3049. #include <uv_pars_vertex>
  3050. #include <displacementmap_pars_vertex>
  3051. #include <normal_pars_vertex>
  3052. #include <morphtarget_pars_vertex>
  3053. #include <skinning_pars_vertex>
  3054. #include <logdepthbuf_pars_vertex>
  3055. #include <clipping_planes_pars_vertex>
  3056. void main() {
  3057. #include <uv_vertex>
  3058. #include <batching_vertex>
  3059. #include <beginnormal_vertex>
  3060. #include <morphinstance_vertex>
  3061. #include <morphnormal_vertex>
  3062. #include <skinbase_vertex>
  3063. #include <skinnormal_vertex>
  3064. #include <defaultnormal_vertex>
  3065. #include <normal_vertex>
  3066. #include <begin_vertex>
  3067. #include <morphtarget_vertex>
  3068. #include <skinning_vertex>
  3069. #include <displacementmap_vertex>
  3070. #include <project_vertex>
  3071. #include <logdepthbuf_vertex>
  3072. #include <clipping_planes_vertex>
  3073. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3074. vViewPosition = - mvPosition.xyz;
  3075. #endif
  3076. }`,cSe=`#define NORMAL
  3077. uniform float opacity;
  3078. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3079. varying vec3 vViewPosition;
  3080. #endif
  3081. #include <packing>
  3082. #include <uv_pars_fragment>
  3083. #include <normal_pars_fragment>
  3084. #include <bumpmap_pars_fragment>
  3085. #include <normalmap_pars_fragment>
  3086. #include <logdepthbuf_pars_fragment>
  3087. #include <clipping_planes_pars_fragment>
  3088. void main() {
  3089. vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
  3090. #include <clipping_planes_fragment>
  3091. #include <logdepthbuf_fragment>
  3092. #include <normal_fragment_begin>
  3093. #include <normal_fragment_maps>
  3094. gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
  3095. #ifdef OPAQUE
  3096. gl_FragColor.a = 1.0;
  3097. #endif
  3098. }`,dSe=`#define PHONG
  3099. varying vec3 vViewPosition;
  3100. #include <common>
  3101. #include <batching_pars_vertex>
  3102. #include <uv_pars_vertex>
  3103. #include <displacementmap_pars_vertex>
  3104. #include <envmap_pars_vertex>
  3105. #include <color_pars_vertex>
  3106. #include <fog_pars_vertex>
  3107. #include <normal_pars_vertex>
  3108. #include <morphtarget_pars_vertex>
  3109. #include <skinning_pars_vertex>
  3110. #include <shadowmap_pars_vertex>
  3111. #include <logdepthbuf_pars_vertex>
  3112. #include <clipping_planes_pars_vertex>
  3113. void main() {
  3114. #include <uv_vertex>
  3115. #include <color_vertex>
  3116. #include <morphcolor_vertex>
  3117. #include <batching_vertex>
  3118. #include <beginnormal_vertex>
  3119. #include <morphinstance_vertex>
  3120. #include <morphnormal_vertex>
  3121. #include <skinbase_vertex>
  3122. #include <skinnormal_vertex>
  3123. #include <defaultnormal_vertex>
  3124. #include <normal_vertex>
  3125. #include <begin_vertex>
  3126. #include <morphtarget_vertex>
  3127. #include <skinning_vertex>
  3128. #include <displacementmap_vertex>
  3129. #include <project_vertex>
  3130. #include <logdepthbuf_vertex>
  3131. #include <clipping_planes_vertex>
  3132. vViewPosition = - mvPosition.xyz;
  3133. #include <worldpos_vertex>
  3134. #include <envmap_vertex>
  3135. #include <shadowmap_vertex>
  3136. #include <fog_vertex>
  3137. }`,uSe=`#define PHONG
  3138. uniform vec3 diffuse;
  3139. uniform vec3 emissive;
  3140. uniform vec3 specular;
  3141. uniform float shininess;
  3142. uniform float opacity;
  3143. #include <common>
  3144. #include <packing>
  3145. #include <dithering_pars_fragment>
  3146. #include <color_pars_fragment>
  3147. #include <uv_pars_fragment>
  3148. #include <map_pars_fragment>
  3149. #include <alphamap_pars_fragment>
  3150. #include <alphatest_pars_fragment>
  3151. #include <alphahash_pars_fragment>
  3152. #include <aomap_pars_fragment>
  3153. #include <lightmap_pars_fragment>
  3154. #include <emissivemap_pars_fragment>
  3155. #include <envmap_common_pars_fragment>
  3156. #include <envmap_pars_fragment>
  3157. #include <fog_pars_fragment>
  3158. #include <bsdfs>
  3159. #include <lights_pars_begin>
  3160. #include <normal_pars_fragment>
  3161. #include <lights_phong_pars_fragment>
  3162. #include <shadowmap_pars_fragment>
  3163. #include <bumpmap_pars_fragment>
  3164. #include <normalmap_pars_fragment>
  3165. #include <specularmap_pars_fragment>
  3166. #include <logdepthbuf_pars_fragment>
  3167. #include <clipping_planes_pars_fragment>
  3168. void main() {
  3169. vec4 diffuseColor = vec4( diffuse, opacity );
  3170. #include <clipping_planes_fragment>
  3171. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3172. vec3 totalEmissiveRadiance = emissive;
  3173. #include <logdepthbuf_fragment>
  3174. #include <map_fragment>
  3175. #include <color_fragment>
  3176. #include <alphamap_fragment>
  3177. #include <alphatest_fragment>
  3178. #include <alphahash_fragment>
  3179. #include <specularmap_fragment>
  3180. #include <normal_fragment_begin>
  3181. #include <normal_fragment_maps>
  3182. #include <emissivemap_fragment>
  3183. #include <lights_phong_fragment>
  3184. #include <lights_fragment_begin>
  3185. #include <lights_fragment_maps>
  3186. #include <lights_fragment_end>
  3187. #include <aomap_fragment>
  3188. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  3189. #include <envmap_fragment>
  3190. #include <opaque_fragment>
  3191. #include <tonemapping_fragment>
  3192. #include <colorspace_fragment>
  3193. #include <fog_fragment>
  3194. #include <premultiplied_alpha_fragment>
  3195. #include <dithering_fragment>
  3196. }`,mSe=`#define STANDARD
  3197. varying vec3 vViewPosition;
  3198. #ifdef USE_TRANSMISSION
  3199. varying vec3 vWorldPosition;
  3200. #endif
  3201. #include <common>
  3202. #include <batching_pars_vertex>
  3203. #include <uv_pars_vertex>
  3204. #include <displacementmap_pars_vertex>
  3205. #include <color_pars_vertex>
  3206. #include <fog_pars_vertex>
  3207. #include <normal_pars_vertex>
  3208. #include <morphtarget_pars_vertex>
  3209. #include <skinning_pars_vertex>
  3210. #include <shadowmap_pars_vertex>
  3211. #include <logdepthbuf_pars_vertex>
  3212. #include <clipping_planes_pars_vertex>
  3213. void main() {
  3214. #include <uv_vertex>
  3215. #include <color_vertex>
  3216. #include <morphinstance_vertex>
  3217. #include <morphcolor_vertex>
  3218. #include <batching_vertex>
  3219. #include <beginnormal_vertex>
  3220. #include <morphnormal_vertex>
  3221. #include <skinbase_vertex>
  3222. #include <skinnormal_vertex>
  3223. #include <defaultnormal_vertex>
  3224. #include <normal_vertex>
  3225. #include <begin_vertex>
  3226. #include <morphtarget_vertex>
  3227. #include <skinning_vertex>
  3228. #include <displacementmap_vertex>
  3229. #include <project_vertex>
  3230. #include <logdepthbuf_vertex>
  3231. #include <clipping_planes_vertex>
  3232. vViewPosition = - mvPosition.xyz;
  3233. #include <worldpos_vertex>
  3234. #include <shadowmap_vertex>
  3235. #include <fog_vertex>
  3236. #ifdef USE_TRANSMISSION
  3237. vWorldPosition = worldPosition.xyz;
  3238. #endif
  3239. }`,hSe=`#define STANDARD
  3240. #ifdef PHYSICAL
  3241. #define IOR
  3242. #define USE_SPECULAR
  3243. #endif
  3244. uniform vec3 diffuse;
  3245. uniform vec3 emissive;
  3246. uniform float roughness;
  3247. uniform float metalness;
  3248. uniform float opacity;
  3249. #ifdef IOR
  3250. uniform float ior;
  3251. #endif
  3252. #ifdef USE_SPECULAR
  3253. uniform float specularIntensity;
  3254. uniform vec3 specularColor;
  3255. #ifdef USE_SPECULAR_COLORMAP
  3256. uniform sampler2D specularColorMap;
  3257. #endif
  3258. #ifdef USE_SPECULAR_INTENSITYMAP
  3259. uniform sampler2D specularIntensityMap;
  3260. #endif
  3261. #endif
  3262. #ifdef USE_CLEARCOAT
  3263. uniform float clearcoat;
  3264. uniform float clearcoatRoughness;
  3265. #endif
  3266. #ifdef USE_DISPERSION
  3267. uniform float dispersion;
  3268. #endif
  3269. #ifdef USE_IRIDESCENCE
  3270. uniform float iridescence;
  3271. uniform float iridescenceIOR;
  3272. uniform float iridescenceThicknessMinimum;
  3273. uniform float iridescenceThicknessMaximum;
  3274. #endif
  3275. #ifdef USE_SHEEN
  3276. uniform vec3 sheenColor;
  3277. uniform float sheenRoughness;
  3278. #ifdef USE_SHEEN_COLORMAP
  3279. uniform sampler2D sheenColorMap;
  3280. #endif
  3281. #ifdef USE_SHEEN_ROUGHNESSMAP
  3282. uniform sampler2D sheenRoughnessMap;
  3283. #endif
  3284. #endif
  3285. #ifdef USE_ANISOTROPY
  3286. uniform vec2 anisotropyVector;
  3287. #ifdef USE_ANISOTROPYMAP
  3288. uniform sampler2D anisotropyMap;
  3289. #endif
  3290. #endif
  3291. varying vec3 vViewPosition;
  3292. #include <common>
  3293. #include <packing>
  3294. #include <dithering_pars_fragment>
  3295. #include <color_pars_fragment>
  3296. #include <uv_pars_fragment>
  3297. #include <map_pars_fragment>
  3298. #include <alphamap_pars_fragment>
  3299. #include <alphatest_pars_fragment>
  3300. #include <alphahash_pars_fragment>
  3301. #include <aomap_pars_fragment>
  3302. #include <lightmap_pars_fragment>
  3303. #include <emissivemap_pars_fragment>
  3304. #include <iridescence_fragment>
  3305. #include <cube_uv_reflection_fragment>
  3306. #include <envmap_common_pars_fragment>
  3307. #include <envmap_physical_pars_fragment>
  3308. #include <fog_pars_fragment>
  3309. #include <lights_pars_begin>
  3310. #include <normal_pars_fragment>
  3311. #include <lights_physical_pars_fragment>
  3312. #include <transmission_pars_fragment>
  3313. #include <shadowmap_pars_fragment>
  3314. #include <bumpmap_pars_fragment>
  3315. #include <normalmap_pars_fragment>
  3316. #include <clearcoat_pars_fragment>
  3317. #include <iridescence_pars_fragment>
  3318. #include <roughnessmap_pars_fragment>
  3319. #include <metalnessmap_pars_fragment>
  3320. #include <logdepthbuf_pars_fragment>
  3321. #include <clipping_planes_pars_fragment>
  3322. void main() {
  3323. vec4 diffuseColor = vec4( diffuse, opacity );
  3324. #include <clipping_planes_fragment>
  3325. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3326. vec3 totalEmissiveRadiance = emissive;
  3327. #include <logdepthbuf_fragment>
  3328. #include <map_fragment>
  3329. #include <color_fragment>
  3330. #include <alphamap_fragment>
  3331. #include <alphatest_fragment>
  3332. #include <alphahash_fragment>
  3333. #include <roughnessmap_fragment>
  3334. #include <metalnessmap_fragment>
  3335. #include <normal_fragment_begin>
  3336. #include <normal_fragment_maps>
  3337. #include <clearcoat_normal_fragment_begin>
  3338. #include <clearcoat_normal_fragment_maps>
  3339. #include <emissivemap_fragment>
  3340. #include <lights_physical_fragment>
  3341. #include <lights_fragment_begin>
  3342. #include <lights_fragment_maps>
  3343. #include <lights_fragment_end>
  3344. #include <aomap_fragment>
  3345. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  3346. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  3347. #include <transmission_fragment>
  3348. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  3349. #ifdef USE_SHEEN
  3350. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  3351. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  3352. #endif
  3353. #ifdef USE_CLEARCOAT
  3354. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  3355. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  3356. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  3357. #endif
  3358. #include <opaque_fragment>
  3359. #include <tonemapping_fragment>
  3360. #include <colorspace_fragment>
  3361. #include <fog_fragment>
  3362. #include <premultiplied_alpha_fragment>
  3363. #include <dithering_fragment>
  3364. }`,pSe=`#define TOON
  3365. varying vec3 vViewPosition;
  3366. #include <common>
  3367. #include <batching_pars_vertex>
  3368. #include <uv_pars_vertex>
  3369. #include <displacementmap_pars_vertex>
  3370. #include <color_pars_vertex>
  3371. #include <fog_pars_vertex>
  3372. #include <normal_pars_vertex>
  3373. #include <morphtarget_pars_vertex>
  3374. #include <skinning_pars_vertex>
  3375. #include <shadowmap_pars_vertex>
  3376. #include <logdepthbuf_pars_vertex>
  3377. #include <clipping_planes_pars_vertex>
  3378. void main() {
  3379. #include <uv_vertex>
  3380. #include <color_vertex>
  3381. #include <morphinstance_vertex>
  3382. #include <morphcolor_vertex>
  3383. #include <batching_vertex>
  3384. #include <beginnormal_vertex>
  3385. #include <morphnormal_vertex>
  3386. #include <skinbase_vertex>
  3387. #include <skinnormal_vertex>
  3388. #include <defaultnormal_vertex>
  3389. #include <normal_vertex>
  3390. #include <begin_vertex>
  3391. #include <morphtarget_vertex>
  3392. #include <skinning_vertex>
  3393. #include <displacementmap_vertex>
  3394. #include <project_vertex>
  3395. #include <logdepthbuf_vertex>
  3396. #include <clipping_planes_vertex>
  3397. vViewPosition = - mvPosition.xyz;
  3398. #include <worldpos_vertex>
  3399. #include <shadowmap_vertex>
  3400. #include <fog_vertex>
  3401. }`,fSe=`#define TOON
  3402. uniform vec3 diffuse;
  3403. uniform vec3 emissive;
  3404. uniform float opacity;
  3405. #include <common>
  3406. #include <packing>
  3407. #include <dithering_pars_fragment>
  3408. #include <color_pars_fragment>
  3409. #include <uv_pars_fragment>
  3410. #include <map_pars_fragment>
  3411. #include <alphamap_pars_fragment>
  3412. #include <alphatest_pars_fragment>
  3413. #include <alphahash_pars_fragment>
  3414. #include <aomap_pars_fragment>
  3415. #include <lightmap_pars_fragment>
  3416. #include <emissivemap_pars_fragment>
  3417. #include <gradientmap_pars_fragment>
  3418. #include <fog_pars_fragment>
  3419. #include <bsdfs>
  3420. #include <lights_pars_begin>
  3421. #include <normal_pars_fragment>
  3422. #include <lights_toon_pars_fragment>
  3423. #include <shadowmap_pars_fragment>
  3424. #include <bumpmap_pars_fragment>
  3425. #include <normalmap_pars_fragment>
  3426. #include <logdepthbuf_pars_fragment>
  3427. #include <clipping_planes_pars_fragment>
  3428. void main() {
  3429. vec4 diffuseColor = vec4( diffuse, opacity );
  3430. #include <clipping_planes_fragment>
  3431. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3432. vec3 totalEmissiveRadiance = emissive;
  3433. #include <logdepthbuf_fragment>
  3434. #include <map_fragment>
  3435. #include <color_fragment>
  3436. #include <alphamap_fragment>
  3437. #include <alphatest_fragment>
  3438. #include <alphahash_fragment>
  3439. #include <normal_fragment_begin>
  3440. #include <normal_fragment_maps>
  3441. #include <emissivemap_fragment>
  3442. #include <lights_toon_fragment>
  3443. #include <lights_fragment_begin>
  3444. #include <lights_fragment_maps>
  3445. #include <lights_fragment_end>
  3446. #include <aomap_fragment>
  3447. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  3448. #include <opaque_fragment>
  3449. #include <tonemapping_fragment>
  3450. #include <colorspace_fragment>
  3451. #include <fog_fragment>
  3452. #include <premultiplied_alpha_fragment>
  3453. #include <dithering_fragment>
  3454. }`,gSe=`uniform float size;
  3455. uniform float scale;
  3456. #include <common>
  3457. #include <color_pars_vertex>
  3458. #include <fog_pars_vertex>
  3459. #include <morphtarget_pars_vertex>
  3460. #include <logdepthbuf_pars_vertex>
  3461. #include <clipping_planes_pars_vertex>
  3462. #ifdef USE_POINTS_UV
  3463. varying vec2 vUv;
  3464. uniform mat3 uvTransform;
  3465. #endif
  3466. void main() {
  3467. #ifdef USE_POINTS_UV
  3468. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  3469. #endif
  3470. #include <color_vertex>
  3471. #include <morphinstance_vertex>
  3472. #include <morphcolor_vertex>
  3473. #include <begin_vertex>
  3474. #include <morphtarget_vertex>
  3475. #include <project_vertex>
  3476. gl_PointSize = size;
  3477. #ifdef USE_SIZEATTENUATION
  3478. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3479. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  3480. #endif
  3481. #include <logdepthbuf_vertex>
  3482. #include <clipping_planes_vertex>
  3483. #include <worldpos_vertex>
  3484. #include <fog_vertex>
  3485. }`,bSe=`uniform vec3 diffuse;
  3486. uniform float opacity;
  3487. #include <common>
  3488. #include <color_pars_fragment>
  3489. #include <map_particle_pars_fragment>
  3490. #include <alphatest_pars_fragment>
  3491. #include <alphahash_pars_fragment>
  3492. #include <fog_pars_fragment>
  3493. #include <logdepthbuf_pars_fragment>
  3494. #include <clipping_planes_pars_fragment>
  3495. void main() {
  3496. vec4 diffuseColor = vec4( diffuse, opacity );
  3497. #include <clipping_planes_fragment>
  3498. vec3 outgoingLight = vec3( 0.0 );
  3499. #include <logdepthbuf_fragment>
  3500. #include <map_particle_fragment>
  3501. #include <color_fragment>
  3502. #include <alphatest_fragment>
  3503. #include <alphahash_fragment>
  3504. outgoingLight = diffuseColor.rgb;
  3505. #include <opaque_fragment>
  3506. #include <tonemapping_fragment>
  3507. #include <colorspace_fragment>
  3508. #include <fog_fragment>
  3509. #include <premultiplied_alpha_fragment>
  3510. }`,xSe=`#include <common>
  3511. #include <batching_pars_vertex>
  3512. #include <fog_pars_vertex>
  3513. #include <morphtarget_pars_vertex>
  3514. #include <skinning_pars_vertex>
  3515. #include <logdepthbuf_pars_vertex>
  3516. #include <shadowmap_pars_vertex>
  3517. void main() {
  3518. #include <batching_vertex>
  3519. #include <beginnormal_vertex>
  3520. #include <morphinstance_vertex>
  3521. #include <morphnormal_vertex>
  3522. #include <skinbase_vertex>
  3523. #include <skinnormal_vertex>
  3524. #include <defaultnormal_vertex>
  3525. #include <begin_vertex>
  3526. #include <morphtarget_vertex>
  3527. #include <skinning_vertex>
  3528. #include <project_vertex>
  3529. #include <logdepthbuf_vertex>
  3530. #include <worldpos_vertex>
  3531. #include <shadowmap_vertex>
  3532. #include <fog_vertex>
  3533. }`,ySe=`uniform vec3 color;
  3534. uniform float opacity;
  3535. #include <common>
  3536. #include <packing>
  3537. #include <fog_pars_fragment>
  3538. #include <bsdfs>
  3539. #include <lights_pars_begin>
  3540. #include <logdepthbuf_pars_fragment>
  3541. #include <shadowmap_pars_fragment>
  3542. #include <shadowmask_pars_fragment>
  3543. void main() {
  3544. #include <logdepthbuf_fragment>
  3545. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  3546. #include <tonemapping_fragment>
  3547. #include <colorspace_fragment>
  3548. #include <fog_fragment>
  3549. }`,vSe=`uniform float rotation;
  3550. uniform vec2 center;
  3551. #include <common>
  3552. #include <uv_pars_vertex>
  3553. #include <fog_pars_vertex>
  3554. #include <logdepthbuf_pars_vertex>
  3555. #include <clipping_planes_pars_vertex>
  3556. void main() {
  3557. #include <uv_vertex>
  3558. vec4 mvPosition = modelViewMatrix[ 3 ];
  3559. vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
  3560. #ifndef USE_SIZEATTENUATION
  3561. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3562. if ( isPerspective ) scale *= - mvPosition.z;
  3563. #endif
  3564. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  3565. vec2 rotatedPosition;
  3566. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  3567. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  3568. mvPosition.xy += rotatedPosition;
  3569. gl_Position = projectionMatrix * mvPosition;
  3570. #include <logdepthbuf_vertex>
  3571. #include <clipping_planes_vertex>
  3572. #include <fog_vertex>
  3573. }`,wSe=`uniform vec3 diffuse;
  3574. uniform float opacity;
  3575. #include <common>
  3576. #include <uv_pars_fragment>
  3577. #include <map_pars_fragment>
  3578. #include <alphamap_pars_fragment>
  3579. #include <alphatest_pars_fragment>
  3580. #include <alphahash_pars_fragment>
  3581. #include <fog_pars_fragment>
  3582. #include <logdepthbuf_pars_fragment>
  3583. #include <clipping_planes_pars_fragment>
  3584. void main() {
  3585. vec4 diffuseColor = vec4( diffuse, opacity );
  3586. #include <clipping_planes_fragment>
  3587. vec3 outgoingLight = vec3( 0.0 );
  3588. #include <logdepthbuf_fragment>
  3589. #include <map_fragment>
  3590. #include <alphamap_fragment>
  3591. #include <alphatest_fragment>
  3592. #include <alphahash_fragment>
  3593. outgoingLight = diffuseColor.rgb;
  3594. #include <opaque_fragment>
  3595. #include <tonemapping_fragment>
  3596. #include <colorspace_fragment>
  3597. #include <fog_fragment>
  3598. }`,Jn={alphahash_fragment:qve,alphahash_pars_fragment:$ve,alphamap_fragment:Vve,alphamap_pars_fragment:Gve,alphatest_fragment:Wve,alphatest_pars_fragment:Kve,aomap_fragment:Yve,aomap_pars_fragment:Xve,batching_pars_vertex:Qve,batching_vertex:Zve,begin_vertex:Jve,beginnormal_vertex:e0e,bsdfs:t0e,iridescence_fragment:n0e,bumpmap_pars_fragment:r0e,clipping_planes_fragment:a0e,clipping_planes_pars_fragment:i0e,clipping_planes_pars_vertex:s0e,clipping_planes_vertex:o0e,color_fragment:l0e,color_pars_fragment:c0e,color_pars_vertex:d0e,color_vertex:u0e,common:m0e,cube_uv_reflection_fragment:h0e,defaultnormal_vertex:p0e,displacementmap_pars_vertex:f0e,displacementmap_vertex:g0e,emissivemap_fragment:b0e,emissivemap_pars_fragment:x0e,colorspace_fragment:y0e,colorspace_pars_fragment:v0e,envmap_fragment:w0e,envmap_common_pars_fragment:S0e,envmap_pars_fragment:_0e,envmap_pars_vertex:k0e,envmap_physical_pars_fragment:R0e,envmap_vertex:N0e,fog_vertex:C0e,fog_pars_vertex:P0e,fog_fragment:T0e,fog_pars_fragment:A0e,gradientmap_pars_fragment:M0e,lightmap_pars_fragment:j0e,lights_lambert_fragment:E0e,lights_lambert_pars_fragment:D0e,lights_pars_begin:F0e,lights_toon_fragment:L0e,lights_toon_pars_fragment:O0e,lights_phong_fragment:I0e,lights_phong_pars_fragment:z0e,lights_physical_fragment:U0e,lights_physical_pars_fragment:B0e,lights_fragment_begin:H0e,lights_fragment_maps:q0e,lights_fragment_end:$0e,logdepthbuf_fragment:V0e,logdepthbuf_pars_fragment:G0e,logdepthbuf_pars_vertex:W0e,logdepthbuf_vertex:K0e,map_fragment:Y0e,map_pars_fragment:X0e,map_particle_fragment:Q0e,map_particle_pars_fragment:Z0e,metalnessmap_fragment:J0e,metalnessmap_pars_fragment:ewe,morphinstance_vertex:twe,morphcolor_vertex:nwe,morphnormal_vertex:rwe,morphtarget_pars_vertex:awe,morphtarget_vertex:iwe,normal_fragment_begin:swe,normal_fragment_maps:owe,normal_pars_fragment:lwe,normal_pars_vertex:cwe,normal_vertex:dwe,normalmap_pars_fragment:uwe,clearcoat_normal_fragment_begin:mwe,clearcoat_normal_fragment_maps:hwe,clearcoat_pars_fragment:pwe,iridescence_pars_fragment:fwe,opaque_fragment:gwe,packing:bwe,premultiplied_alpha_fragment:xwe,project_vertex:ywe,dithering_fragment:vwe,dithering_pars_fragment:wwe,roughnessmap_fragment:Swe,roughnessmap_pars_fragment:_we,shadowmap_pars_fragment:kwe,shadowmap_pars_vertex:Nwe,shadowmap_vertex:Cwe,shadowmask_pars_fragment:Pwe,skinbase_vertex:Twe,skinning_pars_vertex:Awe,skinning_vertex:Mwe,skinnormal_vertex:jwe,specularmap_fragment:Ewe,specularmap_pars_fragment:Dwe,tonemapping_fragment:Fwe,tonemapping_pars_fragment:Rwe,transmission_fragment:Lwe,transmission_pars_fragment:Owe,uv_pars_fragment:Iwe,uv_pars_vertex:zwe,uv_vertex:Uwe,worldpos_vertex:Bwe,background_vert:Hwe,background_frag:qwe,backgroundCube_vert:$we,backgroundCube_frag:Vwe,cube_vert:Gwe,cube_frag:Wwe,depth_vert:Kwe,depth_frag:Ywe,distanceRGBA_vert:Xwe,distanceRGBA_frag:Qwe,equirect_vert:Zwe,equirect_frag:Jwe,linedashed_vert:eSe,linedashed_frag:tSe,meshbasic_vert:nSe,meshbasic_frag:rSe,meshlambert_vert:aSe,meshlambert_frag:iSe,meshmatcap_vert:sSe,meshmatcap_frag:oSe,meshnormal_vert:lSe,meshnormal_frag:cSe,meshphong_vert:dSe,meshphong_frag:uSe,meshphysical_vert:mSe,meshphysical_frag:hSe,meshtoon_vert:pSe,meshtoon_frag:fSe,points_vert:gSe,points_frag:bSe,shadow_vert:xSe,shadow_frag:ySe,sprite_vert:vSe,sprite_frag:wSe},nn={common:{diffuse:{value:new sr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ir},alphaMap:{value:null},alphaMapTransform:{value:new ir},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ir}},envmap:{envMap:{value:null},envMapRotation:{value:new ir},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 ir}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ir}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ir},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ir},normalScale:{value:new tr(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ir},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ir}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ir}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ir}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new sr(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 sr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ir},alphaTest:{value:0},uvTransform:{value:new ir}},sprite:{diffuse:{value:new sr(16777215)},opacity:{value:1},center:{value:new tr(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ir},alphaMap:{value:null},alphaMapTransform:{value:new ir},alphaTest:{value:0}}},cd={basic:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.fog]),vertexShader:Jn.meshbasic_vert,fragmentShader:Jn.meshbasic_frag},lambert:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,nn.lights,{emissive:{value:new sr(0)}}]),vertexShader:Jn.meshlambert_vert,fragmentShader:Jn.meshlambert_frag},phong:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,nn.lights,{emissive:{value:new sr(0)},specular:{value:new sr(1118481)},shininess:{value:30}}]),vertexShader:Jn.meshphong_vert,fragmentShader:Jn.meshphong_frag},standard:{uniforms:Vs([nn.common,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.roughnessmap,nn.metalnessmap,nn.fog,nn.lights,{emissive:{value:new sr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Jn.meshphysical_vert,fragmentShader:Jn.meshphysical_frag},toon:{uniforms:Vs([nn.common,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.gradientmap,nn.fog,nn.lights,{emissive:{value:new sr(0)}}]),vertexShader:Jn.meshtoon_vert,fragmentShader:Jn.meshtoon_frag},matcap:{uniforms:Vs([nn.common,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,{matcap:{value:null}}]),vertexShader:Jn.meshmatcap_vert,fragmentShader:Jn.meshmatcap_frag},points:{uniforms:Vs([nn.points,nn.fog]),vertexShader:Jn.points_vert,fragmentShader:Jn.points_frag},dashed:{uniforms:Vs([nn.common,nn.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Jn.linedashed_vert,fragmentShader:Jn.linedashed_frag},depth:{uniforms:Vs([nn.common,nn.displacementmap]),vertexShader:Jn.depth_vert,fragmentShader:Jn.depth_frag},normal:{uniforms:Vs([nn.common,nn.bumpmap,nn.normalmap,nn.displacementmap,{opacity:{value:1}}]),vertexShader:Jn.meshnormal_vert,fragmentShader:Jn.meshnormal_frag},sprite:{uniforms:Vs([nn.sprite,nn.fog]),vertexShader:Jn.sprite_vert,fragmentShader:Jn.sprite_frag},background:{uniforms:{uvTransform:{value:new ir},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Jn.background_vert,fragmentShader:Jn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ir}},vertexShader:Jn.backgroundCube_vert,fragmentShader:Jn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Jn.cube_vert,fragmentShader:Jn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Jn.equirect_vert,fragmentShader:Jn.equirect_frag},distanceRGBA:{uniforms:Vs([nn.common,nn.displacementmap,{referencePosition:{value:new At},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Jn.distanceRGBA_vert,fragmentShader:Jn.distanceRGBA_frag},shadow:{uniforms:Vs([nn.lights,nn.fog,{color:{value:new sr(0)},opacity:{value:1}}]),vertexShader:Jn.shadow_vert,fragmentShader:Jn.shadow_frag}};cd.physical={uniforms:Vs([cd.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ir},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ir},clearcoatNormalScale:{value:new tr(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ir},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ir},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ir},sheen:{value:0},sheenColor:{value:new sr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ir},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ir},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ir},transmissionSamplerSize:{value:new tr},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ir},attenuationDistance:{value:0},attenuationColor:{value:new sr(0)},specularColor:{value:new sr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ir},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ir},anisotropyVector:{value:new tr},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ir}}]),vertexShader:Jn.meshphysical_vert,fragmentShader:Jn.meshphysical_frag};const X_={r:0,b:0,g:0},Rp=new Vh,SSe=new ci;function _Se(t,e,n,r,i,s,o){const l=new sr(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function y(k){let P=k.isScene===!0?k.background:null;return P&&P.isTexture&&(P=(k.backgroundBlurriness>0?n:e).get(P)),P}function v(k){let P=!1;const N=y(k);N===null?g(l,c):N&&N.isColor&&(g(N,1),P=!0);const M=t.xr.getEnvironmentBlendMode();M==="additive"?r.buffers.color.setClear(0,0,0,1,o):M==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||P)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function b(k,P){const N=y(P);N&&(N.isCubeTexture||N.mapping===AP)?(u===void 0&&(u=new Zl(new DO(1,1,1),new Xu({name:"BackgroundCubeMaterial",uniforms:Px(cd.backgroundCube.uniforms),vertexShader:cd.backgroundCube.vertexShader,fragmentShader:cd.backgroundCube.fragmentShader,side:Co,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(M,A,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Rp.copy(P.backgroundRotation),Rp.x*=-1,Rp.y*=-1,Rp.z*=-1,N.isCubeTexture&&N.isRenderTargetTexture===!1&&(Rp.y*=-1,Rp.z*=-1),u.material.uniforms.envMap.value=N,u.material.uniforms.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=P.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(SSe.makeRotationFromEuler(Rp)),u.material.toneMapped=Cr.getTransfer(N.colorSpace)!==Hr,(m!==N||p!==N.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),u.layers.enableAll(),k.unshift(u,u.geometry,u.material,0,0,null)):N&&N.isTexture&&(d===void 0&&(d=new Zl(new RO(2,2),new Xu({name:"BackgroundMaterial",uniforms:Px(cd.background.uniforms),vertexShader:cd.background.vertexShader,fragmentShader:cd.background.fragmentShader,side:$h,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),Object.defineProperty(d.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(d)),d.material.uniforms.t2D.value=N,d.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,d.material.toneMapped=Cr.getTransfer(N.colorSpace)!==Hr,N.matrixAutoUpdate===!0&&N.updateMatrix(),d.material.uniforms.uvTransform.value.copy(N.matrix),(m!==N||p!==N.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),d.layers.enableAll(),k.unshift(d,d.geometry,d.material,0,0,null))}function g(k,P){k.getRGB(X_,iZ(t)),r.buffers.color.setClear(X_.r,X_.g,X_.b,P,o)}function _(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0)}return{getClearColor:function(){return l},setClearColor:function(k,P=1){l.set(k),c=P,g(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(k){c=k,g(l,c)},render:v,addToRenderList:b,dispose:_}}function kSe(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r={},i=p(null);let s=i,o=!1;function l(F,$,I,X,L){let te=!1;const ae=m(X,I,$);s!==ae&&(s=ae,d(s.object)),te=f(F,X,I,L),te&&y(F,X,I,L),L!==null&&e.update(L,t.ELEMENT_ARRAY_BUFFER),(te||o)&&(o=!1,P(F,$,I,X),L!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(L).buffer))}function c(){return t.createVertexArray()}function d(F){return t.bindVertexArray(F)}function u(F){return t.deleteVertexArray(F)}function m(F,$,I){const X=I.wireframe===!0;let L=r[F.id];L===void 0&&(L={},r[F.id]=L);let te=L[$.id];te===void 0&&(te={},L[$.id]=te);let ae=te[X];return ae===void 0&&(ae=p(c()),te[X]=ae),ae}function p(F){const $=[],I=[],X=[];for(let L=0;L<n;L++)$[L]=0,I[L]=0,X[L]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:$,enabledAttributes:I,attributeDivisors:X,object:F,attributes:{},index:null}}function f(F,$,I,X){const L=s.attributes,te=$.attributes;let ae=0;const ee=I.getAttributes();for(const me in ee)if(ee[me].location>=0){const ue=L[me];let K=te[me];if(K===void 0&&(me==="instanceMatrix"&&F.instanceMatrix&&(K=F.instanceMatrix),me==="instanceColor"&&F.instanceColor&&(K=F.instanceColor)),ue===void 0||ue.attribute!==K||K&&ue.data!==K.data)return!0;ae++}return s.attributesNum!==ae||s.index!==X}function y(F,$,I,X){const L={},te=$.attributes;let ae=0;const ee=I.getAttributes();for(const me in ee)if(ee[me].location>=0){let ue=te[me];ue===void 0&&(me==="instanceMatrix"&&F.instanceMatrix&&(ue=F.instanceMatrix),me==="instanceColor"&&F.instanceColor&&(ue=F.instanceColor));const K={};K.attribute=ue,ue&&ue.data&&(K.data=ue.data),L[me]=K,ae++}s.attributes=L,s.attributesNum=ae,s.index=X}function v(){const F=s.newAttributes;for(let $=0,I=F.length;$<I;$++)F[$]=0}function b(F){g(F,0)}function g(F,$){const I=s.newAttributes,X=s.enabledAttributes,L=s.attributeDivisors;I[F]=1,X[F]===0&&(t.enableVertexAttribArray(F),X[F]=1),L[F]!==$&&(t.vertexAttribDivisor(F,$),L[F]=$)}function _(){const F=s.newAttributes,$=s.enabledAttributes;for(let I=0,X=$.length;I<X;I++)$[I]!==F[I]&&(t.disableVertexAttribArray(I),$[I]=0)}function k(F,$,I,X,L,te,ae){ae===!0?t.vertexAttribIPointer(F,$,I,L,te):t.vertexAttribPointer(F,$,I,X,L,te)}function P(F,$,I,X){v();const L=X.attributes,te=I.getAttributes(),ae=$.defaultAttributeValues;for(const ee in te){const me=te[ee];if(me.location>=0){let le=L[ee];if(le===void 0&&(ee==="instanceMatrix"&&F.instanceMatrix&&(le=F.instanceMatrix),ee==="instanceColor"&&F.instanceColor&&(le=F.instanceColor)),le!==void 0){const ue=le.normalized,K=le.itemSize,ne=e.get(le);if(ne===void 0)continue;const oe=ne.buffer,be=ne.type,_e=ne.bytesPerElement,B=be===t.INT||be===t.UNSIGNED_INT||le.gpuType===_O;if(le.isInterleavedBufferAttribute){const Y=le.data,D=Y.stride,j=le.offset;if(Y.isInstancedInterleavedBuffer){for(let z=0;z<me.locationSize;z++)g(me.location+z,Y.meshPerAttribute);F.isInstancedMesh!==!0&&X._maxInstanceCount===void 0&&(X._maxInstanceCount=Y.meshPerAttribute*Y.count)}else for(let z=0;z<me.locationSize;z++)b(me.location+z);t.bindBuffer(t.ARRAY_BUFFER,oe);for(let z=0;z<me.locationSize;z++)k(me.location+z,K/me.locationSize,be,ue,D*_e,(j+K/me.locationSize*z)*_e,B)}else{if(le.isInstancedBufferAttribute){for(let Y=0;Y<me.locationSize;Y++)g(me.location+Y,le.meshPerAttribute);F.isInstancedMesh!==!0&&X._maxInstanceCount===void 0&&(X._maxInstanceCount=le.meshPerAttribute*le.count)}else for(let Y=0;Y<me.locationSize;Y++)b(me.location+Y);t.bindBuffer(t.ARRAY_BUFFER,oe);for(let Y=0;Y<me.locationSize;Y++)k(me.location+Y,K/me.locationSize,be,ue,K*_e,K/me.locationSize*Y*_e,B)}}else if(ae!==void 0){const ue=ae[ee];if(ue!==void 0)switch(ue.length){case 2:t.vertexAttrib2fv(me.location,ue);break;case 3:t.vertexAttrib3fv(me.location,ue);break;case 4:t.vertexAttrib4fv(me.location,ue);break;default:t.vertexAttrib1fv(me.location,ue)}}}}_()}function N(){T();for(const F in r){const $=r[F];for(const I in $){const X=$[I];for(const L in X)u(X[L].object),delete X[L];delete $[I]}delete r[F]}}function M(F){if(r[F.id]===void 0)return;const $=r[F.id];for(const I in $){const X=$[I];for(const L in X)u(X[L].object),delete X[L];delete $[I]}delete r[F.id]}function A(F){for(const $ in r){const I=r[$];if(I[F.id]===void 0)continue;const X=I[F.id];for(const L in X)u(X[L].object),delete X[L];delete I[F.id]}}function T(){C(),o=!0,s!==i&&(s=i,d(s.object))}function C(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:l,reset:T,resetDefaultState:C,dispose:N,releaseStatesOfGeometry:M,releaseStatesOfProgram:A,initAttributes:v,enableAttribute:b,disableUnusedAttributes:_}}function NSe(t,e,n){let r;function i(d){r=d}function s(d,u){t.drawArrays(r,d,u),n.update(u,r,1)}function o(d,u,m){m!==0&&(t.drawArraysInstanced(r,d,u,m),n.update(u,r,m))}function l(d,u,m){if(m===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r,d,0,u,0,m);let f=0;for(let y=0;y<m;y++)f+=u[y];n.update(f,r,1)}function c(d,u,m,p){if(m===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let y=0;y<d.length;y++)o(d[y],u[y],p[y]);else{f.multiDrawArraysInstancedWEBGL(r,d,0,u,0,p,0,m);let y=0;for(let v=0;v<m;v++)y+=u[v]*p[v];n.update(y,r,1)}}this.setMode=i,this.render=s,this.renderInstances=o,this.renderMultiDraw=l,this.renderMultiDrawInstances=c}function CSe(t,e,n,r){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!==Tc&&r.convert(A)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function l(A){const T=A===ry&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(A!==Cd&&r.convert(A)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==Mu&&!T)}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&&(Un("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),y=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=t.getParameter(t.MAX_TEXTURE_SIZE),b=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),g=t.getParameter(t.MAX_VERTEX_ATTRIBS),_=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),k=t.getParameter(t.MAX_VARYING_VECTORS),P=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=y>0,M=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:y,maxTextureSize:v,maxCubemapSize:b,maxAttributes:g,maxVertexUniforms:_,maxVaryings:k,maxFragmentUniforms:P,vertexTextures:N,maxSamples:M}}function PSe(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new rh,l=new ir,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(m,p){const f=m.length!==0||p||r!==0||i;return i=p,r=m.length,f},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=u(m,p,0)},this.setState=function(m,p,f){const y=m.clippingPlanes,v=m.clipIntersection,b=m.clipShadows,g=t.get(m);if(!i||y===null||y.length===0||s&&!b)s?u(null):d();else{const _=s?0:r,k=_*4;let P=g.clippingState||null;c.value=P,P=u(y,p,k,f);for(let N=0;N!==k;++N)P[N]=n[N];g.clippingState=P,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(m,p,f,y){const v=m!==null?m.length:0;let b=null;if(v!==0){if(b=c.value,y!==!0||b===null){const g=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(b===null||b.length<g)&&(b=new Float32Array(g));for(let k=0,P=f;k!==v;++k,P+=4)o.copy(m[k]).applyMatrix4(_,l),o.normal.toArray(b,P),b[P+3]=o.constant}c.value=b,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,b}}function TSe(t){let e=new WeakMap;function n(o,l){return l===aF?o.mapping=kx:l===iF&&(o.mapping=Nx),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===aF||l===iF)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 vve(c.height);return d.fromEquirectangularTexture(t,o),e.set(o,d),o.addEventListener("dispose",i),n(d.texture,o.mapping)}else return null}}return o}function i(o){const l=o.target;l.removeEventListener("dispose",i);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}const yh=4,nH=[.125,.215,.35,.446,.526,.582],Jp=20,ASe=256,xv=new pZ,rH=new sr;let Uj=null,Bj=0,Hj=0,qj=!1;const MSe=new At;let aH=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,n=0,r=.1,i=100,s={}){const{size:o=256,position:l=MSe}=s;Uj=this._renderer.getRenderTarget(),Bj=this._renderer.getActiveCubeFace(),Hj=this._renderer.getActiveMipmapLevel(),qj=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,r,i,c,l),n>0&&this._blur(c,0,0,n),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=oH(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=sH(),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(Uj,Bj,Hj),this._renderer.xr.enabled=qj,e.scissorTest=!1,db(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===kx||e.mapping===Nx?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Uj=this._renderer.getRenderTarget(),Bj=this._renderer.getActiveCubeFace(),Hj=this._renderer.getActiveMipmapLevel(),qj=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const r=n||this._allocateTargets();return this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,r={magFilter:Bl,minFilter:Bl,generateMipmaps:!1,type:ry,format:Tc,colorSpace:Cx,depthBuffer:!1},i=iH(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=iH(e,n,r);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=jSe(s)),this._blurMaterial=DSe(s,e,n),this._ggxMaterial=ESe(s,e,n)}return i}_compileMaterial(e){const n=new Zl(new Ql,e);this._renderer.compile(n,xv)}_sceneToCubeUV(e,n,r,i,s){const c=new Rl(90,1,n,r),d=[1,-1,1,1,1,1],u=[1,1,1,-1,-1,-1],m=this._renderer,p=m.autoClear,f=m.toneMapping;m.getClearColor(rH),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 Zl(new DO,new EO({name:"PMREM.Background",side:Co,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,b=v.material;let g=!1;const _=e.background;_?_.isColor&&(b.color.copy(_),e.background=null,g=!0):(b.color.copy(rH),g=!0);for(let k=0;k<6;k++){const P=k%3;P===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)):P===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 N=this._cubeSize;db(i,P*N,k>2?N:0,N,N),m.setRenderTarget(i),g&&m.render(v,c),m.render(e,c)}m.toneMapping=f,m.autoClear=p,e.background=_}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===kx||e.mapping===Nx;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=oH()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=sH());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;db(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,xv)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;s<i;s++)this._applyGGXFilter(e,s-1,s);n.autoClear=r}_applyGGXFilter(e,n,r){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,l=this._lodMeshes[r];l.material=o;const c=o.uniforms,d=r/(this._lodMeshes.length-1),u=n/(this._lodMeshes.length-1),m=Math.sqrt(d*d-u*u),p=.05+d*.95,f=m*p,{_lodMax:y}=this,v=this._sizeLods[r],b=3*v*(r>y-yh?r-y+yh:0),g=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=y-n,db(s,b,g,3*v,2*v),i.setRenderTarget(s),i.render(l,xv),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=y-r,db(e,b,g,3*v,2*v),i.setRenderTarget(e),i.render(l,xv)}_blur(e,n,r,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,i,"latitudinal",s),this._halfBlur(o,e,r,r,i,"longitudinal",s)}_halfBlur(e,n,r,i,s,o,l){const c=this._renderer,d=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&Xa("blur direction must be either latitudinal or longitudinal!");const u=3,m=this._lodMeshes[i];m.material=d;const p=d.uniforms,f=this._sizeLods[r]-1,y=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Jp-1),v=s/y,b=isFinite(s)?1+Math.floor(u*v):Jp;b>Jp&&Un(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Jp}`);const g=[];let _=0;for(let A=0;A<Jp;++A){const T=A/v,C=Math.exp(-T*T/2);g.push(C),A===0?_+=C:A<b&&(_+=2*C)}for(let A=0;A<g.length;A++)g[A]=g[A]/_;p.envMap.value=e.texture,p.samples.value=b,p.weights.value=g,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:k}=this;p.dTheta.value=y,p.mipInt.value=k-r;const P=this._sizeLods[i],N=3*P*(i>k-yh?i-k+yh:0),M=4*(this._cubeSize-P);db(n,N,M,3*P,2*P),c.setRenderTarget(n),c.render(m,xv)}};function jSe(t){const e=[],n=[],r=[];let i=t;const s=t-yh+1+nH.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);e.push(l);let c=1/l;o>t-yh?c=nH[o-t+yh-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,y=6,v=3,b=2,g=1,_=new Float32Array(v*y*f),k=new Float32Array(b*y*f),P=new Float32Array(g*y*f);for(let M=0;M<f;M++){const A=M%3*2/3-1,T=M>2?0:-1,C=[A,T,0,A+2/3,T,0,A+2/3,T+1,0,A,T,0,A+2/3,T+1,0,A,T+1,0];_.set(C,v*y*M),k.set(p,b*y*M);const F=[M,M,M,M,M,M];P.set(F,g*y*M)}const N=new Ql;N.setAttribute("position",new Zs(_,v)),N.setAttribute("uv",new Zs(k,b)),N.setAttribute("faceIndex",new Zs(P,g)),r.push(new Zl(N,null)),i>yh&&i--}return{lodMeshes:r,sizeLods:e,sigmas:n}}function iH(t,e,n){const r=new $f(t,e,n);return r.texture.mapping=AP,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function db(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function ESe(t,e,n){return new Xu({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:ASe,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:jP(),fragmentShader:`
  3599. precision highp float;
  3600. precision highp int;
  3601. varying vec3 vOutputDirection;
  3602. uniform sampler2D envMap;
  3603. uniform float roughness;
  3604. uniform float mipInt;
  3605. #define ENVMAP_TYPE_CUBE_UV
  3606. #include <cube_uv_reflection_fragment>
  3607. #define PI 3.14159265359
  3608. // Van der Corput radical inverse
  3609. float radicalInverse_VdC(uint bits) {
  3610. bits = (bits << 16u) | (bits >> 16u);
  3611. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  3612. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  3613. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  3614. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  3615. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  3616. }
  3617. // Hammersley sequence
  3618. vec2 hammersley(uint i, uint N) {
  3619. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  3620. }
  3621. // GGX VNDF importance sampling (Eric Heitz 2018)
  3622. // "Sampling the GGX Distribution of Visible Normals"
  3623. // https://jcgt.org/published/0007/04/01/
  3624. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  3625. float alpha = roughness * roughness;
  3626. // Section 3.2: Transform view direction to hemisphere configuration
  3627. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  3628. // Section 4.1: Orthonormal basis
  3629. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  3630. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  3631. vec3 T2 = cross(Vh, T1);
  3632. // Section 4.2: Parameterization of projected area
  3633. float r = sqrt(Xi.x);
  3634. float phi = 2.0 * PI * Xi.y;
  3635. float t1 = r * cos(phi);
  3636. float t2 = r * sin(phi);
  3637. float s = 0.5 * (1.0 + Vh.z);
  3638. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  3639. // Section 4.3: Reprojection onto hemisphere
  3640. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  3641. // Section 3.4: Transform back to ellipsoid configuration
  3642. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  3643. }
  3644. void main() {
  3645. vec3 N = normalize(vOutputDirection);
  3646. vec3 V = N; // Assume view direction equals normal for pre-filtering
  3647. vec3 prefilteredColor = vec3(0.0);
  3648. float totalWeight = 0.0;
  3649. // For very low roughness, just sample the environment directly
  3650. if (roughness < 0.001) {
  3651. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  3652. return;
  3653. }
  3654. // Tangent space basis for VNDF sampling
  3655. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  3656. vec3 tangent = normalize(cross(up, N));
  3657. vec3 bitangent = cross(N, tangent);
  3658. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  3659. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  3660. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  3661. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  3662. // Transform H back to world space
  3663. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  3664. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  3665. float NdotL = max(dot(N, L), 0.0);
  3666. if(NdotL > 0.0) {
  3667. // Sample environment at fixed mip level
  3668. // VNDF importance sampling handles the distribution filtering
  3669. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  3670. // Weight by NdotL for the split-sum approximation
  3671. // VNDF PDF naturally accounts for the visible microfacet distribution
  3672. prefilteredColor += sampleColor * NdotL;
  3673. totalWeight += NdotL;
  3674. }
  3675. }
  3676. if (totalWeight > 0.0) {
  3677. prefilteredColor = prefilteredColor / totalWeight;
  3678. }
  3679. gl_FragColor = vec4(prefilteredColor, 1.0);
  3680. }
  3681. `,blending:Ou,depthTest:!1,depthWrite:!1})}function DSe(t,e,n){const r=new Float32Array(Jp),i=new At(0,1,0);return new Xu({name:"SphericalGaussianBlur",defines:{n:Jp,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:jP(),fragmentShader:`
  3682. precision mediump float;
  3683. precision mediump int;
  3684. varying vec3 vOutputDirection;
  3685. uniform sampler2D envMap;
  3686. uniform int samples;
  3687. uniform float weights[ n ];
  3688. uniform bool latitudinal;
  3689. uniform float dTheta;
  3690. uniform float mipInt;
  3691. uniform vec3 poleAxis;
  3692. #define ENVMAP_TYPE_CUBE_UV
  3693. #include <cube_uv_reflection_fragment>
  3694. vec3 getSample( float theta, vec3 axis ) {
  3695. float cosTheta = cos( theta );
  3696. // Rodrigues' axis-angle rotation
  3697. vec3 sampleDirection = vOutputDirection * cosTheta
  3698. + cross( axis, vOutputDirection ) * sin( theta )
  3699. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  3700. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  3701. }
  3702. void main() {
  3703. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  3704. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  3705. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  3706. }
  3707. axis = normalize( axis );
  3708. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  3709. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  3710. for ( int i = 1; i < n; i++ ) {
  3711. if ( i >= samples ) {
  3712. break;
  3713. }
  3714. float theta = dTheta * float( i );
  3715. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  3716. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  3717. }
  3718. }
  3719. `,blending:Ou,depthTest:!1,depthWrite:!1})}function sH(){return new Xu({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:jP(),fragmentShader:`
  3720. precision mediump float;
  3721. precision mediump int;
  3722. varying vec3 vOutputDirection;
  3723. uniform sampler2D envMap;
  3724. #include <common>
  3725. void main() {
  3726. vec3 outputDirection = normalize( vOutputDirection );
  3727. vec2 uv = equirectUv( outputDirection );
  3728. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  3729. }
  3730. `,blending:Ou,depthTest:!1,depthWrite:!1})}function oH(){return new Xu({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:jP(),fragmentShader:`
  3731. precision mediump float;
  3732. precision mediump int;
  3733. uniform float flipEnvMap;
  3734. varying vec3 vOutputDirection;
  3735. uniform samplerCube envMap;
  3736. void main() {
  3737. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  3738. }
  3739. `,blending:Ou,depthTest:!1,depthWrite:!1})}function jP(){return`
  3740. precision mediump float;
  3741. precision mediump int;
  3742. attribute float faceIndex;
  3743. varying vec3 vOutputDirection;
  3744. // RH coordinate system; PMREM face-indexing convention
  3745. vec3 getDirection( vec2 uv, float face ) {
  3746. uv = 2.0 * uv - 1.0;
  3747. vec3 direction = vec3( uv, 1.0 );
  3748. if ( face == 0.0 ) {
  3749. direction = direction.zyx; // ( 1, v, u ) pos x
  3750. } else if ( face == 1.0 ) {
  3751. direction = direction.xzy;
  3752. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  3753. } else if ( face == 2.0 ) {
  3754. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  3755. } else if ( face == 3.0 ) {
  3756. direction = direction.zyx;
  3757. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  3758. } else if ( face == 4.0 ) {
  3759. direction = direction.xzy;
  3760. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  3761. } else if ( face == 5.0 ) {
  3762. direction.z *= -1.0; // ( u, v, -1 ) neg z
  3763. }
  3764. return direction;
  3765. }
  3766. void main() {
  3767. vOutputDirection = getDirection( uv, faceIndex );
  3768. gl_Position = vec4( position, 1.0 );
  3769. }
  3770. `}function FSe(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,d=c===aF||c===iF,u=c===kx||c===Nx;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 aH(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 aH(t)),m=d?n.fromEquirectangular(l):n.fromCubemap(l),m.texture.pmremVersion=l.pmremVersion,e.set(l,m),l.addEventListener("dispose",s),m.texture):null}}}return l}function i(l){let c=0;const d=6;for(let u=0;u<d;u++)l[u]!==void 0&&c++;return c===d}function s(l){const c=l.target;c.removeEventListener("dispose",s);const d=e.get(c);d!==void 0&&(e.delete(c),d.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function RSe(t){const e={};function n(r){if(e[r]!==void 0)return e[r];const i=t.getExtension(r);return e[r]=i,i}return{has:function(r){return n(r)!==null},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(r){const i=n(r);return i===null&&H0("WebGLRenderer: "+r+" extension not supported."),i}}}function LSe(t,e,n,r){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const y in p.attributes)e.remove(p.attributes[y]);p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),r.releaseStatesOfGeometry(p),p.isInstancedBufferGeometry===!0&&delete p._maxInstanceCount,n.memory.geometries--}function l(m,p){return i[p.id]===!0||(p.addEventListener("dispose",o),i[p.id]=!0,n.memory.geometries++),p}function c(m){const p=m.attributes;for(const f in p)e.update(p[f],t.ARRAY_BUFFER)}function d(m){const p=[],f=m.index,y=m.attributes.position;let v=0;if(f!==null){const _=f.array;v=f.version;for(let k=0,P=_.length;k<P;k+=3){const N=_[k+0],M=_[k+1],A=_[k+2];p.push(N,M,M,A,A,N)}}else if(y!==void 0){const _=y.array;v=y.version;for(let k=0,P=_.length/3-1;k<P;k+=3){const N=k+0,M=k+1,A=k+2;p.push(N,M,M,A,A,N)}}else return;const b=new(GQ(p)?nZ:tZ)(p,1);b.version=v;const g=s.get(m);g&&e.remove(g),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 OSe(t,e,n){let r;function i(p){r=p}let s,o;function l(p){s=p.type,o=p.bytesPerElement}function c(p,f){t.drawElements(r,f,s,p*o),n.update(f,r,1)}function d(p,f,y){y!==0&&(t.drawElementsInstanced(r,f,s,p*o,y),n.update(f,r,y))}function u(p,f,y){if(y===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r,f,0,s,p,0,y);let b=0;for(let g=0;g<y;g++)b+=f[g];n.update(b,r,1)}function m(p,f,y,v){if(y===0)return;const b=e.get("WEBGL_multi_draw");if(b===null)for(let g=0;g<p.length;g++)d(p[g]/o,f[g],v[g]);else{b.multiDrawElementsInstancedWEBGL(r,f,0,s,p,0,v,0,y);let g=0;for(let _=0;_<y;_++)g+=f[_]*v[_];n.update(g,r,1)}}this.setMode=i,this.setIndex=l,this.render=c,this.renderInstances=d,this.renderMultiDraw=u,this.renderMultiDrawInstances=m}function ISe(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(s,o,l){switch(n.calls++,o){case t.TRIANGLES:n.triangles+=l*(s/3);break;case t.LINES:n.lines+=l*(s/2);break;case t.LINE_STRIP:n.lines+=l*(s-1);break;case t.LINE_LOOP:n.lines+=l*s;break;case t.POINTS:n.points+=l*s;break;default:Xa("WebGLInfo: Unknown draw mode:",o);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:i,update:r}}function zSe(t,e,n){const r=new WeakMap,i=new ii;function s(o,l,c){const d=o.morphTargetInfluences,u=l.morphAttributes.position||l.morphAttributes.normal||l.morphAttributes.color,m=u!==void 0?u.length:0;let p=r.get(l);if(p===void 0||p.count!==m){let F=function(){T.dispose(),r.delete(l),l.removeEventListener("dispose",F)};var f=F;p!==void 0&&p.texture.dispose();const y=l.morphAttributes.position!==void 0,v=l.morphAttributes.normal!==void 0,b=l.morphAttributes.color!==void 0,g=l.morphAttributes.position||[],_=l.morphAttributes.normal||[],k=l.morphAttributes.color||[];let P=0;y===!0&&(P=1),v===!0&&(P=2),b===!0&&(P=3);let N=l.attributes.position.count*P,M=1;N>e.maxTextureSize&&(M=Math.ceil(N/e.maxTextureSize),N=e.maxTextureSize);const A=new Float32Array(N*M*4*m),T=new QQ(A,N,M,m);T.type=Mu,T.needsUpdate=!0;const C=P*4;for(let $=0;$<m;$++){const I=g[$],X=_[$],L=k[$],te=N*M*4*$;for(let ae=0;ae<I.count;ae++){const ee=ae*C;y===!0&&(i.fromBufferAttribute(I,ae),A[te+ee+0]=i.x,A[te+ee+1]=i.y,A[te+ee+2]=i.z,A[te+ee+3]=0),v===!0&&(i.fromBufferAttribute(X,ae),A[te+ee+4]=i.x,A[te+ee+5]=i.y,A[te+ee+6]=i.z,A[te+ee+7]=0),b===!0&&(i.fromBufferAttribute(L,ae),A[te+ee+8]=i.x,A[te+ee+9]=i.y,A[te+ee+10]=i.z,A[te+ee+11]=L.itemSize===4?i.w:1)}}p={count:m,texture:T,size:new tr(N,M)},r.set(l,p),l.addEventListener("dispose",F)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(t,"morphTexture",o.morphTexture,n);else{let y=0;for(let b=0;b<d.length;b++)y+=d[b];const v=l.morphTargetsRelative?1:1-y;c.getUniforms().setValue(t,"morphTargetBaseInfluence",v),c.getUniforms().setValue(t,"morphTargetInfluences",d)}c.getUniforms().setValue(t,"morphTargetsTexture",p.texture,n),c.getUniforms().setValue(t,"morphTargetsTextureSize",p.size)}return{update:s}}function USe(t,e,n,r){let i=new WeakMap;function s(c){const d=r.render.frame,u=c.geometry,m=e.get(c,u);if(i.get(m)!==d&&(e.update(m),i.set(m,d)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),i.get(c)!==d&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),i.set(c,d))),c.isSkinnedMesh){const p=c.skeleton;i.get(p)!==d&&(p.update(),i.set(p,d))}return m}function o(){i=new WeakMap}function l(c){const d=c.target;d.removeEventListener("dispose",l),n.remove(d.instanceMatrix),d.instanceColor!==null&&n.remove(d.instanceColor)}return{update:s,dispose:o}}const gZ=new zc,lH=new cZ(1,1),bZ=new QQ,xZ=new rve,yZ=new oZ,cH=[],dH=[],uH=new Float32Array(16),mH=new Float32Array(9),hH=new Float32Array(4);function iy(t,e,n){const r=t[0];if(r<=0||r>0)return t;const i=e*n;let s=cH[i];if(s===void 0&&(s=new Float32Array(i),cH[i]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function bi(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n<r;n++)if(t[n]!==e[n])return!1;return!0}function xi(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function EP(t,e){let n=dH[e];n===void 0&&(n=new Int32Array(e),dH[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function BSe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function HSe(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),xi(n,e)}}function qSe(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),xi(n,e)}}function $Se(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),xi(n,e)}}function VSe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(bi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),xi(n,e)}else{if(bi(n,r))return;hH.set(r),t.uniformMatrix2fv(this.addr,!1,hH),xi(n,r)}}function GSe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(bi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),xi(n,e)}else{if(bi(n,r))return;mH.set(r),t.uniformMatrix3fv(this.addr,!1,mH),xi(n,r)}}function WSe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(bi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),xi(n,e)}else{if(bi(n,r))return;uH.set(r),t.uniformMatrix4fv(this.addr,!1,uH),xi(n,r)}}function KSe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function YSe(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),xi(n,e)}}function XSe(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),xi(n,e)}}function QSe(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),xi(n,e)}}function ZSe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function JSe(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),xi(n,e)}}function e_e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3ui(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(bi(n,e))return;t.uniform3uiv(this.addr,e),xi(n,e)}}function t_e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(bi(n,e))return;t.uniform4uiv(this.addr,e),xi(n,e)}}function n_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i);let s;this.type===t.SAMPLER_2D_SHADOW?(lH.compareFunction=VQ,s=lH):s=gZ,n.setTexture2D(e||s,i)}function r_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(e||xZ,i)}function a_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(e||yZ,i)}function i_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(e||bZ,i)}function s_e(t){switch(t){case 5126:return BSe;case 35664:return HSe;case 35665:return qSe;case 35666:return $Se;case 35674:return VSe;case 35675:return GSe;case 35676:return WSe;case 5124:case 35670:return KSe;case 35667:case 35671:return YSe;case 35668:case 35672:return XSe;case 35669:case 35673:return QSe;case 5125:return ZSe;case 36294:return JSe;case 36295:return e_e;case 36296:return t_e;case 35678:case 36198:case 36298:case 36306:case 35682:return n_e;case 35679:case 36299:case 36307:return r_e;case 35680:case 36300:case 36308:case 36293:return a_e;case 36289:case 36303:case 36311:case 36292:return i_e}}function o_e(t,e){t.uniform1fv(this.addr,e)}function l_e(t,e){const n=iy(e,this.size,2);t.uniform2fv(this.addr,n)}function c_e(t,e){const n=iy(e,this.size,3);t.uniform3fv(this.addr,n)}function d_e(t,e){const n=iy(e,this.size,4);t.uniform4fv(this.addr,n)}function u_e(t,e){const n=iy(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function m_e(t,e){const n=iy(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function h_e(t,e){const n=iy(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function p_e(t,e){t.uniform1iv(this.addr,e)}function f_e(t,e){t.uniform2iv(this.addr,e)}function g_e(t,e){t.uniform3iv(this.addr,e)}function b_e(t,e){t.uniform4iv(this.addr,e)}function x_e(t,e){t.uniform1uiv(this.addr,e)}function y_e(t,e){t.uniform2uiv(this.addr,e)}function v_e(t,e){t.uniform3uiv(this.addr,e)}function w_e(t,e){t.uniform4uiv(this.addr,e)}function S_e(t,e,n){const r=this.cache,i=e.length,s=EP(n,i);bi(r,s)||(t.uniform1iv(this.addr,s),xi(r,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||gZ,s[o])}function __e(t,e,n){const r=this.cache,i=e.length,s=EP(n,i);bi(r,s)||(t.uniform1iv(this.addr,s),xi(r,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||xZ,s[o])}function k_e(t,e,n){const r=this.cache,i=e.length,s=EP(n,i);bi(r,s)||(t.uniform1iv(this.addr,s),xi(r,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||yZ,s[o])}function N_e(t,e,n){const r=this.cache,i=e.length,s=EP(n,i);bi(r,s)||(t.uniform1iv(this.addr,s),xi(r,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||bZ,s[o])}function C_e(t){switch(t){case 5126:return o_e;case 35664:return l_e;case 35665:return c_e;case 35666:return d_e;case 35674:return u_e;case 35675:return m_e;case 35676:return h_e;case 5124:case 35670:return p_e;case 35667:case 35671:return f_e;case 35668:case 35672:return g_e;case 35669:case 35673:return b_e;case 5125:return x_e;case 36294:return y_e;case 36295:return v_e;case 36296:return w_e;case 35678:case 36198:case 36298:case 36306:case 35682:return S_e;case 35679:case 36299:case 36307:return __e;case 35680:case 36300:case 36308:case 36293:return k_e;case 36289:case 36303:case 36311:case 36292:return N_e}}let P_e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=s_e(n.type)}},T_e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=C_e(n.type)}},A_e=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],r)}}};const $j=/(\w+)(\])?(\[|\.)?/g;function pH(t,e){t.seq.push(e),t.map[e.id]=e}function M_e(t,e,n){const r=t.name,i=r.length;for($j.lastIndex=0;;){const s=$j.exec(r),o=$j.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){pH(n,d===void 0?new P_e(l,t,e):new T_e(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new A_e(l),pH(n,m)),n=m}}}let Pk=class{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<r;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);M_e(s,o,this)}}setValue(e,n,r,i){const s=this.map[n];s!==void 0&&s.setValue(e,r,i)}setOptional(e,n,r){const i=n[r];i!==void 0&&this.setValue(e,r,i)}static upload(e,n,r,i){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=r[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,i)}}static seqWithValue(e,n){const r=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&r.push(o)}return r}};function fH(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const j_e=37297;let E_e=0;function D_e(t,e){const n=t.split(`
  3771. `),r=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
  3772. `)}const gH=new ir;function F_e(t){Cr._getMatrix(gH,Cr.workingColorSpace,t);const e=`mat3( ${gH.elements.map(n=>n.toFixed(4))} )`;switch(Cr.getTransfer(t)){case lN:return[e,"LinearTransferOETF"];case Hr:return[e,"sRGBTransferOETF"];default:return Un("WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function bH(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),s=(t.getShaderInfoLog(e)||"").trim();if(r&&s==="")return"";const o=/ERROR: 0:(\d+)/.exec(s);if(o){const l=parseInt(o[1]);return n.toUpperCase()+`
  3773. `+s+`
  3774. `+D_e(t.getShaderSource(e),l)}else return s}function R_e(t,e){const n=F_e(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`
  3775. `)}function L_e(t,e){let n;switch(e){case Mye:n="Linear";break;case jye:n="Reinhard";break;case Eye:n="Cineon";break;case Dye:n="ACESFilmic";break;case Rye:n="AgX";break;case Lye:n="Neutral";break;case Fye:n="Custom";break;default:Un("WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const Q_=new At;function O_e(){Cr.getLuminanceCoefficients(Q_);const t=Q_.x.toFixed(4),e=Q_.y.toFixed(4),n=Q_.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(`
  3776. `)}function I_e(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter($v).join(`
  3777. `)}function z_e(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
  3778. `)}function U_e(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){const s=t.getActiveAttrib(e,i),o=s.name;let l=1;s.type===t.FLOAT_MAT2&&(l=2),s.type===t.FLOAT_MAT3&&(l=3),s.type===t.FLOAT_MAT4&&(l=4),n[o]={type:s.type,location:t.getAttribLocation(e,o),locationSize:l}}return n}function $v(t){return t!==""}function xH(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 yH(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const B_e=/^[ \t]*#include +<([\w\d./]+)>/gm;function IF(t){return t.replace(B_e,q_e)}const H_e=new Map;function q_e(t,e){let n=Jn[e];if(n===void 0){const r=H_e.get(e);if(r!==void 0)n=Jn[r],Un('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return IF(n)}const $_e=/#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 vH(t){return t.replace($_e,V_e)}function V_e(t,e,n,r){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function wH(t){let e=`precision ${t.precision} float;
  3779. precision ${t.precision} int;
  3780. precision ${t.precision} sampler2D;
  3781. precision ${t.precision} samplerCube;
  3782. precision ${t.precision} sampler3D;
  3783. precision ${t.precision} sampler2DArray;
  3784. precision ${t.precision} sampler2DShadow;
  3785. precision ${t.precision} samplerCubeShadow;
  3786. precision ${t.precision} sampler2DArrayShadow;
  3787. precision ${t.precision} isampler2D;
  3788. precision ${t.precision} isampler3D;
  3789. precision ${t.precision} isamplerCube;
  3790. precision ${t.precision} isampler2DArray;
  3791. precision ${t.precision} usampler2D;
  3792. precision ${t.precision} usampler3D;
  3793. precision ${t.precision} usamplerCube;
  3794. precision ${t.precision} usampler2DArray;
  3795. `;return t.precision==="highp"?e+=`
  3796. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  3797. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  3798. #define LOW_PRECISION`),e}function G_e(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===RQ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===cye?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===bu&&(e="SHADOWMAP_TYPE_VSM"),e}function W_e(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case kx:case Nx:e="ENVMAP_TYPE_CUBE";break;case AP:e="ENVMAP_TYPE_CUBE_UV";break}return e}function K_e(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===Nx&&(e="ENVMAP_MODE_REFRACTION"),e}function Y_e(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case SO:e="ENVMAP_BLENDING_MULTIPLY";break;case Tye:e="ENVMAP_BLENDING_MIX";break;case Aye:e="ENVMAP_BLENDING_ADD";break}return e}function X_e(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:r,maxMip:n}}function Q_e(t,e,n,r){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=G_e(n),d=W_e(n),u=K_e(n),m=Y_e(n),p=X_e(n),f=I_e(n),y=z_e(s),v=i.createProgram();let b,g,_=n.glslVersion?"#version "+n.glslVersion+`
  3799. `:"";n.isRawShaderMaterial?(b=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y].filter($v).join(`
  3800. `),b.length>0&&(b+=`
  3801. `),g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y].filter($v).join(`
  3802. `),g.length>0&&(g+=`
  3803. `)):(b=[wH(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y,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",`
  3804. `].filter($v).join(`
  3805. `),g=[wH(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y,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?Jn.tonemapping_pars_fragment:"",n.toneMapping!==Dh?L_e("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Jn.colorspace_pars_fragment,R_e("linearToOutputTexel",n.outputColorSpace),O_e(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  3806. `].filter($v).join(`
  3807. `)),o=IF(o),o=xH(o,n),o=yH(o,n),l=IF(l),l=xH(l,n),l=yH(l,n),o=vH(o),l=vH(l),n.isRawShaderMaterial!==!0&&(_=`#version 300 es
  3808. `,b=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
  3809. `)+`
  3810. `+b,g=["#define varying in",n.glslVersion===P6?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===P6?"":"#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(`
  3811. `)+`
  3812. `+g);const k=_+b+o,P=_+g+l,N=fH(i,i.VERTEX_SHADER,k),M=fH(i,i.FRAGMENT_SHADER,P);i.attachShader(v,N),i.attachShader(v,M),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function A($){if(t.debug.checkShaderErrors){const I=i.getProgramInfoLog(v)||"",X=i.getShaderInfoLog(N)||"",L=i.getShaderInfoLog(M)||"",te=I.trim(),ae=X.trim(),ee=L.trim();let me=!0,le=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(me=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,M);else{const ue=bH(i,N,"vertex"),K=bH(i,M,"fragment");Xa("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+`
  3813. Material Name: `+$.name+`
  3814. Material Type: `+$.type+`
  3815. Program Info Log: `+te+`
  3816. `+ue+`
  3817. `+K)}else te!==""?Un("WebGLProgram: Program Info Log:",te):(ae===""||ee==="")&&(le=!1);le&&($.diagnostics={runnable:me,programLog:te,vertexShader:{log:ae,prefix:b},fragmentShader:{log:ee,prefix:g}})}i.deleteShader(N),i.deleteShader(M),T=new Pk(i,v),C=U_e(i,v)}let T;this.getUniforms=function(){return T===void 0&&A(this),T};let C;this.getAttributes=function(){return C===void 0&&A(this),C};let F=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return F===!1&&(F=i.getProgramParameter(v,j_e)),F},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=E_e++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=M,this}let Z_e=0,J_e=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new e1e(e),n.set(e,r)),r}},e1e=class{constructor(e){this.id=Z_e++,this.code=e,this.usedTimes=0}};function t1e(t,e,n,r,i,s,o){const l=new JQ,c=new J_e,d=new Set,u=[],m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.precision;const y={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(C){return d.add(C),C===0?"uv":`uv${C}`}function b(C,F,$,I,X){const L=I.fog,te=X.geometry,ae=C.isMeshStandardMaterial?I.environment:null,ee=(C.isMeshStandardMaterial?n:e).get(C.envMap||ae),me=ee&&ee.mapping===AP?ee.image.height:null,le=y[C.type];C.precision!==null&&(f=i.getMaxPrecision(C.precision),f!==C.precision&&Un("WebGLProgram.getParameters:",C.precision,"not supported, using",f,"instead."));const ue=te.morphAttributes.position||te.morphAttributes.normal||te.morphAttributes.color,K=ue!==void 0?ue.length:0;let ne=0;te.morphAttributes.position!==void 0&&(ne=1),te.morphAttributes.normal!==void 0&&(ne=2),te.morphAttributes.color!==void 0&&(ne=3);let oe,be,_e,B;if(le){const ut=cd[le];oe=ut.vertexShader,be=ut.fragmentShader}else oe=C.vertexShader,be=C.fragmentShader,c.update(C),_e=c.getVertexShaderID(C),B=c.getFragmentShaderID(C);const Y=t.getRenderTarget(),D=t.state.buffers.depth.getReversed(),j=X.isInstancedMesh===!0,z=X.isBatchedMesh===!0,W=!!C.map,q=!!C.matcap,de=!!ee,O=!!C.aoMap,G=!!C.lightMap,Q=!!C.bumpMap,V=!!C.normalMap,J=!!C.displacementMap,ie=!!C.emissiveMap,he=!!C.metalnessMap,fe=!!C.roughnessMap,se=C.anisotropy>0,U=C.clearcoat>0,R=C.dispersion>0,re=C.iridescence>0,xe=C.sheen>0,we=C.transmission>0,ye=se&&!!C.anisotropyMap,Ae=U&&!!C.clearcoatMap,ve=U&&!!C.clearcoatNormalMap,Te=U&&!!C.clearcoatRoughnessMap,Fe=re&&!!C.iridescenceMap,Ee=re&&!!C.iridescenceThicknessMap,Se=xe&&!!C.sheenColorMap,je=xe&&!!C.sheenRoughnessMap,qe=!!C.specularMap,Re=!!C.specularColorMap,Ye=!!C.specularIntensityMap,ce=we&&!!C.transmissionMap,ze=we&&!!C.thicknessMap,Ne=!!C.gradientMap,Ge=!!C.alphaMap,$e=C.alphaTest>0,Pe=!!C.alphaHash,Me=!!C.extensions;let Ve=Dh;C.toneMapped&&(Y===null||Y.isXRRenderTarget===!0)&&(Ve=t.toneMapping);const tt={shaderID:le,shaderType:C.type,shaderName:C.name,vertexShader:oe,fragmentShader:be,defines:C.defines,customVertexShaderID:_e,customFragmentShaderID:B,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:f,batching:z,batchingColor:z&&X._colorsTexture!==null,instancing:j,instancingColor:j&&X.instanceColor!==null,instancingMorph:j&&X.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:Y===null?t.outputColorSpace:Y.isXRRenderTarget===!0?Y.texture.colorSpace:Cx,alphaToCoverage:!!C.alphaToCoverage,map:W,matcap:q,envMap:de,envMapMode:de&&ee.mapping,envMapCubeUVHeight:me,aoMap:O,lightMap:G,bumpMap:Q,normalMap:V,displacementMap:p&&J,emissiveMap:ie,normalMapObjectSpace:V&&C.normalMapType===Uye,normalMapTangentSpace:V&&C.normalMapType===$Q,metalnessMap:he,roughnessMap:fe,anisotropy:se,anisotropyMap:ye,clearcoat:U,clearcoatMap:Ae,clearcoatNormalMap:ve,clearcoatRoughnessMap:Te,dispersion:R,iridescence:re,iridescenceMap:Fe,iridescenceThicknessMap:Ee,sheen:xe,sheenColorMap:Se,sheenRoughnessMap:je,specularMap:qe,specularColorMap:Re,specularIntensityMap:Ye,transmission:we,transmissionMap:ce,thicknessMap:ze,gradientMap:Ne,opaque:C.transparent===!1&&C.blending===ax&&C.alphaToCoverage===!1,alphaMap:Ge,alphaTest:$e,alphaHash:Pe,combine:C.combine,mapUv:W&&v(C.map.channel),aoMapUv:O&&v(C.aoMap.channel),lightMapUv:G&&v(C.lightMap.channel),bumpMapUv:Q&&v(C.bumpMap.channel),normalMapUv:V&&v(C.normalMap.channel),displacementMapUv:J&&v(C.displacementMap.channel),emissiveMapUv:ie&&v(C.emissiveMap.channel),metalnessMapUv:he&&v(C.metalnessMap.channel),roughnessMapUv:fe&&v(C.roughnessMap.channel),anisotropyMapUv:ye&&v(C.anisotropyMap.channel),clearcoatMapUv:Ae&&v(C.clearcoatMap.channel),clearcoatNormalMapUv:ve&&v(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Te&&v(C.clearcoatRoughnessMap.channel),iridescenceMapUv:Fe&&v(C.iridescenceMap.channel),iridescenceThicknessMapUv:Ee&&v(C.iridescenceThicknessMap.channel),sheenColorMapUv:Se&&v(C.sheenColorMap.channel),sheenRoughnessMapUv:je&&v(C.sheenRoughnessMap.channel),specularMapUv:qe&&v(C.specularMap.channel),specularColorMapUv:Re&&v(C.specularColorMap.channel),specularIntensityMapUv:Ye&&v(C.specularIntensityMap.channel),transmissionMapUv:ce&&v(C.transmissionMap.channel),thicknessMapUv:ze&&v(C.thicknessMap.channel),alphaMapUv:Ge&&v(C.alphaMap.channel),vertexTangents:!!te.attributes.tangent&&(V||se),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!te.attributes.color&&te.attributes.color.itemSize===4,pointsUvs:X.isPoints===!0&&!!te.attributes.uv&&(W||Ge),fog:!!L,useFog:C.fog===!0,fogExp2:!!L&&L.isFogExp2,flatShading:C.flatShading===!0&&C.wireframe===!1,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:m,reversedDepthBuffer:D,skinning:X.isSkinnedMesh===!0,morphTargets:te.morphAttributes.position!==void 0,morphNormals:te.morphAttributes.normal!==void 0,morphColors:te.morphAttributes.color!==void 0,morphTargetsCount:K,morphTextureStride:ne,numDirLights:F.directional.length,numPointLights:F.point.length,numSpotLights:F.spot.length,numSpotLightMaps:F.spotLightMap.length,numRectAreaLights:F.rectArea.length,numHemiLights:F.hemi.length,numDirLightShadows:F.directionalShadowMap.length,numPointLightShadows:F.pointShadowMap.length,numSpotLightShadows:F.spotShadowMap.length,numSpotLightShadowsWithMaps:F.numSpotLightShadowsWithMaps,numLightProbes:F.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:C.dithering,shadowMapEnabled:t.shadowMap.enabled&&$.length>0,shadowMapType:t.shadowMap.type,toneMapping:Ve,decodeVideoTexture:W&&C.map.isVideoTexture===!0&&Cr.getTransfer(C.map.colorSpace)===Hr,decodeVideoTextureEmissive:ie&&C.emissiveMap.isVideoTexture===!0&&Cr.getTransfer(C.emissiveMap.colorSpace)===Hr,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===ud,flipSided:C.side===Co,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:Me&&C.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Me&&C.extensions.multiDraw===!0||z)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return tt.vertexUv1s=d.has(1),tt.vertexUv2s=d.has(2),tt.vertexUv3s=d.has(3),d.clear(),tt}function g(C){const F=[];if(C.shaderID?F.push(C.shaderID):(F.push(C.customVertexShaderID),F.push(C.customFragmentShaderID)),C.defines!==void 0)for(const $ in C.defines)F.push($),F.push(C.defines[$]);return C.isRawShaderMaterial===!1&&(_(F,C),k(F,C),F.push(t.outputColorSpace)),F.push(C.customProgramCacheKey),F.join()}function _(C,F){C.push(F.precision),C.push(F.outputColorSpace),C.push(F.envMapMode),C.push(F.envMapCubeUVHeight),C.push(F.mapUv),C.push(F.alphaMapUv),C.push(F.lightMapUv),C.push(F.aoMapUv),C.push(F.bumpMapUv),C.push(F.normalMapUv),C.push(F.displacementMapUv),C.push(F.emissiveMapUv),C.push(F.metalnessMapUv),C.push(F.roughnessMapUv),C.push(F.anisotropyMapUv),C.push(F.clearcoatMapUv),C.push(F.clearcoatNormalMapUv),C.push(F.clearcoatRoughnessMapUv),C.push(F.iridescenceMapUv),C.push(F.iridescenceThicknessMapUv),C.push(F.sheenColorMapUv),C.push(F.sheenRoughnessMapUv),C.push(F.specularMapUv),C.push(F.specularColorMapUv),C.push(F.specularIntensityMapUv),C.push(F.transmissionMapUv),C.push(F.thicknessMapUv),C.push(F.combine),C.push(F.fogExp2),C.push(F.sizeAttenuation),C.push(F.morphTargetsCount),C.push(F.morphAttributeCount),C.push(F.numDirLights),C.push(F.numPointLights),C.push(F.numSpotLights),C.push(F.numSpotLightMaps),C.push(F.numHemiLights),C.push(F.numRectAreaLights),C.push(F.numDirLightShadows),C.push(F.numPointLightShadows),C.push(F.numSpotLightShadows),C.push(F.numSpotLightShadowsWithMaps),C.push(F.numLightProbes),C.push(F.shadowMapType),C.push(F.toneMapping),C.push(F.numClippingPlanes),C.push(F.numClipIntersection),C.push(F.depthPacking)}function k(C,F){l.disableAll(),F.supportsVertexTextures&&l.enable(0),F.instancing&&l.enable(1),F.instancingColor&&l.enable(2),F.instancingMorph&&l.enable(3),F.matcap&&l.enable(4),F.envMap&&l.enable(5),F.normalMapObjectSpace&&l.enable(6),F.normalMapTangentSpace&&l.enable(7),F.clearcoat&&l.enable(8),F.iridescence&&l.enable(9),F.alphaTest&&l.enable(10),F.vertexColors&&l.enable(11),F.vertexAlphas&&l.enable(12),F.vertexUv1s&&l.enable(13),F.vertexUv2s&&l.enable(14),F.vertexUv3s&&l.enable(15),F.vertexTangents&&l.enable(16),F.anisotropy&&l.enable(17),F.alphaHash&&l.enable(18),F.batching&&l.enable(19),F.dispersion&&l.enable(20),F.batchingColor&&l.enable(21),F.gradientMap&&l.enable(22),C.push(l.mask),l.disableAll(),F.fog&&l.enable(0),F.useFog&&l.enable(1),F.flatShading&&l.enable(2),F.logarithmicDepthBuffer&&l.enable(3),F.reversedDepthBuffer&&l.enable(4),F.skinning&&l.enable(5),F.morphTargets&&l.enable(6),F.morphNormals&&l.enable(7),F.morphColors&&l.enable(8),F.premultipliedAlpha&&l.enable(9),F.shadowMapEnabled&&l.enable(10),F.doubleSided&&l.enable(11),F.flipSided&&l.enable(12),F.useDepthPacking&&l.enable(13),F.dithering&&l.enable(14),F.transmission&&l.enable(15),F.sheen&&l.enable(16),F.opaque&&l.enable(17),F.pointsUvs&&l.enable(18),F.decodeVideoTexture&&l.enable(19),F.decodeVideoTextureEmissive&&l.enable(20),F.alphaToCoverage&&l.enable(21),C.push(l.mask)}function P(C){const F=y[C.type];let $;if(F){const I=cd[F];$=gve.clone(I.uniforms)}else $=C.uniforms;return $}function N(C,F){let $;for(let I=0,X=u.length;I<X;I++){const L=u[I];if(L.cacheKey===F){$=L,++$.usedTimes;break}}return $===void 0&&($=new Q_e(t,F,C,s),u.push($)),$}function M(C){if(--C.usedTimes===0){const F=u.indexOf(C);u[F]=u[u.length-1],u.pop(),C.destroy()}}function A(C){c.remove(C)}function T(){c.dispose()}return{getParameters:b,getProgramCacheKey:g,getUniforms:P,acquireProgram:N,releaseProgram:M,releaseShaderCache:A,programs:u,dispose:T}}function n1e(){let t=new WeakMap;function e(o){return t.has(o)}function n(o){let l=t.get(o);return l===void 0&&(l={},t.set(o,l)),l}function r(o){t.delete(o)}function i(o,l,c){t.get(o)[l]=c}function s(){t=new WeakMap}return{has:e,get:n,remove:r,update:i,dispose:s}}function r1e(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 SH(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 _H(){const t=[];let e=0;const n=[],r=[],i=[];function s(){e=0,n.length=0,r.length=0,i.length=0}function o(m,p,f,y,v,b){let g=t[e];return g===void 0?(g={id:m.id,object:m,geometry:p,material:f,groupOrder:y,renderOrder:m.renderOrder,z:v,group:b},t[e]=g):(g.id=m.id,g.object=m,g.geometry=p,g.material=f,g.groupOrder=y,g.renderOrder=m.renderOrder,g.z=v,g.group=b),e++,g}function l(m,p,f,y,v,b){const g=o(m,p,f,y,v,b);f.transmission>0?r.push(g):f.transparent===!0?i.push(g):n.push(g)}function c(m,p,f,y,v,b){const g=o(m,p,f,y,v,b);f.transmission>0?r.unshift(g):f.transparent===!0?i.unshift(g):n.unshift(g)}function d(m,p){n.length>1&&n.sort(m||r1e),r.length>1&&r.sort(p||SH),i.length>1&&i.sort(p||SH)}function u(){for(let m=e,p=t.length;m<p;m++){const f=t[m];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:r,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function a1e(){let t=new WeakMap;function e(r,i){const s=t.get(r);let o;return s===void 0?(o=new _H,t.set(r,[o])):i>=s.length?(o=new _H,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function i1e(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new At,color:new sr};break;case"SpotLight":n={position:new At,direction:new At,color:new sr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new At,color:new sr,distance:0,decay:0};break;case"HemisphereLight":n={direction:new At,skyColor:new sr,groundColor:new sr};break;case"RectAreaLight":n={color:new sr,position:new At,halfWidth:new At,halfHeight:new At};break}return t[e.id]=n,n}}}function s1e(){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 tr};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tr};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tr,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let o1e=0;function l1e(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function c1e(t){const e=new i1e,n=s1e(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let d=0;d<9;d++)r.probe.push(new At);const i=new At,s=new ci,o=new ci;function l(d){let u=0,m=0,p=0;for(let C=0;C<9;C++)r.probe[C].set(0,0,0);let f=0,y=0,v=0,b=0,g=0,_=0,k=0,P=0,N=0,M=0,A=0;d.sort(l1e);for(let C=0,F=d.length;C<F;C++){const $=d[C],I=$.color,X=$.intensity,L=$.distance,te=$.shadow&&$.shadow.map?$.shadow.map.texture:null;if($.isAmbientLight)u+=I.r*X,m+=I.g*X,p+=I.b*X;else if($.isLightProbe){for(let ae=0;ae<9;ae++)r.probe[ae].addScaledVector($.sh.coefficients[ae],X);A++}else if($.isDirectionalLight){const ae=e.get($);if(ae.color.copy($.color).multiplyScalar($.intensity),$.castShadow){const ee=$.shadow,me=n.get($);me.shadowIntensity=ee.intensity,me.shadowBias=ee.bias,me.shadowNormalBias=ee.normalBias,me.shadowRadius=ee.radius,me.shadowMapSize=ee.mapSize,r.directionalShadow[f]=me,r.directionalShadowMap[f]=te,r.directionalShadowMatrix[f]=$.shadow.matrix,_++}r.directional[f]=ae,f++}else if($.isSpotLight){const ae=e.get($);ae.position.setFromMatrixPosition($.matrixWorld),ae.color.copy(I).multiplyScalar(X),ae.distance=L,ae.coneCos=Math.cos($.angle),ae.penumbraCos=Math.cos($.angle*(1-$.penumbra)),ae.decay=$.decay,r.spot[v]=ae;const ee=$.shadow;if($.map&&(r.spotLightMap[N]=$.map,N++,ee.updateMatrices($),$.castShadow&&M++),r.spotLightMatrix[v]=ee.matrix,$.castShadow){const me=n.get($);me.shadowIntensity=ee.intensity,me.shadowBias=ee.bias,me.shadowNormalBias=ee.normalBias,me.shadowRadius=ee.radius,me.shadowMapSize=ee.mapSize,r.spotShadow[v]=me,r.spotShadowMap[v]=te,P++}v++}else if($.isRectAreaLight){const ae=e.get($);ae.color.copy(I).multiplyScalar(X),ae.halfWidth.set($.width*.5,0,0),ae.halfHeight.set(0,$.height*.5,0),r.rectArea[b]=ae,b++}else if($.isPointLight){const ae=e.get($);if(ae.color.copy($.color).multiplyScalar($.intensity),ae.distance=$.distance,ae.decay=$.decay,$.castShadow){const ee=$.shadow,me=n.get($);me.shadowIntensity=ee.intensity,me.shadowBias=ee.bias,me.shadowNormalBias=ee.normalBias,me.shadowRadius=ee.radius,me.shadowMapSize=ee.mapSize,me.shadowCameraNear=ee.camera.near,me.shadowCameraFar=ee.camera.far,r.pointShadow[y]=me,r.pointShadowMap[y]=te,r.pointShadowMatrix[y]=$.shadow.matrix,k++}r.point[y]=ae,y++}else if($.isHemisphereLight){const ae=e.get($);ae.skyColor.copy($.color).multiplyScalar(X),ae.groundColor.copy($.groundColor).multiplyScalar(X),r.hemi[g]=ae,g++}}b>0&&(t.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=nn.LTC_FLOAT_1,r.rectAreaLTC2=nn.LTC_FLOAT_2):(r.rectAreaLTC1=nn.LTC_HALF_1,r.rectAreaLTC2=nn.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=m,r.ambient[2]=p;const T=r.hash;(T.directionalLength!==f||T.pointLength!==y||T.spotLength!==v||T.rectAreaLength!==b||T.hemiLength!==g||T.numDirectionalShadows!==_||T.numPointShadows!==k||T.numSpotShadows!==P||T.numSpotMaps!==N||T.numLightProbes!==A)&&(r.directional.length=f,r.spot.length=v,r.rectArea.length=b,r.point.length=y,r.hemi.length=g,r.directionalShadow.length=_,r.directionalShadowMap.length=_,r.pointShadow.length=k,r.pointShadowMap.length=k,r.spotShadow.length=P,r.spotShadowMap.length=P,r.directionalShadowMatrix.length=_,r.pointShadowMatrix.length=k,r.spotLightMatrix.length=P+N-M,r.spotLightMap.length=N,r.numSpotLightShadowsWithMaps=M,r.numLightProbes=A,T.directionalLength=f,T.pointLength=y,T.spotLength=v,T.rectAreaLength=b,T.hemiLength=g,T.numDirectionalShadows=_,T.numPointShadows=k,T.numSpotShadows=P,T.numSpotMaps=N,T.numLightProbes=A,r.version=o1e++)}function c(d,u){let m=0,p=0,f=0,y=0,v=0;const b=u.matrixWorldInverse;for(let g=0,_=d.length;g<_;g++){const k=d[g];if(k.isDirectionalLight){const P=r.directional[m];P.direction.setFromMatrixPosition(k.matrixWorld),i.setFromMatrixPosition(k.target.matrixWorld),P.direction.sub(i),P.direction.transformDirection(b),m++}else if(k.isSpotLight){const P=r.spot[f];P.position.setFromMatrixPosition(k.matrixWorld),P.position.applyMatrix4(b),P.direction.setFromMatrixPosition(k.matrixWorld),i.setFromMatrixPosition(k.target.matrixWorld),P.direction.sub(i),P.direction.transformDirection(b),f++}else if(k.isRectAreaLight){const P=r.rectArea[y];P.position.setFromMatrixPosition(k.matrixWorld),P.position.applyMatrix4(b),o.identity(),s.copy(k.matrixWorld),s.premultiply(b),o.extractRotation(s),P.halfWidth.set(k.width*.5,0,0),P.halfHeight.set(0,k.height*.5,0),P.halfWidth.applyMatrix4(o),P.halfHeight.applyMatrix4(o),y++}else if(k.isPointLight){const P=r.point[p];P.position.setFromMatrixPosition(k.matrixWorld),P.position.applyMatrix4(b),p++}else if(k.isHemisphereLight){const P=r.hemi[v];P.direction.setFromMatrixPosition(k.matrixWorld),P.direction.transformDirection(b),v++}}}return{setup:l,setupView:c,state:r}}function kH(t){const e=new c1e(t),n=[],r=[];function i(u){d.camera=u,n.length=0,r.length=0}function s(u){n.push(u)}function o(u){r.push(u)}function l(){e.setup(n)}function c(u){e.setupView(n,u)}const d={lightsArray:n,shadowsArray:r,camera:null,lights:e,transmissionRenderTarget:{}};return{init:i,state:d,setupLights:l,setupLightsView:c,pushLight:s,pushShadow:o}}function d1e(t){let e=new WeakMap;function n(i,s=0){const o=e.get(i);let l;return o===void 0?(l=new kH(t),e.set(i,[l])):s>=o.length?(l=new kH(t),o.push(l)):l=o[s],l}function r(){e=new WeakMap}return{get:n,dispose:r}}const u1e=`void main() {
  3818. gl_Position = vec4( position, 1.0 );
  3819. }`,m1e=`uniform sampler2D shadow_pass;
  3820. uniform vec2 resolution;
  3821. uniform float radius;
  3822. #include <packing>
  3823. void main() {
  3824. const float samples = float( VSM_SAMPLES );
  3825. float mean = 0.0;
  3826. float squared_mean = 0.0;
  3827. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  3828. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  3829. for ( float i = 0.0; i < samples; i ++ ) {
  3830. float uvOffset = uvStart + i * uvStride;
  3831. #ifdef HORIZONTAL_PASS
  3832. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  3833. mean += distribution.x;
  3834. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  3835. #else
  3836. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  3837. mean += depth;
  3838. squared_mean += depth * depth;
  3839. #endif
  3840. }
  3841. mean = mean / samples;
  3842. squared_mean = squared_mean / samples;
  3843. float std_dev = sqrt( squared_mean - mean * mean );
  3844. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  3845. }`;function h1e(t,e,n){let r=new FO;const i=new tr,s=new tr,o=new ii,l=new Ave({depthPacking:zye}),c=new Mve,d={},u=n.maxTextureSize,m={[$h]:Co,[Co]:$h,[ud]:ud},p=new Xu({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new tr},radius:{value:4}},vertexShader:u1e,fragmentShader:m1e}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const y=new Ql;y.setAttribute("position",new Zs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Zl(y,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=RQ;let g=this.type;this.render=function(M,A,T){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||M.length===0)return;const C=t.getRenderTarget(),F=t.getActiveCubeFace(),$=t.getActiveMipmapLevel(),I=t.state;I.setBlending(Ou),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 X=g!==bu&&this.type===bu,L=g===bu&&this.type!==bu;for(let te=0,ae=M.length;te<ae;te++){const ee=M[te],me=ee.shadow;if(me===void 0){Un("WebGLShadowMap:",ee,"has no shadow.");continue}if(me.autoUpdate===!1&&me.needsUpdate===!1)continue;i.copy(me.mapSize);const le=me.getFrameExtents();if(i.multiply(le),s.copy(me.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/le.x),i.x=s.x*le.x,me.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/le.y),i.y=s.y*le.y,me.mapSize.y=s.y)),me.map===null||X===!0||L===!0){const K=this.type!==bu?{minFilter:nl,magFilter:nl}:{};me.map!==null&&me.map.dispose(),me.map=new $f(i.x,i.y,K),me.map.texture.name=ee.name+".shadowMap",me.camera.updateProjectionMatrix()}t.setRenderTarget(me.map),t.clear();const ue=me.getViewportCount();for(let K=0;K<ue;K++){const ne=me.getViewport(K);o.set(s.x*ne.x,s.y*ne.y,s.x*ne.z,s.y*ne.w),I.viewport(o),me.updateMatrices(ee,K),r=me.getFrustum(),P(A,T,me.camera,ee,this.type)}me.isPointLightShadow!==!0&&this.type===bu&&_(me,T),me.needsUpdate=!1}g=this.type,b.needsUpdate=!1,t.setRenderTarget(C,F,$)};function _(M,A){const T=e.update(v);p.defines.VSM_SAMPLES!==M.blurSamples&&(p.defines.VSM_SAMPLES=M.blurSamples,f.defines.VSM_SAMPLES=M.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new $f(i.x,i.y)),p.uniforms.shadow_pass.value=M.map.texture,p.uniforms.resolution.value=M.mapSize,p.uniforms.radius.value=M.radius,t.setRenderTarget(M.mapPass),t.clear(),t.renderBufferDirect(A,null,T,p,v,null),f.uniforms.shadow_pass.value=M.mapPass.texture,f.uniforms.resolution.value=M.mapSize,f.uniforms.radius.value=M.radius,t.setRenderTarget(M.map),t.clear(),t.renderBufferDirect(A,null,T,f,v,null)}function k(M,A,T,C){let F=null;const $=T.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if($!==void 0)F=$;else if(F=T.isPointLight===!0?c:l,t.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){const I=F.uuid,X=A.uuid;let L=d[I];L===void 0&&(L={},d[I]=L);let te=L[X];te===void 0&&(te=F.clone(),L[X]=te,A.addEventListener("dispose",N)),F=te}if(F.visible=A.visible,F.wireframe=A.wireframe,C===bu?F.side=A.shadowSide!==null?A.shadowSide:A.side:F.side=A.shadowSide!==null?A.shadowSide:m[A.side],F.alphaMap=A.alphaMap,F.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,F.map=A.map,F.clipShadows=A.clipShadows,F.clippingPlanes=A.clippingPlanes,F.clipIntersection=A.clipIntersection,F.displacementMap=A.displacementMap,F.displacementScale=A.displacementScale,F.displacementBias=A.displacementBias,F.wireframeLinewidth=A.wireframeLinewidth,F.linewidth=A.linewidth,T.isPointLight===!0&&F.isMeshDistanceMaterial===!0){const I=t.properties.get(F);I.light=T}return F}function P(M,A,T,C,F){if(M.visible===!1)return;if(M.layers.test(A.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&F===bu)&&(!M.frustumCulled||r.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,M.matrixWorld);const X=e.update(M),L=M.material;if(Array.isArray(L)){const te=X.groups;for(let ae=0,ee=te.length;ae<ee;ae++){const me=te[ae],le=L[me.materialIndex];if(le&&le.visible){const ue=k(M,le,C,F);M.onBeforeShadow(t,M,A,T,X,ue,me),t.renderBufferDirect(T,null,X,ue,M,me),M.onAfterShadow(t,M,A,T,X,ue,me)}}}else if(L.visible){const te=k(M,L,C,F);M.onBeforeShadow(t,M,A,T,X,te,null),t.renderBufferDirect(T,null,X,te,M,null),M.onAfterShadow(t,M,A,T,X,te,null)}}const I=M.children;for(let X=0,L=I.length;X<L;X++)P(I[X],A,T,C,F)}function N(M){M.target.removeEventListener("dispose",N);for(const T in d){const C=d[T],F=M.target.uuid;F in C&&(C[F].dispose(),delete C[F])}}}const p1e={[Q3]:Z3,[J3]:nF,[eF]:rF,[_x]:tF,[Z3]:Q3,[nF]:J3,[rF]:eF,[tF]:_x};function f1e(t,e){function n(){let ce=!1;const ze=new ii;let Ne=null;const Ge=new ii(0,0,0,0);return{setMask:function($e){Ne!==$e&&!ce&&(t.colorMask($e,$e,$e,$e),Ne=$e)},setLocked:function($e){ce=$e},setClear:function($e,Pe,Me,Ve,tt){tt===!0&&($e*=Ve,Pe*=Ve,Me*=Ve),ze.set($e,Pe,Me,Ve),Ge.equals(ze)===!1&&(t.clearColor($e,Pe,Me,Ve),Ge.copy(ze))},reset:function(){ce=!1,Ne=null,Ge.set(-1,0,0,0)}}}function r(){let ce=!1,ze=!1,Ne=null,Ge=null,$e=null;return{setReversed:function(Pe){if(ze!==Pe){const Me=e.get("EXT_clip_control");Pe?Me.clipControlEXT(Me.LOWER_LEFT_EXT,Me.ZERO_TO_ONE_EXT):Me.clipControlEXT(Me.LOWER_LEFT_EXT,Me.NEGATIVE_ONE_TO_ONE_EXT),ze=Pe;const Ve=$e;$e=null,this.setClear(Ve)}},getReversed:function(){return ze},setTest:function(Pe){Pe?Y(t.DEPTH_TEST):D(t.DEPTH_TEST)},setMask:function(Pe){Ne!==Pe&&!ce&&(t.depthMask(Pe),Ne=Pe)},setFunc:function(Pe){if(ze&&(Pe=p1e[Pe]),Ge!==Pe){switch(Pe){case Q3:t.depthFunc(t.NEVER);break;case Z3:t.depthFunc(t.ALWAYS);break;case J3:t.depthFunc(t.LESS);break;case _x:t.depthFunc(t.LEQUAL);break;case eF:t.depthFunc(t.EQUAL);break;case tF:t.depthFunc(t.GEQUAL);break;case nF:t.depthFunc(t.GREATER);break;case rF:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Ge=Pe}},setLocked:function(Pe){ce=Pe},setClear:function(Pe){$e!==Pe&&(ze&&(Pe=1-Pe),t.clearDepth(Pe),$e=Pe)},reset:function(){ce=!1,Ne=null,Ge=null,$e=null,ze=!1}}}function i(){let ce=!1,ze=null,Ne=null,Ge=null,$e=null,Pe=null,Me=null,Ve=null,tt=null;return{setTest:function(ut){ce||(ut?Y(t.STENCIL_TEST):D(t.STENCIL_TEST))},setMask:function(ut){ze!==ut&&!ce&&(t.stencilMask(ut),ze=ut)},setFunc:function(ut,xt,wt){(Ne!==ut||Ge!==xt||$e!==wt)&&(t.stencilFunc(ut,xt,wt),Ne=ut,Ge=xt,$e=wt)},setOp:function(ut,xt,wt){(Pe!==ut||Me!==xt||Ve!==wt)&&(t.stencilOp(ut,xt,wt),Pe=ut,Me=xt,Ve=wt)},setLocked:function(ut){ce=ut},setClear:function(ut){tt!==ut&&(t.clearStencil(ut),tt=ut)},reset:function(){ce=!1,ze=null,Ne=null,Ge=null,$e=null,Pe=null,Me=null,Ve=null,tt=null}}}const s=new n,o=new r,l=new i,c=new WeakMap,d=new WeakMap;let u={},m={},p=new WeakMap,f=[],y=null,v=!1,b=null,g=null,_=null,k=null,P=null,N=null,M=null,A=new sr(0,0,0),T=0,C=!1,F=null,$=null,I=null,X=null,L=null;const te=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let ae=!1,ee=0;const me=t.getParameter(t.VERSION);me.indexOf("WebGL")!==-1?(ee=parseFloat(/^WebGL (\d)/.exec(me)[1]),ae=ee>=1):me.indexOf("OpenGL ES")!==-1&&(ee=parseFloat(/^OpenGL ES (\d)/.exec(me)[1]),ae=ee>=2);let le=null,ue={};const K=t.getParameter(t.SCISSOR_BOX),ne=t.getParameter(t.VIEWPORT),oe=new ii().fromArray(K),be=new ii().fromArray(ne);function _e(ce,ze,Ne,Ge){const $e=new Uint8Array(4),Pe=t.createTexture();t.bindTexture(ce,Pe),t.texParameteri(ce,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(ce,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Me=0;Me<Ne;Me++)ce===t.TEXTURE_3D||ce===t.TEXTURE_2D_ARRAY?t.texImage3D(ze,0,t.RGBA,1,1,Ge,0,t.RGBA,t.UNSIGNED_BYTE,$e):t.texImage2D(ze+Me,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$e);return Pe}const B={};B[t.TEXTURE_2D]=_e(t.TEXTURE_2D,t.TEXTURE_2D,1),B[t.TEXTURE_CUBE_MAP]=_e(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),B[t.TEXTURE_2D_ARRAY]=_e(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),B[t.TEXTURE_3D]=_e(t.TEXTURE_3D,t.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),l.setClear(0),Y(t.DEPTH_TEST),o.setFunc(_x),Q(!1),V(w6),Y(t.CULL_FACE),O(Ou);function Y(ce){u[ce]!==!0&&(t.enable(ce),u[ce]=!0)}function D(ce){u[ce]!==!1&&(t.disable(ce),u[ce]=!1)}function j(ce,ze){return m[ce]!==ze?(t.bindFramebuffer(ce,ze),m[ce]=ze,ce===t.DRAW_FRAMEBUFFER&&(m[t.FRAMEBUFFER]=ze),ce===t.FRAMEBUFFER&&(m[t.DRAW_FRAMEBUFFER]=ze),!0):!1}function z(ce,ze){let Ne=f,Ge=!1;if(ce){Ne=p.get(ze),Ne===void 0&&(Ne=[],p.set(ze,Ne));const $e=ce.textures;if(Ne.length!==$e.length||Ne[0]!==t.COLOR_ATTACHMENT0){for(let Pe=0,Me=$e.length;Pe<Me;Pe++)Ne[Pe]=t.COLOR_ATTACHMENT0+Pe;Ne.length=$e.length,Ge=!0}}else Ne[0]!==t.BACK&&(Ne[0]=t.BACK,Ge=!0);Ge&&t.drawBuffers(Ne)}function W(ce){return y!==ce?(t.useProgram(ce),y=ce,!0):!1}const q={[Zp]:t.FUNC_ADD,[uye]:t.FUNC_SUBTRACT,[mye]:t.FUNC_REVERSE_SUBTRACT};q[hye]=t.MIN,q[pye]=t.MAX;const de={[fye]:t.ZERO,[gye]:t.ONE,[bye]:t.SRC_COLOR,[Y3]:t.SRC_ALPHA,[_ye]:t.SRC_ALPHA_SATURATE,[wye]:t.DST_COLOR,[yye]:t.DST_ALPHA,[xye]:t.ONE_MINUS_SRC_COLOR,[X3]:t.ONE_MINUS_SRC_ALPHA,[Sye]:t.ONE_MINUS_DST_COLOR,[vye]:t.ONE_MINUS_DST_ALPHA,[kye]:t.CONSTANT_COLOR,[Nye]:t.ONE_MINUS_CONSTANT_COLOR,[Cye]:t.CONSTANT_ALPHA,[Pye]:t.ONE_MINUS_CONSTANT_ALPHA};function O(ce,ze,Ne,Ge,$e,Pe,Me,Ve,tt,ut){if(ce===Ou){v===!0&&(D(t.BLEND),v=!1);return}if(v===!1&&(Y(t.BLEND),v=!0),ce!==dye){if(ce!==b||ut!==C){if((g!==Zp||P!==Zp)&&(t.blendEquation(t.FUNC_ADD),g=Zp,P=Zp),ut)switch(ce){case ax:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case S6:t.blendFunc(t.ONE,t.ONE);break;case _6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case k6:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:Xa("WebGLState: Invalid blending: ",ce);break}else switch(ce){case ax:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case S6:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case _6:Xa("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case k6:Xa("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Xa("WebGLState: Invalid blending: ",ce);break}_=null,k=null,N=null,M=null,A.set(0,0,0),T=0,b=ce,C=ut}return}$e=$e||ze,Pe=Pe||Ne,Me=Me||Ge,(ze!==g||$e!==P)&&(t.blendEquationSeparate(q[ze],q[$e]),g=ze,P=$e),(Ne!==_||Ge!==k||Pe!==N||Me!==M)&&(t.blendFuncSeparate(de[Ne],de[Ge],de[Pe],de[Me]),_=Ne,k=Ge,N=Pe,M=Me),(Ve.equals(A)===!1||tt!==T)&&(t.blendColor(Ve.r,Ve.g,Ve.b,tt),A.copy(Ve),T=tt),b=ce,C=!1}function G(ce,ze){ce.side===ud?D(t.CULL_FACE):Y(t.CULL_FACE);let Ne=ce.side===Co;ze&&(Ne=!Ne),Q(Ne),ce.blending===ax&&ce.transparent===!1?O(Ou):O(ce.blending,ce.blendEquation,ce.blendSrc,ce.blendDst,ce.blendEquationAlpha,ce.blendSrcAlpha,ce.blendDstAlpha,ce.blendColor,ce.blendAlpha,ce.premultipliedAlpha),o.setFunc(ce.depthFunc),o.setTest(ce.depthTest),o.setMask(ce.depthWrite),s.setMask(ce.colorWrite);const Ge=ce.stencilWrite;l.setTest(Ge),Ge&&(l.setMask(ce.stencilWriteMask),l.setFunc(ce.stencilFunc,ce.stencilRef,ce.stencilFuncMask),l.setOp(ce.stencilFail,ce.stencilZFail,ce.stencilZPass)),ie(ce.polygonOffset,ce.polygonOffsetFactor,ce.polygonOffsetUnits),ce.alphaToCoverage===!0?Y(t.SAMPLE_ALPHA_TO_COVERAGE):D(t.SAMPLE_ALPHA_TO_COVERAGE)}function Q(ce){F!==ce&&(ce?t.frontFace(t.CW):t.frontFace(t.CCW),F=ce)}function V(ce){ce!==oye?(Y(t.CULL_FACE),ce!==$&&(ce===w6?t.cullFace(t.BACK):ce===lye?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):D(t.CULL_FACE),$=ce}function J(ce){ce!==I&&(ae&&t.lineWidth(ce),I=ce)}function ie(ce,ze,Ne){ce?(Y(t.POLYGON_OFFSET_FILL),(X!==ze||L!==Ne)&&(t.polygonOffset(ze,Ne),X=ze,L=Ne)):D(t.POLYGON_OFFSET_FILL)}function he(ce){ce?Y(t.SCISSOR_TEST):D(t.SCISSOR_TEST)}function fe(ce){ce===void 0&&(ce=t.TEXTURE0+te-1),le!==ce&&(t.activeTexture(ce),le=ce)}function se(ce,ze,Ne){Ne===void 0&&(le===null?Ne=t.TEXTURE0+te-1:Ne=le);let Ge=ue[Ne];Ge===void 0&&(Ge={type:void 0,texture:void 0},ue[Ne]=Ge),(Ge.type!==ce||Ge.texture!==ze)&&(le!==Ne&&(t.activeTexture(Ne),le=Ne),t.bindTexture(ce,ze||B[ce]),Ge.type=ce,Ge.texture=ze)}function U(){const ce=ue[le];ce!==void 0&&ce.type!==void 0&&(t.bindTexture(ce.type,null),ce.type=void 0,ce.texture=void 0)}function R(){try{t.compressedTexImage2D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function re(){try{t.compressedTexImage3D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function xe(){try{t.texSubImage2D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function we(){try{t.texSubImage3D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function ye(){try{t.compressedTexSubImage2D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function Ae(){try{t.compressedTexSubImage3D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function ve(){try{t.texStorage2D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function Te(){try{t.texStorage3D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function Fe(){try{t.texImage2D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function Ee(){try{t.texImage3D(...arguments)}catch(ce){ce("WebGLState:",ce)}}function Se(ce){oe.equals(ce)===!1&&(t.scissor(ce.x,ce.y,ce.z,ce.w),oe.copy(ce))}function je(ce){be.equals(ce)===!1&&(t.viewport(ce.x,ce.y,ce.z,ce.w),be.copy(ce))}function qe(ce,ze){let Ne=d.get(ze);Ne===void 0&&(Ne=new WeakMap,d.set(ze,Ne));let Ge=Ne.get(ce);Ge===void 0&&(Ge=t.getUniformBlockIndex(ze,ce.name),Ne.set(ce,Ge))}function Re(ce,ze){const Ge=d.get(ze).get(ce);c.get(ze)!==Ge&&(t.uniformBlockBinding(ze,Ge,ce.__bindingPointIndex),c.set(ze,Ge))}function Ye(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),o.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),u={},le=null,ue={},m={},p=new WeakMap,f=[],y=null,v=!1,b=null,g=null,_=null,k=null,P=null,N=null,M=null,A=new sr(0,0,0),T=0,C=!1,F=null,$=null,I=null,X=null,L=null,oe.set(0,0,t.canvas.width,t.canvas.height),be.set(0,0,t.canvas.width,t.canvas.height),s.reset(),o.reset(),l.reset()}return{buffers:{color:s,depth:o,stencil:l},enable:Y,disable:D,bindFramebuffer:j,drawBuffers:z,useProgram:W,setBlending:O,setMaterial:G,setFlipSided:Q,setCullFace:V,setLineWidth:J,setPolygonOffset:ie,setScissorTest:he,activeTexture:fe,bindTexture:se,unbindTexture:U,compressedTexImage2D:R,compressedTexImage3D:re,texImage2D:Fe,texImage3D:Ee,updateUBOMapping:qe,uniformBlockBinding:Re,texStorage2D:ve,texStorage3D:Te,texSubImage2D:xe,texSubImage3D:we,compressedTexSubImage2D:ye,compressedTexSubImage3D:Ae,scissor:Se,viewport:je,reset:Ye}}function g1e(t,e,n,r,i,s,o){const l=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),d=new tr,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 y(U,R){return f?new OffscreenCanvas(U,R):dN("canvas")}function v(U,R,re){let xe=1;const we=se(U);if((we.width>re||we.height>re)&&(xe=re/Math.max(we.width,we.height)),xe<1)if(typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&U instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&U instanceof ImageBitmap||typeof VideoFrame<"u"&&U instanceof VideoFrame){const ye=Math.floor(xe*we.width),Ae=Math.floor(xe*we.height);m===void 0&&(m=y(ye,Ae));const ve=R?y(ye,Ae):m;return ve.width=ye,ve.height=Ae,ve.getContext("2d").drawImage(U,0,0,ye,Ae),Un("WebGLRenderer: Texture has been resized from ("+we.width+"x"+we.height+") to ("+ye+"x"+Ae+")."),ve}else return"data"in U&&Un("WebGLRenderer: Image in DataTexture is too big ("+we.width+"x"+we.height+")."),U;return U}function b(U){return U.generateMipmaps}function g(U){t.generateMipmap(U)}function _(U){return U.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:U.isWebGL3DRenderTarget?t.TEXTURE_3D:U.isWebGLArrayRenderTarget||U.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function k(U,R,re,xe,we=!1){if(U!==null){if(t[U]!==void 0)return t[U];Un("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+U+"'")}let ye=R;if(R===t.RED&&(re===t.FLOAT&&(ye=t.R32F),re===t.HALF_FLOAT&&(ye=t.R16F),re===t.UNSIGNED_BYTE&&(ye=t.R8)),R===t.RED_INTEGER&&(re===t.UNSIGNED_BYTE&&(ye=t.R8UI),re===t.UNSIGNED_SHORT&&(ye=t.R16UI),re===t.UNSIGNED_INT&&(ye=t.R32UI),re===t.BYTE&&(ye=t.R8I),re===t.SHORT&&(ye=t.R16I),re===t.INT&&(ye=t.R32I)),R===t.RG&&(re===t.FLOAT&&(ye=t.RG32F),re===t.HALF_FLOAT&&(ye=t.RG16F),re===t.UNSIGNED_BYTE&&(ye=t.RG8)),R===t.RG_INTEGER&&(re===t.UNSIGNED_BYTE&&(ye=t.RG8UI),re===t.UNSIGNED_SHORT&&(ye=t.RG16UI),re===t.UNSIGNED_INT&&(ye=t.RG32UI),re===t.BYTE&&(ye=t.RG8I),re===t.SHORT&&(ye=t.RG16I),re===t.INT&&(ye=t.RG32I)),R===t.RGB_INTEGER&&(re===t.UNSIGNED_BYTE&&(ye=t.RGB8UI),re===t.UNSIGNED_SHORT&&(ye=t.RGB16UI),re===t.UNSIGNED_INT&&(ye=t.RGB32UI),re===t.BYTE&&(ye=t.RGB8I),re===t.SHORT&&(ye=t.RGB16I),re===t.INT&&(ye=t.RGB32I)),R===t.RGBA_INTEGER&&(re===t.UNSIGNED_BYTE&&(ye=t.RGBA8UI),re===t.UNSIGNED_SHORT&&(ye=t.RGBA16UI),re===t.UNSIGNED_INT&&(ye=t.RGBA32UI),re===t.BYTE&&(ye=t.RGBA8I),re===t.SHORT&&(ye=t.RGBA16I),re===t.INT&&(ye=t.RGBA32I)),R===t.RGB&&(re===t.UNSIGNED_INT_5_9_9_9_REV&&(ye=t.RGB9_E5),re===t.UNSIGNED_INT_10F_11F_11F_REV&&(ye=t.R11F_G11F_B10F)),R===t.RGBA){const Ae=we?lN:Cr.getTransfer(xe);re===t.FLOAT&&(ye=t.RGBA32F),re===t.HALF_FLOAT&&(ye=t.RGBA16F),re===t.UNSIGNED_BYTE&&(ye=Ae===Hr?t.SRGB8_ALPHA8:t.RGBA8),re===t.UNSIGNED_SHORT_4_4_4_4&&(ye=t.RGBA4),re===t.UNSIGNED_SHORT_5_5_5_1&&(ye=t.RGB5_A1)}return(ye===t.R16F||ye===t.R32F||ye===t.RG16F||ye===t.RG32F||ye===t.RGBA16F||ye===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function P(U,R){let re;return U?R===null||R===Hf||R===z0?re=t.DEPTH24_STENCIL8:R===Mu?re=t.DEPTH32F_STENCIL8:R===I0&&(re=t.DEPTH24_STENCIL8,Un("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===Hf||R===z0?re=t.DEPTH_COMPONENT24:R===Mu?re=t.DEPTH_COMPONENT32F:R===I0&&(re=t.DEPTH_COMPONENT16),re}function N(U,R){return b(U)===!0||U.isFramebufferTexture&&U.minFilter!==nl&&U.minFilter!==Bl?Math.log2(Math.max(R.width,R.height))+1:U.mipmaps!==void 0&&U.mipmaps.length>0?U.mipmaps.length:U.isCompressedTexture&&Array.isArray(U.image)?R.mipmaps.length:1}function M(U){const R=U.target;R.removeEventListener("dispose",M),T(R),R.isVideoTexture&&u.delete(R)}function A(U){const R=U.target;R.removeEventListener("dispose",A),F(R)}function T(U){const R=r.get(U);if(R.__webglInit===void 0)return;const re=U.source,xe=p.get(re);if(xe){const we=xe[R.__cacheKey];we.usedTimes--,we.usedTimes===0&&C(U),Object.keys(xe).length===0&&p.delete(re)}r.remove(U)}function C(U){const R=r.get(U);t.deleteTexture(R.__webglTexture);const re=U.source,xe=p.get(re);delete xe[R.__cacheKey],o.memory.textures--}function F(U){const R=r.get(U);if(U.depthTexture&&(U.depthTexture.dispose(),r.remove(U.depthTexture)),U.isWebGLCubeRenderTarget)for(let xe=0;xe<6;xe++){if(Array.isArray(R.__webglFramebuffer[xe]))for(let we=0;we<R.__webglFramebuffer[xe].length;we++)t.deleteFramebuffer(R.__webglFramebuffer[xe][we]);else t.deleteFramebuffer(R.__webglFramebuffer[xe]);R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer[xe])}else{if(Array.isArray(R.__webglFramebuffer))for(let xe=0;xe<R.__webglFramebuffer.length;xe++)t.deleteFramebuffer(R.__webglFramebuffer[xe]);else t.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&t.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let xe=0;xe<R.__webglColorRenderbuffer.length;xe++)R.__webglColorRenderbuffer[xe]&&t.deleteRenderbuffer(R.__webglColorRenderbuffer[xe]);R.__webglDepthRenderbuffer&&t.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const re=U.textures;for(let xe=0,we=re.length;xe<we;xe++){const ye=r.get(re[xe]);ye.__webglTexture&&(t.deleteTexture(ye.__webglTexture),o.memory.textures--),r.remove(re[xe])}r.remove(U)}let $=0;function I(){$=0}function X(){const U=$;return U>=i.maxTextures&&Un("WebGLTextures: Trying to use "+U+" texture units while this GPU supports only "+i.maxTextures),$+=1,U}function L(U){const R=[];return R.push(U.wrapS),R.push(U.wrapT),R.push(U.wrapR||0),R.push(U.magFilter),R.push(U.minFilter),R.push(U.anisotropy),R.push(U.internalFormat),R.push(U.format),R.push(U.type),R.push(U.generateMipmaps),R.push(U.premultiplyAlpha),R.push(U.flipY),R.push(U.unpackAlignment),R.push(U.colorSpace),R.join()}function te(U,R){const re=r.get(U);if(U.isVideoTexture&&he(U),U.isRenderTargetTexture===!1&&U.isExternalTexture!==!0&&U.version>0&&re.__version!==U.version){const xe=U.image;if(xe===null)Un("WebGLRenderer: Texture marked for update but no image data found.");else if(xe.complete===!1)Un("WebGLRenderer: Texture marked for update but image is incomplete");else{B(re,U,R);return}}else U.isExternalTexture&&(re.__webglTexture=U.sourceTexture?U.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,re.__webglTexture,t.TEXTURE0+R)}function ae(U,R){const re=r.get(U);if(U.isRenderTargetTexture===!1&&U.version>0&&re.__version!==U.version){B(re,U,R);return}else U.isExternalTexture&&(re.__webglTexture=U.sourceTexture?U.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,re.__webglTexture,t.TEXTURE0+R)}function ee(U,R){const re=r.get(U);if(U.isRenderTargetTexture===!1&&U.version>0&&re.__version!==U.version){B(re,U,R);return}n.bindTexture(t.TEXTURE_3D,re.__webglTexture,t.TEXTURE0+R)}function me(U,R){const re=r.get(U);if(U.version>0&&re.__version!==U.version){Y(re,U,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,re.__webglTexture,t.TEXTURE0+R)}const le={[sF]:t.REPEAT,[Au]:t.CLAMP_TO_EDGE,[oF]:t.MIRRORED_REPEAT},ue={[nl]:t.NEAREST,[Oye]:t.NEAREST_MIPMAP_NEAREST,[M_]:t.NEAREST_MIPMAP_LINEAR,[Bl]:t.LINEAR,[pj]:t.LINEAR_MIPMAP_NEAREST,[sf]:t.LINEAR_MIPMAP_LINEAR},K={[Bye]:t.NEVER,[Wye]:t.ALWAYS,[Hye]:t.LESS,[VQ]:t.LEQUAL,[qye]:t.EQUAL,[Gye]:t.GEQUAL,[$ye]:t.GREATER,[Vye]:t.NOTEQUAL};function ne(U,R){if(R.type===Mu&&e.has("OES_texture_float_linear")===!1&&(R.magFilter===Bl||R.magFilter===pj||R.magFilter===M_||R.magFilter===sf||R.minFilter===Bl||R.minFilter===pj||R.minFilter===M_||R.minFilter===sf)&&Un("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(U,t.TEXTURE_WRAP_S,le[R.wrapS]),t.texParameteri(U,t.TEXTURE_WRAP_T,le[R.wrapT]),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,le[R.wrapR]),t.texParameteri(U,t.TEXTURE_MAG_FILTER,ue[R.magFilter]),t.texParameteri(U,t.TEXTURE_MIN_FILTER,ue[R.minFilter]),R.compareFunction&&(t.texParameteri(U,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(U,t.TEXTURE_COMPARE_FUNC,K[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===nl||R.minFilter!==M_&&R.minFilter!==sf||R.type===Mu&&e.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||r.get(R).__currentAnisotropy){const re=e.get("EXT_texture_filter_anisotropic");t.texParameterf(U,re.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy}}}function oe(U,R){let re=!1;U.__webglInit===void 0&&(U.__webglInit=!0,R.addEventListener("dispose",M));const xe=R.source;let we=p.get(xe);we===void 0&&(we={},p.set(xe,we));const ye=L(R);if(ye!==U.__cacheKey){we[ye]===void 0&&(we[ye]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,re=!0),we[ye].usedTimes++;const Ae=we[U.__cacheKey];Ae!==void 0&&(we[U.__cacheKey].usedTimes--,Ae.usedTimes===0&&C(R)),U.__cacheKey=ye,U.__webglTexture=we[ye].texture}return re}function be(U,R,re){return Math.floor(Math.floor(U/re)/R)}function _e(U,R,re,xe){const ye=U.updateRanges;if(ye.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,R.width,R.height,re,xe,R.data);else{ye.sort((Ee,Se)=>Ee.start-Se.start);let Ae=0;for(let Ee=1;Ee<ye.length;Ee++){const Se=ye[Ae],je=ye[Ee],qe=Se.start+Se.count,Re=be(je.start,R.width,4),Ye=be(Se.start,R.width,4);je.start<=qe+1&&Re===Ye&&be(je.start+je.count-1,R.width,4)===Re?Se.count=Math.max(Se.count,je.start+je.count-Se.start):(++Ae,ye[Ae]=je)}ye.length=Ae+1;const ve=t.getParameter(t.UNPACK_ROW_LENGTH),Te=t.getParameter(t.UNPACK_SKIP_PIXELS),Fe=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,R.width);for(let Ee=0,Se=ye.length;Ee<Se;Ee++){const je=ye[Ee],qe=Math.floor(je.start/4),Re=Math.ceil(je.count/4),Ye=qe%R.width,ce=Math.floor(qe/R.width),ze=Re,Ne=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,Ye),t.pixelStorei(t.UNPACK_SKIP_ROWS,ce),n.texSubImage2D(t.TEXTURE_2D,0,Ye,ce,ze,Ne,re,xe,R.data)}U.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,ve),t.pixelStorei(t.UNPACK_SKIP_PIXELS,Te),t.pixelStorei(t.UNPACK_SKIP_ROWS,Fe)}}function B(U,R,re){let xe=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(xe=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(xe=t.TEXTURE_3D);const we=oe(U,R),ye=R.source;n.bindTexture(xe,U.__webglTexture,t.TEXTURE0+re);const Ae=r.get(ye);if(ye.version!==Ae.__version||we===!0){n.activeTexture(t.TEXTURE0+re);const ve=Cr.getPrimaries(Cr.workingColorSpace),Te=R.colorSpace===uh?null:Cr.getPrimaries(R.colorSpace),Fe=R.colorSpace===uh||ve===Te?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,Fe);let Ee=v(R.image,!1,i.maxTextureSize);Ee=fe(R,Ee);const Se=s.convert(R.format,R.colorSpace),je=s.convert(R.type);let qe=k(R.internalFormat,Se,je,R.colorSpace,R.isVideoTexture);ne(xe,R);let Re;const Ye=R.mipmaps,ce=R.isVideoTexture!==!0,ze=Ae.__version===void 0||we===!0,Ne=ye.dataReady,Ge=N(R,Ee);if(R.isDepthTexture)qe=P(R.format===B0,R.type),ze&&(ce?n.texStorage2D(t.TEXTURE_2D,1,qe,Ee.width,Ee.height):n.texImage2D(t.TEXTURE_2D,0,qe,Ee.width,Ee.height,0,Se,je,null));else if(R.isDataTexture)if(Ye.length>0){ce&&ze&&n.texStorage2D(t.TEXTURE_2D,Ge,qe,Ye[0].width,Ye[0].height);for(let $e=0,Pe=Ye.length;$e<Pe;$e++)Re=Ye[$e],ce?Ne&&n.texSubImage2D(t.TEXTURE_2D,$e,0,0,Re.width,Re.height,Se,je,Re.data):n.texImage2D(t.TEXTURE_2D,$e,qe,Re.width,Re.height,0,Se,je,Re.data);R.generateMipmaps=!1}else ce?(ze&&n.texStorage2D(t.TEXTURE_2D,Ge,qe,Ee.width,Ee.height),Ne&&_e(R,Ee,Se,je)):n.texImage2D(t.TEXTURE_2D,0,qe,Ee.width,Ee.height,0,Se,je,Ee.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){ce&&ze&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ge,qe,Ye[0].width,Ye[0].height,Ee.depth);for(let $e=0,Pe=Ye.length;$e<Pe;$e++)if(Re=Ye[$e],R.format!==Tc)if(Se!==null)if(ce){if(Ne)if(R.layerUpdates.size>0){const Me=tH(Re.width,Re.height,R.format,R.type);for(const Ve of R.layerUpdates){const tt=Re.data.subarray(Ve*Me/Re.data.BYTES_PER_ELEMENT,(Ve+1)*Me/Re.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,$e,0,0,Ve,Re.width,Re.height,1,Se,tt)}R.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,$e,0,0,0,Re.width,Re.height,Ee.depth,Se,Re.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,$e,qe,Re.width,Re.height,Ee.depth,0,Re.data,0,0);else Un("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else ce?Ne&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,$e,0,0,0,Re.width,Re.height,Ee.depth,Se,je,Re.data):n.texImage3D(t.TEXTURE_2D_ARRAY,$e,qe,Re.width,Re.height,Ee.depth,0,Se,je,Re.data)}else{ce&&ze&&n.texStorage2D(t.TEXTURE_2D,Ge,qe,Ye[0].width,Ye[0].height);for(let $e=0,Pe=Ye.length;$e<Pe;$e++)Re=Ye[$e],R.format!==Tc?Se!==null?ce?Ne&&n.compressedTexSubImage2D(t.TEXTURE_2D,$e,0,0,Re.width,Re.height,Se,Re.data):n.compressedTexImage2D(t.TEXTURE_2D,$e,qe,Re.width,Re.height,0,Re.data):Un("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):ce?Ne&&n.texSubImage2D(t.TEXTURE_2D,$e,0,0,Re.width,Re.height,Se,je,Re.data):n.texImage2D(t.TEXTURE_2D,$e,qe,Re.width,Re.height,0,Se,je,Re.data)}else if(R.isDataArrayTexture)if(ce){if(ze&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ge,qe,Ee.width,Ee.height,Ee.depth),Ne)if(R.layerUpdates.size>0){const $e=tH(Ee.width,Ee.height,R.format,R.type);for(const Pe of R.layerUpdates){const Me=Ee.data.subarray(Pe*$e/Ee.data.BYTES_PER_ELEMENT,(Pe+1)*$e/Ee.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,Pe,Ee.width,Ee.height,1,Se,je,Me)}R.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Ee.width,Ee.height,Ee.depth,Se,je,Ee.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,qe,Ee.width,Ee.height,Ee.depth,0,Se,je,Ee.data);else if(R.isData3DTexture)ce?(ze&&n.texStorage3D(t.TEXTURE_3D,Ge,qe,Ee.width,Ee.height,Ee.depth),Ne&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Ee.width,Ee.height,Ee.depth,Se,je,Ee.data)):n.texImage3D(t.TEXTURE_3D,0,qe,Ee.width,Ee.height,Ee.depth,0,Se,je,Ee.data);else if(R.isFramebufferTexture){if(ze)if(ce)n.texStorage2D(t.TEXTURE_2D,Ge,qe,Ee.width,Ee.height);else{let $e=Ee.width,Pe=Ee.height;for(let Me=0;Me<Ge;Me++)n.texImage2D(t.TEXTURE_2D,Me,qe,$e,Pe,0,Se,je,null),$e>>=1,Pe>>=1}}else if(Ye.length>0){if(ce&&ze){const $e=se(Ye[0]);n.texStorage2D(t.TEXTURE_2D,Ge,qe,$e.width,$e.height)}for(let $e=0,Pe=Ye.length;$e<Pe;$e++)Re=Ye[$e],ce?Ne&&n.texSubImage2D(t.TEXTURE_2D,$e,0,0,Se,je,Re):n.texImage2D(t.TEXTURE_2D,$e,qe,Se,je,Re);R.generateMipmaps=!1}else if(ce){if(ze){const $e=se(Ee);n.texStorage2D(t.TEXTURE_2D,Ge,qe,$e.width,$e.height)}Ne&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,Se,je,Ee)}else n.texImage2D(t.TEXTURE_2D,0,qe,Se,je,Ee);b(R)&&g(xe),Ae.__version=ye.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function Y(U,R,re){if(R.image.length!==6)return;const xe=oe(U,R),we=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,U.__webglTexture,t.TEXTURE0+re);const ye=r.get(we);if(we.version!==ye.__version||xe===!0){n.activeTexture(t.TEXTURE0+re);const Ae=Cr.getPrimaries(Cr.workingColorSpace),ve=R.colorSpace===uh?null:Cr.getPrimaries(R.colorSpace),Te=R.colorSpace===uh||Ae===ve?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Te);const Fe=R.isCompressedTexture||R.image[0].isCompressedTexture,Ee=R.image[0]&&R.image[0].isDataTexture,Se=[];for(let Pe=0;Pe<6;Pe++)!Fe&&!Ee?Se[Pe]=v(R.image[Pe],!0,i.maxCubemapSize):Se[Pe]=Ee?R.image[Pe].image:R.image[Pe],Se[Pe]=fe(R,Se[Pe]);const je=Se[0],qe=s.convert(R.format,R.colorSpace),Re=s.convert(R.type),Ye=k(R.internalFormat,qe,Re,R.colorSpace),ce=R.isVideoTexture!==!0,ze=ye.__version===void 0||xe===!0,Ne=we.dataReady;let Ge=N(R,je);ne(t.TEXTURE_CUBE_MAP,R);let $e;if(Fe){ce&&ze&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Ge,Ye,je.width,je.height);for(let Pe=0;Pe<6;Pe++){$e=Se[Pe].mipmaps;for(let Me=0;Me<$e.length;Me++){const Ve=$e[Me];R.format!==Tc?qe!==null?ce?Ne&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,0,0,Ve.width,Ve.height,qe,Ve.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,Ye,Ve.width,Ve.height,0,Ve.data):Un("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):ce?Ne&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,0,0,Ve.width,Ve.height,qe,Re,Ve.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,Ye,Ve.width,Ve.height,0,qe,Re,Ve.data)}}}else{if($e=R.mipmaps,ce&&ze){$e.length>0&&Ge++;const Pe=se(Se[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,Ge,Ye,Pe.width,Pe.height)}for(let Pe=0;Pe<6;Pe++)if(Ee){ce?Ne&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,0,0,Se[Pe].width,Se[Pe].height,qe,Re,Se[Pe].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,Ye,Se[Pe].width,Se[Pe].height,0,qe,Re,Se[Pe].data);for(let Me=0;Me<$e.length;Me++){const tt=$e[Me].image[Pe].image;ce?Ne&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,0,0,tt.width,tt.height,qe,Re,tt.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,Ye,tt.width,tt.height,0,qe,Re,tt.data)}}else{ce?Ne&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,0,0,qe,Re,Se[Pe]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,Ye,qe,Re,Se[Pe]);for(let Me=0;Me<$e.length;Me++){const Ve=$e[Me];ce?Ne&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,0,0,qe,Re,Ve.image[Pe]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,Ye,qe,Re,Ve.image[Pe])}}}b(R)&&g(t.TEXTURE_CUBE_MAP),ye.__version=we.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function D(U,R,re,xe,we,ye){const Ae=s.convert(re.format,re.colorSpace),ve=s.convert(re.type),Te=k(re.internalFormat,Ae,ve,re.colorSpace),Fe=r.get(R),Ee=r.get(re);if(Ee.__renderTarget=R,!Fe.__hasExternalTextures){const Se=Math.max(1,R.width>>ye),je=Math.max(1,R.height>>ye);we===t.TEXTURE_3D||we===t.TEXTURE_2D_ARRAY?n.texImage3D(we,ye,Te,Se,je,R.depth,0,Ae,ve,null):n.texImage2D(we,ye,Te,Se,je,0,Ae,ve,null)}n.bindFramebuffer(t.FRAMEBUFFER,U),ie(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,xe,we,Ee.__webglTexture,0,J(R)):(we===t.TEXTURE_2D||we>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&we<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,xe,we,Ee.__webglTexture,ye),n.bindFramebuffer(t.FRAMEBUFFER,null)}function j(U,R,re){if(t.bindRenderbuffer(t.RENDERBUFFER,U),R.depthBuffer){const xe=R.depthTexture,we=xe&&xe.isDepthTexture?xe.type:null,ye=P(R.stencilBuffer,we),Ae=R.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ve=J(R);ie(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ve,ye,R.width,R.height):re?t.renderbufferStorageMultisample(t.RENDERBUFFER,ve,ye,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,ye,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,Ae,t.RENDERBUFFER,U)}else{const xe=R.textures;for(let we=0;we<xe.length;we++){const ye=xe[we],Ae=s.convert(ye.format,ye.colorSpace),ve=s.convert(ye.type),Te=k(ye.internalFormat,Ae,ve,ye.colorSpace),Fe=J(R);re&&ie(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Fe,Te,R.width,R.height):ie(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Fe,Te,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Te,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function z(U,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,U),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const xe=r.get(R.depthTexture);xe.__renderTarget=R,(!xe.__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),te(R.depthTexture,0);const we=xe.__webglTexture,ye=J(R);if(R.depthTexture.format===U0)ie(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,we,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,we,0);else if(R.depthTexture.format===B0)ie(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,we,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,we,0);else throw new Error("Unknown depthTexture format")}function W(U){const R=r.get(U),re=U.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==U.depthTexture){const xe=U.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),xe){const we=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,xe.removeEventListener("dispose",we)};xe.addEventListener("dispose",we),R.__depthDisposeCallback=we}R.__boundDepthTexture=xe}if(U.depthTexture&&!R.__autoAllocateDepthBuffer){if(re)throw new Error("target.depthTexture not supported in Cube render targets");const xe=U.texture.mipmaps;xe&&xe.length>0?z(R.__webglFramebuffer[0],U):z(R.__webglFramebuffer,U)}else if(re){R.__webglDepthbuffer=[];for(let xe=0;xe<6;xe++)if(n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[xe]),R.__webglDepthbuffer[xe]===void 0)R.__webglDepthbuffer[xe]=t.createRenderbuffer(),j(R.__webglDepthbuffer[xe],U,!1);else{const we=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ye=R.__webglDepthbuffer[xe];t.bindRenderbuffer(t.RENDERBUFFER,ye),t.framebufferRenderbuffer(t.FRAMEBUFFER,we,t.RENDERBUFFER,ye)}}else{const xe=U.texture.mipmaps;if(xe&&xe.length>0?n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=t.createRenderbuffer(),j(R.__webglDepthbuffer,U,!1);else{const we=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ye=R.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,ye),t.framebufferRenderbuffer(t.FRAMEBUFFER,we,t.RENDERBUFFER,ye)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function q(U,R,re){const xe=r.get(U);R!==void 0&&D(xe.__webglFramebuffer,U,U.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),re!==void 0&&W(U)}function de(U){const R=U.texture,re=r.get(U),xe=r.get(R);U.addEventListener("dispose",A);const we=U.textures,ye=U.isWebGLCubeRenderTarget===!0,Ae=we.length>1;if(Ae||(xe.__webglTexture===void 0&&(xe.__webglTexture=t.createTexture()),xe.__version=R.version,o.memory.textures++),ye){re.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer[ve]=[];for(let Te=0;Te<R.mipmaps.length;Te++)re.__webglFramebuffer[ve][Te]=t.createFramebuffer()}else re.__webglFramebuffer[ve]=t.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer=[];for(let ve=0;ve<R.mipmaps.length;ve++)re.__webglFramebuffer[ve]=t.createFramebuffer()}else re.__webglFramebuffer=t.createFramebuffer();if(Ae)for(let ve=0,Te=we.length;ve<Te;ve++){const Fe=r.get(we[ve]);Fe.__webglTexture===void 0&&(Fe.__webglTexture=t.createTexture(),o.memory.textures++)}if(U.samples>0&&ie(U)===!1){re.__webglMultisampledFramebuffer=t.createFramebuffer(),re.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,re.__webglMultisampledFramebuffer);for(let ve=0;ve<we.length;ve++){const Te=we[ve];re.__webglColorRenderbuffer[ve]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,re.__webglColorRenderbuffer[ve]);const Fe=s.convert(Te.format,Te.colorSpace),Ee=s.convert(Te.type),Se=k(Te.internalFormat,Fe,Ee,Te.colorSpace,U.isXRRenderTarget===!0),je=J(U);t.renderbufferStorageMultisample(t.RENDERBUFFER,je,Se,U.width,U.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+ve,t.RENDERBUFFER,re.__webglColorRenderbuffer[ve])}t.bindRenderbuffer(t.RENDERBUFFER,null),U.depthBuffer&&(re.__webglDepthRenderbuffer=t.createRenderbuffer(),j(re.__webglDepthRenderbuffer,U,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(ye){n.bindTexture(t.TEXTURE_CUBE_MAP,xe.__webglTexture),ne(t.TEXTURE_CUBE_MAP,R);for(let ve=0;ve<6;ve++)if(R.mipmaps&&R.mipmaps.length>0)for(let Te=0;Te<R.mipmaps.length;Te++)D(re.__webglFramebuffer[ve][Te],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,Te);else D(re.__webglFramebuffer[ve],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);b(R)&&g(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(Ae){for(let ve=0,Te=we.length;ve<Te;ve++){const Fe=we[ve],Ee=r.get(Fe);let Se=t.TEXTURE_2D;(U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(Se=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(Se,Ee.__webglTexture),ne(Se,Fe),D(re.__webglFramebuffer,U,Fe,t.COLOR_ATTACHMENT0+ve,Se,0),b(Fe)&&g(Se)}n.unbindTexture()}else{let ve=t.TEXTURE_2D;if((U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(ve=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(ve,xe.__webglTexture),ne(ve,R),R.mipmaps&&R.mipmaps.length>0)for(let Te=0;Te<R.mipmaps.length;Te++)D(re.__webglFramebuffer[Te],U,R,t.COLOR_ATTACHMENT0,ve,Te);else D(re.__webglFramebuffer,U,R,t.COLOR_ATTACHMENT0,ve,0);b(R)&&g(ve),n.unbindTexture()}U.depthBuffer&&W(U)}function O(U){const R=U.textures;for(let re=0,xe=R.length;re<xe;re++){const we=R[re];if(b(we)){const ye=_(U),Ae=r.get(we).__webglTexture;n.bindTexture(ye,Ae),g(ye),n.unbindTexture()}}}const G=[],Q=[];function V(U){if(U.samples>0){if(ie(U)===!1){const R=U.textures,re=U.width,xe=U.height;let we=t.COLOR_BUFFER_BIT;const ye=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Ae=r.get(U),ve=R.length>1;if(ve)for(let Fe=0;Fe<R.length;Fe++)n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,Ae.__webglMultisampledFramebuffer);const Te=U.texture.mipmaps;Te&&Te.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglFramebuffer);for(let Fe=0;Fe<R.length;Fe++){if(U.resolveDepthBuffer&&(U.depthBuffer&&(we|=t.DEPTH_BUFFER_BIT),U.stencilBuffer&&U.resolveStencilBuffer&&(we|=t.STENCIL_BUFFER_BIT)),ve){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,Ae.__webglColorRenderbuffer[Fe]);const Ee=r.get(R[Fe]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Ee,0)}t.blitFramebuffer(0,0,re,xe,0,0,re,xe,we,t.NEAREST),c===!0&&(G.length=0,Q.length=0,G.push(t.COLOR_ATTACHMENT0+Fe),U.depthBuffer&&U.resolveDepthBuffer===!1&&(G.push(ye),Q.push(ye),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,Q)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,G))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),ve)for(let Fe=0;Fe<R.length;Fe++){n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.RENDERBUFFER,Ae.__webglColorRenderbuffer[Fe]);const Ee=r.get(R[Fe]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.TEXTURE_2D,Ee,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglMultisampledFramebuffer)}else if(U.depthBuffer&&U.resolveDepthBuffer===!1&&c){const R=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[R])}}}function J(U){return Math.min(i.maxSamples,U.samples)}function ie(U){const R=r.get(U);return U.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function he(U){const R=o.render.frame;u.get(U)!==R&&(u.set(U,R),U.update())}function fe(U,R){const re=U.colorSpace,xe=U.format,we=U.type;return U.isCompressedTexture===!0||U.isVideoTexture===!0||re!==Cx&&re!==uh&&(Cr.getTransfer(re)===Hr?(xe!==Tc||we!==Cd)&&Un("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Xa("WebGLTextures: Unsupported texture color space:",re)),R}function se(U){return typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement?(d.width=U.naturalWidth||U.width,d.height=U.naturalHeight||U.height):typeof VideoFrame<"u"&&U instanceof VideoFrame?(d.width=U.displayWidth,d.height=U.displayHeight):(d.width=U.width,d.height=U.height),d}this.allocateTextureUnit=X,this.resetTextureUnits=I,this.setTexture2D=te,this.setTexture2DArray=ae,this.setTexture3D=ee,this.setTextureCube=me,this.rebindTextures=q,this.setupRenderTarget=de,this.updateRenderTargetMipmap=O,this.updateMultisampleRenderTarget=V,this.setupDepthRenderbuffer=W,this.setupFrameBufferTexture=D,this.useMultisampledRTT=ie}function b1e(t,e){function n(r,i=uh){let s;const o=Cr.getTransfer(i);if(r===Cd)return t.UNSIGNED_BYTE;if(r===kO)return t.UNSIGNED_SHORT_4_4_4_4;if(r===NO)return t.UNSIGNED_SHORT_5_5_5_1;if(r===zQ)return t.UNSIGNED_INT_5_9_9_9_REV;if(r===UQ)return t.UNSIGNED_INT_10F_11F_11F_REV;if(r===OQ)return t.BYTE;if(r===IQ)return t.SHORT;if(r===I0)return t.UNSIGNED_SHORT;if(r===_O)return t.INT;if(r===Hf)return t.UNSIGNED_INT;if(r===Mu)return t.FLOAT;if(r===ry)return t.HALF_FLOAT;if(r===BQ)return t.ALPHA;if(r===HQ)return t.RGB;if(r===Tc)return t.RGBA;if(r===U0)return t.DEPTH_COMPONENT;if(r===B0)return t.DEPTH_STENCIL;if(r===qQ)return t.RED;if(r===CO)return t.RED_INTEGER;if(r===PO)return t.RG;if(r===TO)return t.RG_INTEGER;if(r===AO)return t.RGBA_INTEGER;if(r===vk||r===wk||r===Sk||r===_k)if(o===Hr)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===vk)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===wk)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===Sk)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===_k)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===vk)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===wk)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===Sk)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===_k)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===lF||r===cF||r===dF||r===uF)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===lF)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===cF)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===dF)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===uF)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===mF||r===hF||r===pF)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===mF||r===hF)return o===Hr?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===pF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===fF||r===gF||r===bF||r===xF||r===yF||r===vF||r===wF||r===SF||r===_F||r===kF||r===NF||r===CF||r===PF||r===TF)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===fF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===gF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===bF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===xF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===yF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===vF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===wF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===SF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===_F)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===kF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===NF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===CF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===PF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===TF)return o===Hr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===AF||r===MF||r===jF)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===AF)return o===Hr?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===MF)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===jF)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===EF||r===DF||r===FF||r===RF)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===EF)return s.COMPRESSED_RED_RGTC1_EXT;if(r===DF)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===FF)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===RF)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===z0?t.UNSIGNED_INT_24_8:t[r]!==void 0?t[r]:null}return{convert:n}}const x1e=`
  3846. void main() {
  3847. gl_Position = vec4( position, 1.0 );
  3848. }`,y1e=`
  3849. uniform sampler2DArray depthColor;
  3850. uniform float depthWidth;
  3851. uniform float depthHeight;
  3852. void main() {
  3853. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  3854. if ( coord.x >= 1.0 ) {
  3855. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  3856. } else {
  3857. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  3858. }
  3859. }`;class v1e{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const r=new dZ(e.texture);(e.depthNear!==n.depthNear||e.depthFar!==n.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=r}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,r=new Xu({vertexShader:x1e,fragmentShader:y1e,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new Zl(new RO(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}let w1e=class extends dg{constructor(e,n){super();const r=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,y=null;const v=typeof XRWebGLBinding<"u",b=new v1e,g={},_=n.getContextAttributes();let k=null,P=null;const N=[],M=[],A=new tr;let T=null;const C=new Rl;C.viewport=new ii;const F=new Rl;F.viewport=new ii;const $=[C,F],I=new Ive;let X=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(B){let Y=N[B];return Y===void 0&&(Y=new Lj,N[B]=Y),Y.getTargetRaySpace()},this.getControllerGrip=function(B){let Y=N[B];return Y===void 0&&(Y=new Lj,N[B]=Y),Y.getGripSpace()},this.getHand=function(B){let Y=N[B];return Y===void 0&&(Y=new Lj,N[B]=Y),Y.getHandSpace()};function te(B){const Y=M.indexOf(B.inputSource);if(Y===-1)return;const D=N[Y];D!==void 0&&(D.update(B.inputSource,B.frame,d||o),D.dispatchEvent({type:B.type,data:B.inputSource}))}function ae(){i.removeEventListener("select",te),i.removeEventListener("selectstart",te),i.removeEventListener("selectend",te),i.removeEventListener("squeeze",te),i.removeEventListener("squeezestart",te),i.removeEventListener("squeezeend",te),i.removeEventListener("end",ae),i.removeEventListener("inputsourceschange",ee);for(let B=0;B<N.length;B++){const Y=M[B];Y!==null&&(M[B]=null,N[B].disconnect(Y))}X=null,L=null,b.reset();for(const B in g)delete g[B];e.setRenderTarget(k),f=null,p=null,m=null,i=null,P=null,_e.stop(),r.isPresenting=!1,e.setPixelRatio(T),e.setSize(A.width,A.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(B){s=B,r.isPresenting===!0&&Un("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(B){l=B,r.isPresenting===!0&&Un("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||o},this.setReferenceSpace=function(B){d=B},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m===null&&v&&(m=new XRWebGLBinding(i,n)),m},this.getFrame=function(){return y},this.getSession=function(){return i},this.setSession=async function(B){if(i=B,i!==null){if(k=e.getRenderTarget(),i.addEventListener("select",te),i.addEventListener("selectstart",te),i.addEventListener("selectend",te),i.addEventListener("squeeze",te),i.addEventListener("squeezestart",te),i.addEventListener("squeezeend",te),i.addEventListener("end",ae),i.addEventListener("inputsourceschange",ee),_.xrCompatible!==!0&&await n.makeXRCompatible(),T=e.getPixelRatio(),e.getSize(A),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let D=null,j=null,z=null;_.depth&&(z=_.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,D=_.stencil?B0:U0,j=_.stencil?z0:Hf);const W={colorFormat:n.RGBA8,depthFormat:z,scaleFactor:s};m=this.getBinding(),p=m.createProjectionLayer(W),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),P=new $f(p.textureWidth,p.textureHeight,{format:Tc,type:Cd,depthTexture:new cZ(p.textureWidth,p.textureHeight,j,void 0,void 0,void 0,void 0,void 0,void 0,D),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}else{const D={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,D),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),P=new $f(f.framebufferWidth,f.framebufferHeight,{format:Tc,type:Cd,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}P.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),_e.setContext(i),_e.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return b.getDepthTexture()};function ee(B){for(let Y=0;Y<B.removed.length;Y++){const D=B.removed[Y],j=M.indexOf(D);j>=0&&(M[j]=null,N[j].disconnect(D))}for(let Y=0;Y<B.added.length;Y++){const D=B.added[Y];let j=M.indexOf(D);if(j===-1){for(let W=0;W<N.length;W++)if(W>=M.length){M.push(D),j=W;break}else if(M[W]===null){M[W]=D,j=W;break}if(j===-1)break}const z=N[j];z&&z.connect(D)}}const me=new At,le=new At;function ue(B,Y,D){me.setFromMatrixPosition(Y.matrixWorld),le.setFromMatrixPosition(D.matrixWorld);const j=me.distanceTo(le),z=Y.projectionMatrix.elements,W=D.projectionMatrix.elements,q=z[14]/(z[10]-1),de=z[14]/(z[10]+1),O=(z[9]+1)/z[5],G=(z[9]-1)/z[5],Q=(z[8]-1)/z[0],V=(W[8]+1)/W[0],J=q*Q,ie=q*V,he=j/(-Q+V),fe=he*-Q;if(Y.matrixWorld.decompose(B.position,B.quaternion,B.scale),B.translateX(fe),B.translateZ(he),B.matrixWorld.compose(B.position,B.quaternion,B.scale),B.matrixWorldInverse.copy(B.matrixWorld).invert(),z[10]===-1)B.projectionMatrix.copy(Y.projectionMatrix),B.projectionMatrixInverse.copy(Y.projectionMatrixInverse);else{const se=q+he,U=de+he,R=J-fe,re=ie+(j-fe),xe=O*de/U*se,we=G*de/U*se;B.projectionMatrix.makePerspective(R,re,xe,we,se,U),B.projectionMatrixInverse.copy(B.projectionMatrix).invert()}}function K(B,Y){Y===null?B.matrixWorld.copy(B.matrix):B.matrixWorld.multiplyMatrices(Y.matrixWorld,B.matrix),B.matrixWorldInverse.copy(B.matrixWorld).invert()}this.updateCamera=function(B){if(i===null)return;let Y=B.near,D=B.far;b.texture!==null&&(b.depthNear>0&&(Y=b.depthNear),b.depthFar>0&&(D=b.depthFar)),I.near=F.near=C.near=Y,I.far=F.far=C.far=D,(X!==I.near||L!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),X=I.near,L=I.far),I.layers.mask=B.layers.mask|6,C.layers.mask=I.layers.mask&3,F.layers.mask=I.layers.mask&5;const j=B.parent,z=I.cameras;K(I,j);for(let W=0;W<z.length;W++)K(z[W],j);z.length===2?ue(I,C,F):I.projectionMatrix.copy(C.projectionMatrix),ne(B,I,j)};function ne(B,Y,D){D===null?B.matrix.copy(Y.matrixWorld):(B.matrix.copy(D.matrixWorld),B.matrix.invert(),B.matrix.multiply(Y.matrixWorld)),B.matrix.decompose(B.position,B.quaternion,B.scale),B.updateMatrixWorld(!0),B.projectionMatrix.copy(Y.projectionMatrix),B.projectionMatrixInverse.copy(Y.projectionMatrixInverse),B.isPerspectiveCamera&&(B.fov=LF*2*Math.atan(1/B.projectionMatrix.elements[5]),B.zoom=1)}this.getCamera=function(){return I},this.getFoveation=function(){if(!(p===null&&f===null))return c},this.setFoveation=function(B){c=B,p!==null&&(p.fixedFoveation=B),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=B)},this.hasDepthSensing=function(){return b.texture!==null},this.getDepthSensingMesh=function(){return b.getMesh(I)},this.getCameraTexture=function(B){return g[B]};let oe=null;function be(B,Y){if(u=Y.getViewerPose(d||o),y=Y,u!==null){const D=u.views;f!==null&&(e.setRenderTargetFramebuffer(P,f.framebuffer),e.setRenderTarget(P));let j=!1;D.length!==I.cameras.length&&(I.cameras.length=0,j=!0);for(let de=0;de<D.length;de++){const O=D[de];let G=null;if(f!==null)G=f.getViewport(O);else{const V=m.getViewSubImage(p,O);G=V.viewport,de===0&&(e.setRenderTargetTextures(P,V.colorTexture,V.depthStencilTexture),e.setRenderTarget(P))}let Q=$[de];Q===void 0&&(Q=new Rl,Q.layers.enable(de),Q.viewport=new ii,$[de]=Q),Q.matrix.fromArray(O.transform.matrix),Q.matrix.decompose(Q.position,Q.quaternion,Q.scale),Q.projectionMatrix.fromArray(O.projectionMatrix),Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert(),Q.viewport.set(G.x,G.y,G.width,G.height),de===0&&(I.matrix.copy(Q.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale)),j===!0&&I.cameras.push(Q)}const z=i.enabledFeatures;if(z&&z.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&v){m=r.getBinding();const de=m.getDepthInformation(D[0]);de&&de.isValid&&de.texture&&b.init(de,i.renderState)}if(z&&z.includes("camera-access")&&v){e.state.unbindTexture(),m=r.getBinding();for(let de=0;de<D.length;de++){const O=D[de].camera;if(O){let G=g[O];G||(G=new dZ,g[O]=G);const Q=m.getCameraImage(O);G.sourceTexture=Q}}}}for(let D=0;D<N.length;D++){const j=M[D],z=N[D];j!==null&&z!==void 0&&z.update(j,Y,d||o)}oe&&oe(B,Y),Y.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:Y}),y=null}const _e=new fZ;_e.setAnimationLoop(be),this.setAnimationLoop=function(B){oe=B},this.dispose=function(){}}};const Lp=new Vh,S1e=new ci;function _1e(t,e){function n(b,g){b.matrixAutoUpdate===!0&&b.updateMatrix(),g.value.copy(b.matrix)}function r(b,g){g.color.getRGB(b.fogColor.value,iZ(t)),g.isFog?(b.fogNear.value=g.near,b.fogFar.value=g.far):g.isFogExp2&&(b.fogDensity.value=g.density)}function i(b,g,_,k,P){g.isMeshBasicMaterial||g.isMeshLambertMaterial?s(b,g):g.isMeshToonMaterial?(s(b,g),m(b,g)):g.isMeshPhongMaterial?(s(b,g),u(b,g)):g.isMeshStandardMaterial?(s(b,g),p(b,g),g.isMeshPhysicalMaterial&&f(b,g,P)):g.isMeshMatcapMaterial?(s(b,g),y(b,g)):g.isMeshDepthMaterial?s(b,g):g.isMeshDistanceMaterial?(s(b,g),v(b,g)):g.isMeshNormalMaterial?s(b,g):g.isLineBasicMaterial?(o(b,g),g.isLineDashedMaterial&&l(b,g)):g.isPointsMaterial?c(b,g,_,k):g.isSpriteMaterial?d(b,g):g.isShadowMaterial?(b.color.value.copy(g.color),b.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function s(b,g){b.opacity.value=g.opacity,g.color&&b.diffuse.value.copy(g.color),g.emissive&&b.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.bumpMap&&(b.bumpMap.value=g.bumpMap,n(g.bumpMap,b.bumpMapTransform),b.bumpScale.value=g.bumpScale,g.side===Co&&(b.bumpScale.value*=-1)),g.normalMap&&(b.normalMap.value=g.normalMap,n(g.normalMap,b.normalMapTransform),b.normalScale.value.copy(g.normalScale),g.side===Co&&b.normalScale.value.negate()),g.displacementMap&&(b.displacementMap.value=g.displacementMap,n(g.displacementMap,b.displacementMapTransform),b.displacementScale.value=g.displacementScale,b.displacementBias.value=g.displacementBias),g.emissiveMap&&(b.emissiveMap.value=g.emissiveMap,n(g.emissiveMap,b.emissiveMapTransform)),g.specularMap&&(b.specularMap.value=g.specularMap,n(g.specularMap,b.specularMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest);const _=e.get(g),k=_.envMap,P=_.envMapRotation;k&&(b.envMap.value=k,Lp.copy(P),Lp.x*=-1,Lp.y*=-1,Lp.z*=-1,k.isCubeTexture&&k.isRenderTargetTexture===!1&&(Lp.y*=-1,Lp.z*=-1),b.envMapRotation.value.setFromMatrix4(S1e.makeRotationFromEuler(Lp)),b.flipEnvMap.value=k.isCubeTexture&&k.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=g.reflectivity,b.ior.value=g.ior,b.refractionRatio.value=g.refractionRatio),g.lightMap&&(b.lightMap.value=g.lightMap,b.lightMapIntensity.value=g.lightMapIntensity,n(g.lightMap,b.lightMapTransform)),g.aoMap&&(b.aoMap.value=g.aoMap,b.aoMapIntensity.value=g.aoMapIntensity,n(g.aoMap,b.aoMapTransform))}function o(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform))}function l(b,g){b.dashSize.value=g.dashSize,b.totalSize.value=g.dashSize+g.gapSize,b.scale.value=g.scale}function c(b,g,_,k){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.size.value=g.size*_,b.scale.value=k*.5,g.map&&(b.map.value=g.map,n(g.map,b.uvTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function d(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.rotation.value=g.rotation,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function u(b,g){b.specular.value.copy(g.specular),b.shininess.value=Math.max(g.shininess,1e-4)}function m(b,g){g.gradientMap&&(b.gradientMap.value=g.gradientMap)}function p(b,g){b.metalness.value=g.metalness,g.metalnessMap&&(b.metalnessMap.value=g.metalnessMap,n(g.metalnessMap,b.metalnessMapTransform)),b.roughness.value=g.roughness,g.roughnessMap&&(b.roughnessMap.value=g.roughnessMap,n(g.roughnessMap,b.roughnessMapTransform)),g.envMap&&(b.envMapIntensity.value=g.envMapIntensity)}function f(b,g,_){b.ior.value=g.ior,g.sheen>0&&(b.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),b.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(b.sheenColorMap.value=g.sheenColorMap,n(g.sheenColorMap,b.sheenColorMapTransform)),g.sheenRoughnessMap&&(b.sheenRoughnessMap.value=g.sheenRoughnessMap,n(g.sheenRoughnessMap,b.sheenRoughnessMapTransform))),g.clearcoat>0&&(b.clearcoat.value=g.clearcoat,b.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(b.clearcoatMap.value=g.clearcoatMap,n(g.clearcoatMap,b.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,n(g.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(b.clearcoatNormalMap.value=g.clearcoatNormalMap,n(g.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===Co&&b.clearcoatNormalScale.value.negate())),g.dispersion>0&&(b.dispersion.value=g.dispersion),g.iridescence>0&&(b.iridescence.value=g.iridescence,b.iridescenceIOR.value=g.iridescenceIOR,b.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(b.iridescenceMap.value=g.iridescenceMap,n(g.iridescenceMap,b.iridescenceMapTransform)),g.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=g.iridescenceThicknessMap,n(g.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),g.transmission>0&&(b.transmission.value=g.transmission,b.transmissionSamplerMap.value=_.texture,b.transmissionSamplerSize.value.set(_.width,_.height),g.transmissionMap&&(b.transmissionMap.value=g.transmissionMap,n(g.transmissionMap,b.transmissionMapTransform)),b.thickness.value=g.thickness,g.thicknessMap&&(b.thicknessMap.value=g.thicknessMap,n(g.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=g.attenuationDistance,b.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(b.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(b.anisotropyMap.value=g.anisotropyMap,n(g.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=g.specularIntensity,b.specularColor.value.copy(g.specularColor),g.specularColorMap&&(b.specularColorMap.value=g.specularColorMap,n(g.specularColorMap,b.specularColorMapTransform)),g.specularIntensityMap&&(b.specularIntensityMap.value=g.specularIntensityMap,n(g.specularIntensityMap,b.specularIntensityMapTransform))}function y(b,g){g.matcap&&(b.matcap.value=g.matcap)}function v(b,g){const _=e.get(g).light;b.referencePosition.value.setFromMatrixPosition(_.matrixWorld),b.nearDistance.value=_.shadow.camera.near,b.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function k1e(t,e,n,r){let i={},s={},o=[];const l=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function c(_,k){const P=k.program;r.uniformBlockBinding(_,P)}function d(_,k){let P=i[_.id];P===void 0&&(y(_),P=u(_),i[_.id]=P,_.addEventListener("dispose",b));const N=k.program;r.updateUBOMapping(_,N);const M=e.render.frame;s[_.id]!==M&&(p(_),s[_.id]=M)}function u(_){const k=m();_.__bindingPointIndex=k;const P=t.createBuffer(),N=_.__size,M=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,P),t.bufferData(t.UNIFORM_BUFFER,N,M),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,k,P),P}function m(){for(let _=0;_<l;_++)if(o.indexOf(_)===-1)return o.push(_),_;return Xa("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function p(_){const k=i[_.id],P=_.uniforms,N=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,k);for(let M=0,A=P.length;M<A;M++){const T=Array.isArray(P[M])?P[M]:[P[M]];for(let C=0,F=T.length;C<F;C++){const $=T[C];if(f($,M,C,N)===!0){const I=$.__offset,X=Array.isArray($.value)?$.value:[$.value];let L=0;for(let te=0;te<X.length;te++){const ae=X[te],ee=v(ae);typeof ae=="number"||typeof ae=="boolean"?($.__data[0]=ae,t.bufferSubData(t.UNIFORM_BUFFER,I+L,$.__data)):ae.isMatrix3?($.__data[0]=ae.elements[0],$.__data[1]=ae.elements[1],$.__data[2]=ae.elements[2],$.__data[3]=0,$.__data[4]=ae.elements[3],$.__data[5]=ae.elements[4],$.__data[6]=ae.elements[5],$.__data[7]=0,$.__data[8]=ae.elements[6],$.__data[9]=ae.elements[7],$.__data[10]=ae.elements[8],$.__data[11]=0):(ae.toArray($.__data,L),L+=ee.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,I,$.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(_,k,P,N){const M=_.value,A=k+"_"+P;if(N[A]===void 0)return typeof M=="number"||typeof M=="boolean"?N[A]=M:N[A]=M.clone(),!0;{const T=N[A];if(typeof M=="number"||typeof M=="boolean"){if(T!==M)return N[A]=M,!0}else if(T.equals(M)===!1)return T.copy(M),!0}return!1}function y(_){const k=_.uniforms;let P=0;const N=16;for(let A=0,T=k.length;A<T;A++){const C=Array.isArray(k[A])?k[A]:[k[A]];for(let F=0,$=C.length;F<$;F++){const I=C[F],X=Array.isArray(I.value)?I.value:[I.value];for(let L=0,te=X.length;L<te;L++){const ae=X[L],ee=v(ae),me=P%N,le=me%ee.boundary,ue=me+le;P+=le,ue!==0&&N-ue<ee.storage&&(P+=N-ue),I.__data=new Float32Array(ee.storage/Float32Array.BYTES_PER_ELEMENT),I.__offset=P,P+=ee.storage}}}const M=P%N;return M>0&&(P+=N-M),_.__size=P,_.__cache={},this}function v(_){const k={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(k.boundary=4,k.storage=4):_.isVector2?(k.boundary=8,k.storage=8):_.isVector3||_.isColor?(k.boundary=16,k.storage=12):_.isVector4?(k.boundary=16,k.storage=16):_.isMatrix3?(k.boundary=48,k.storage=48):_.isMatrix4?(k.boundary=64,k.storage=64):_.isTexture?Un("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Un("WebGLRenderer: Unsupported uniform value type.",_),k}function b(_){const k=_.target;k.removeEventListener("dispose",b);const P=o.indexOf(k.__bindingPointIndex);o.splice(P,1),t.deleteBuffer(i[k.id]),delete i[k.id],delete s[k.id]}function g(){for(const _ in i)t.deleteBuffer(i[_]);o=[],i={},s={}}return{bind:c,update:d,dispose:g}}const N1e=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 ou=null;function C1e(){return ou===null&&(ou=new _ve(N1e,32,32,PO,ry),ou.minFilter=Bl,ou.magFilter=Bl,ou.wrapS=Au,ou.wrapT=Au,ou.generateMipmaps=!1,ou.needsUpdate=!0),ou}let P1e=class{constructor(e={}){const{canvas:n=Kye(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:d=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:m=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let f;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=r.getContextAttributes().alpha}else f=o;const y=new Set([AO,TO,CO]),v=new Set([Cd,Hf,I0,z0,kO,NO]),b=new Uint32Array(4),g=new Int32Array(4);let _=null,k=null;const P=[],N=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Dh,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const M=this;let A=!1;this._outputColorSpace=Qo;let T=0,C=0,F=null,$=-1,I=null;const X=new ii,L=new ii;let te=null;const ae=new sr(0);let ee=0,me=n.width,le=n.height,ue=1,K=null,ne=null;const oe=new ii(0,0,me,le),be=new ii(0,0,me,le);let _e=!1;const B=new FO;let Y=!1,D=!1;const j=new ci,z=new At,W=new ii,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let de=!1;function O(){return F===null?ue:1}let G=r;function Q(Ce,We){return n.getContext(Ce,We)}try{const Ce={alpha:!0,depth:i,stencil:s,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:d,powerPreference:u,failIfMajorPerformanceCaveat:m};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${wO}`),n.addEventListener("webglcontextlost",$e,!1),n.addEventListener("webglcontextrestored",Pe,!1),n.addEventListener("webglcontextcreationerror",Me,!1),G===null){const We="webgl2";if(G=Q(We,Ce),G===null)throw Q(We)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(Ce){throw Ce("WebGLRenderer: "+Ce.message),Ce}let V,J,ie,he,fe,se,U,R,re,xe,we,ye,Ae,ve,Te,Fe,Ee,Se,je,qe,Re,Ye,ce,ze;function Ne(){V=new RSe(G),V.init(),Ye=new b1e(G,V),J=new CSe(G,V,e,Ye),ie=new f1e(G,V),J.reversedDepthBuffer&&p&&ie.buffers.depth.setReversed(!0),he=new ISe(G),fe=new n1e,se=new g1e(G,V,ie,fe,J,Ye,he),U=new TSe(M),R=new FSe(M),re=new Hve(G),ce=new kSe(G,re),xe=new LSe(G,re,he,ce),we=new USe(G,xe,re,he),je=new zSe(G,J,se),Fe=new PSe(fe),ye=new t1e(M,U,R,V,J,ce,Fe),Ae=new _1e(M,fe),ve=new a1e,Te=new d1e(V),Se=new _Se(M,U,R,ie,we,f,c),Ee=new h1e(M,we,J),ze=new k1e(G,he,J,ie),qe=new NSe(G,V,he),Re=new OSe(G,V,he),he.programs=ye.programs,M.capabilities=J,M.extensions=V,M.properties=fe,M.renderLists=ve,M.shadowMap=Ee,M.state=ie,M.info=he}Ne();const Ge=new w1e(M,G);this.xr=Ge,this.getContext=function(){return G},this.getContextAttributes=function(){return G.getContextAttributes()},this.forceContextLoss=function(){const Ce=V.get("WEBGL_lose_context");Ce&&Ce.loseContext()},this.forceContextRestore=function(){const Ce=V.get("WEBGL_lose_context");Ce&&Ce.restoreContext()},this.getPixelRatio=function(){return ue},this.setPixelRatio=function(Ce){Ce!==void 0&&(ue=Ce,this.setSize(me,le,!1))},this.getSize=function(Ce){return Ce.set(me,le)},this.setSize=function(Ce,We,Xe=!0){if(Ge.isPresenting){Un("WebGLRenderer: Can't change size while VR device is presenting.");return}me=Ce,le=We,n.width=Math.floor(Ce*ue),n.height=Math.floor(We*ue),Xe===!0&&(n.style.width=Ce+"px",n.style.height=We+"px"),this.setViewport(0,0,Ce,We)},this.getDrawingBufferSize=function(Ce){return Ce.set(me*ue,le*ue).floor()},this.setDrawingBufferSize=function(Ce,We,Xe){me=Ce,le=We,ue=Xe,n.width=Math.floor(Ce*Xe),n.height=Math.floor(We*Xe),this.setViewport(0,0,Ce,We)},this.getCurrentViewport=function(Ce){return Ce.copy(X)},this.getViewport=function(Ce){return Ce.copy(oe)},this.setViewport=function(Ce,We,Xe,Qe){Ce.isVector4?oe.set(Ce.x,Ce.y,Ce.z,Ce.w):oe.set(Ce,We,Xe,Qe),ie.viewport(X.copy(oe).multiplyScalar(ue).round())},this.getScissor=function(Ce){return Ce.copy(be)},this.setScissor=function(Ce,We,Xe,Qe){Ce.isVector4?be.set(Ce.x,Ce.y,Ce.z,Ce.w):be.set(Ce,We,Xe,Qe),ie.scissor(L.copy(be).multiplyScalar(ue).round())},this.getScissorTest=function(){return _e},this.setScissorTest=function(Ce){ie.setScissorTest(_e=Ce)},this.setOpaqueSort=function(Ce){K=Ce},this.setTransparentSort=function(Ce){ne=Ce},this.getClearColor=function(Ce){return Ce.copy(Se.getClearColor())},this.setClearColor=function(){Se.setClearColor(...arguments)},this.getClearAlpha=function(){return Se.getClearAlpha()},this.setClearAlpha=function(){Se.setClearAlpha(...arguments)},this.clear=function(Ce=!0,We=!0,Xe=!0){let Qe=0;if(Ce){let Ze=!1;if(F!==null){const rt=F.texture.format;Ze=y.has(rt)}if(Ze){const rt=F.texture.type,bt=v.has(rt),Pt=Se.getClearColor(),vt=Se.getClearAlpha(),He=Pt.r,St=Pt.g,Ct=Pt.b;bt?(b[0]=He,b[1]=St,b[2]=Ct,b[3]=vt,G.clearBufferuiv(G.COLOR,0,b)):(g[0]=He,g[1]=St,g[2]=Ct,g[3]=vt,G.clearBufferiv(G.COLOR,0,g))}else Qe|=G.COLOR_BUFFER_BIT}We&&(Qe|=G.DEPTH_BUFFER_BIT),Xe&&(Qe|=G.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),G.clear(Qe)},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",$e,!1),n.removeEventListener("webglcontextrestored",Pe,!1),n.removeEventListener("webglcontextcreationerror",Me,!1),Se.dispose(),ve.dispose(),Te.dispose(),fe.dispose(),U.dispose(),R.dispose(),we.dispose(),ce.dispose(),ze.dispose(),ye.dispose(),Ge.dispose(),Ge.removeEventListener("sessionstart",Xt),Ge.removeEventListener("sessionend",Kt),Ut.stop()};function $e(Ce){Ce.preventDefault(),A6("WebGLRenderer: Context Lost."),A=!0}function Pe(){A6("WebGLRenderer: Context Restored."),A=!1;const Ce=he.autoReset,We=Ee.enabled,Xe=Ee.autoUpdate,Qe=Ee.needsUpdate,Ze=Ee.type;Ne(),he.autoReset=Ce,Ee.enabled=We,Ee.autoUpdate=Xe,Ee.needsUpdate=Qe,Ee.type=Ze}function Me(Ce){Xa("WebGLRenderer: A WebGL context could not be created. Reason: ",Ce.statusMessage)}function Ve(Ce){const We=Ce.target;We.removeEventListener("dispose",Ve),tt(We)}function tt(Ce){ut(Ce),fe.remove(Ce)}function ut(Ce){const We=fe.get(Ce).programs;We!==void 0&&(We.forEach(function(Xe){ye.releaseProgram(Xe)}),Ce.isShaderMaterial&&ye.releaseShaderCache(Ce))}this.renderBufferDirect=function(Ce,We,Xe,Qe,Ze,rt){We===null&&(We=q);const bt=Ze.isMesh&&Ze.matrixWorld.determinant()<0,Pt=Ue(Ce,We,Xe,Qe,Ze);ie.setMaterial(Qe,bt);let vt=Xe.index,He=1;if(Qe.wireframe===!0){if(vt=xe.getWireframeAttribute(Xe),vt===void 0)return;He=2}const St=Xe.drawRange,Ct=Xe.attributes.position;let Zt=St.start*He,Jt=(St.start+St.count)*He;rt!==null&&(Zt=Math.max(Zt,rt.start*He),Jt=Math.min(Jt,(rt.start+rt.count)*He)),vt!==null?(Zt=Math.max(Zt,0),Jt=Math.min(Jt,vt.count)):Ct!=null&&(Zt=Math.max(Zt,0),Jt=Math.min(Jt,Ct.count));const Nn=Jt-Zt;if(Nn<0||Nn===1/0)return;ce.setup(Ze,Qe,Pt,Xe,vt);let vn,yn=qe;if(vt!==null&&(vn=re.get(vt),yn=Re,yn.setIndex(vn)),Ze.isMesh)Qe.wireframe===!0?(ie.setLineWidth(Qe.wireframeLinewidth*O()),yn.setMode(G.LINES)):yn.setMode(G.TRIANGLES);else if(Ze.isLine){let an=Qe.linewidth;an===void 0&&(an=1),ie.setLineWidth(an*O()),Ze.isLineSegments?yn.setMode(G.LINES):Ze.isLineLoop?yn.setMode(G.LINE_LOOP):yn.setMode(G.LINE_STRIP)}else Ze.isPoints?yn.setMode(G.POINTS):Ze.isSprite&&yn.setMode(G.TRIANGLES);if(Ze.isBatchedMesh)if(Ze._multiDrawInstances!==null)H0("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),yn.renderMultiDrawInstances(Ze._multiDrawStarts,Ze._multiDrawCounts,Ze._multiDrawCount,Ze._multiDrawInstances);else if(V.get("WEBGL_multi_draw"))yn.renderMultiDraw(Ze._multiDrawStarts,Ze._multiDrawCounts,Ze._multiDrawCount);else{const an=Ze._multiDrawStarts,rn=Ze._multiDrawCounts,bn=Ze._multiDrawCount,Gn=vt?re.get(vt).bytesPerElement:1,ar=fe.get(Qe).currentProgram.getUniforms();for(let On=0;On<bn;On++)ar.setValue(G,"_gl_DrawID",On),yn.render(an[On]/Gn,rn[On])}else if(Ze.isInstancedMesh)yn.renderInstances(Zt,Nn,Ze.count);else if(Xe.isInstancedBufferGeometry){const an=Xe._maxInstanceCount!==void 0?Xe._maxInstanceCount:1/0,rn=Math.min(Xe.instanceCount,an);yn.renderInstances(Zt,Nn,rn)}else yn.render(Zt,Nn)};function xt(Ce,We,Xe){Ce.transparent===!0&&Ce.side===ud&&Ce.forceSinglePass===!1?(Ce.side=Co,Ce.needsUpdate=!0,Mt(Ce,We,Xe),Ce.side=$h,Ce.needsUpdate=!0,Mt(Ce,We,Xe),Ce.side=ud):Mt(Ce,We,Xe)}this.compile=function(Ce,We,Xe=null){Xe===null&&(Xe=Ce),k=Te.get(Xe),k.init(We),N.push(k),Xe.traverseVisible(function(Ze){Ze.isLight&&Ze.layers.test(We.layers)&&(k.pushLight(Ze),Ze.castShadow&&k.pushShadow(Ze))}),Ce!==Xe&&Ce.traverseVisible(function(Ze){Ze.isLight&&Ze.layers.test(We.layers)&&(k.pushLight(Ze),Ze.castShadow&&k.pushShadow(Ze))}),k.setupLights();const Qe=new Set;return Ce.traverse(function(Ze){if(!(Ze.isMesh||Ze.isPoints||Ze.isLine||Ze.isSprite))return;const rt=Ze.material;if(rt)if(Array.isArray(rt))for(let bt=0;bt<rt.length;bt++){const Pt=rt[bt];xt(Pt,Xe,Ze),Qe.add(Pt)}else xt(rt,Xe,Ze),Qe.add(rt)}),k=N.pop(),Qe},this.compileAsync=function(Ce,We,Xe=null){const Qe=this.compile(Ce,We,Xe);return new Promise(Ze=>{function rt(){if(Qe.forEach(function(bt){fe.get(bt).currentProgram.isReady()&&Qe.delete(bt)}),Qe.size===0){Ze(Ce);return}setTimeout(rt,10)}V.get("KHR_parallel_shader_compile")!==null?rt():setTimeout(rt,10)})};let wt=null;function Ht(Ce){wt&&wt(Ce)}function Xt(){Ut.stop()}function Kt(){Ut.start()}const Ut=new fZ;Ut.setAnimationLoop(Ht),typeof self<"u"&&Ut.setContext(self),this.setAnimationLoop=function(Ce){wt=Ce,Ge.setAnimationLoop(Ce),Ce===null?Ut.stop():Ut.start()},Ge.addEventListener("sessionstart",Xt),Ge.addEventListener("sessionend",Kt),this.render=function(Ce,We){if(We!==void 0&&We.isCamera!==!0){Xa("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(A===!0)return;if(Ce.matrixWorldAutoUpdate===!0&&Ce.updateMatrixWorld(),We.parent===null&&We.matrixWorldAutoUpdate===!0&&We.updateMatrixWorld(),Ge.enabled===!0&&Ge.isPresenting===!0&&(Ge.cameraAutoUpdate===!0&&Ge.updateCamera(We),We=Ge.getCamera()),Ce.isScene===!0&&Ce.onBeforeRender(M,Ce,We,F),k=Te.get(Ce,N.length),k.init(We),N.push(k),j.multiplyMatrices(We.projectionMatrix,We.matrixWorldInverse),B.setFromProjectionMatrix(j,pd,We.reversedDepth),D=this.localClippingEnabled,Y=Fe.init(this.clippingPlanes,D),_=ve.get(Ce,P.length),_.init(),P.push(_),Ge.enabled===!0&&Ge.isPresenting===!0){const rt=M.xr.getDepthSensingMesh();rt!==null&&en(rt,We,-1/0,M.sortObjects)}en(Ce,We,0,M.sortObjects),_.finish(),M.sortObjects===!0&&_.sort(K,ne),de=Ge.enabled===!1||Ge.isPresenting===!1||Ge.hasDepthSensing()===!1,de&&Se.addToRenderList(_,Ce),this.info.render.frame++,Y===!0&&Fe.beginShadows();const Xe=k.state.shadowsArray;Ee.render(Xe,Ce,We),Y===!0&&Fe.endShadows(),this.info.autoReset===!0&&this.info.reset();const Qe=_.opaque,Ze=_.transmissive;if(k.setupLights(),We.isArrayCamera){const rt=We.cameras;if(Ze.length>0)for(let bt=0,Pt=rt.length;bt<Pt;bt++){const vt=rt[bt];Ft(Qe,Ze,Ce,vt)}de&&Se.render(Ce);for(let bt=0,Pt=rt.length;bt<Pt;bt++){const vt=rt[bt];Ke(_,Ce,vt,vt.viewport)}}else Ze.length>0&&Ft(Qe,Ze,Ce,We),de&&Se.render(Ce),Ke(_,Ce,We);F!==null&&C===0&&(se.updateMultisampleRenderTarget(F),se.updateRenderTargetMipmap(F)),Ce.isScene===!0&&Ce.onAfterRender(M,Ce,We),ce.resetDefaultState(),$=-1,I=null,N.pop(),N.length>0?(k=N[N.length-1],Y===!0&&Fe.setGlobalState(M.clippingPlanes,k.state.camera)):k=null,P.pop(),P.length>0?_=P[P.length-1]:_=null};function en(Ce,We,Xe,Qe){if(Ce.visible===!1)return;if(Ce.layers.test(We.layers)){if(Ce.isGroup)Xe=Ce.renderOrder;else if(Ce.isLOD)Ce.autoUpdate===!0&&Ce.update(We);else if(Ce.isLight)k.pushLight(Ce),Ce.castShadow&&k.pushShadow(Ce);else if(Ce.isSprite){if(!Ce.frustumCulled||B.intersectsSprite(Ce)){Qe&&W.setFromMatrixPosition(Ce.matrixWorld).applyMatrix4(j);const bt=we.update(Ce),Pt=Ce.material;Pt.visible&&_.push(Ce,bt,Pt,Xe,W.z,null)}}else if((Ce.isMesh||Ce.isLine||Ce.isPoints)&&(!Ce.frustumCulled||B.intersectsObject(Ce))){const bt=we.update(Ce),Pt=Ce.material;if(Qe&&(Ce.boundingSphere!==void 0?(Ce.boundingSphere===null&&Ce.computeBoundingSphere(),W.copy(Ce.boundingSphere.center)):(bt.boundingSphere===null&&bt.computeBoundingSphere(),W.copy(bt.boundingSphere.center)),W.applyMatrix4(Ce.matrixWorld).applyMatrix4(j)),Array.isArray(Pt)){const vt=bt.groups;for(let He=0,St=vt.length;He<St;He++){const Ct=vt[He],Zt=Pt[Ct.materialIndex];Zt&&Zt.visible&&_.push(Ce,bt,Zt,Xe,W.z,Ct)}}else Pt.visible&&_.push(Ce,bt,Pt,Xe,W.z,null)}}const rt=Ce.children;for(let bt=0,Pt=rt.length;bt<Pt;bt++)en(rt[bt],We,Xe,Qe)}function Ke(Ce,We,Xe,Qe){const{opaque:Ze,transmissive:rt,transparent:bt}=Ce;k.setupLightsView(Xe),Y===!0&&Fe.setGlobalState(M.clippingPlanes,Xe),Qe&&ie.viewport(X.copy(Qe)),Ze.length>0&&Nt(Ze,We,Xe),rt.length>0&&Nt(rt,We,Xe),bt.length>0&&Nt(bt,We,Xe),ie.buffers.depth.setTest(!0),ie.buffers.depth.setMask(!0),ie.buffers.color.setMask(!0),ie.setPolygonOffset(!1)}function Ft(Ce,We,Xe,Qe){if((Xe.isScene===!0?Xe.overrideMaterial:null)!==null)return;k.state.transmissionRenderTarget[Qe.id]===void 0&&(k.state.transmissionRenderTarget[Qe.id]=new $f(1,1,{generateMipmaps:!0,type:V.has("EXT_color_buffer_half_float")||V.has("EXT_color_buffer_float")?ry:Cd,minFilter:sf,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Cr.workingColorSpace}));const rt=k.state.transmissionRenderTarget[Qe.id],bt=Qe.viewport||X;rt.setSize(bt.z*M.transmissionResolutionScale,bt.w*M.transmissionResolutionScale);const Pt=M.getRenderTarget(),vt=M.getActiveCubeFace(),He=M.getActiveMipmapLevel();M.setRenderTarget(rt),M.getClearColor(ae),ee=M.getClearAlpha(),ee<1&&M.setClearColor(16777215,.5),M.clear(),de&&Se.render(Xe);const St=M.toneMapping;M.toneMapping=Dh;const Ct=Qe.viewport;if(Qe.viewport!==void 0&&(Qe.viewport=void 0),k.setupLightsView(Qe),Y===!0&&Fe.setGlobalState(M.clippingPlanes,Qe),Nt(Ce,Xe,Qe),se.updateMultisampleRenderTarget(rt),se.updateRenderTargetMipmap(rt),V.has("WEBGL_multisampled_render_to_texture")===!1){let Zt=!1;for(let Jt=0,Nn=We.length;Jt<Nn;Jt++){const vn=We[Jt],{object:yn,geometry:an,material:rn,group:bn}=vn;if(rn.side===ud&&yn.layers.test(Qe.layers)){const Gn=rn.side;rn.side=Co,rn.needsUpdate=!0,ht(yn,Xe,Qe,an,rn,bn),rn.side=Gn,rn.needsUpdate=!0,Zt=!0}}Zt===!0&&(se.updateMultisampleRenderTarget(rt),se.updateRenderTargetMipmap(rt))}M.setRenderTarget(Pt,vt,He),M.setClearColor(ae,ee),Ct!==void 0&&(Qe.viewport=Ct),M.toneMapping=St}function Nt(Ce,We,Xe){const Qe=We.isScene===!0?We.overrideMaterial:null;for(let Ze=0,rt=Ce.length;Ze<rt;Ze++){const bt=Ce[Ze],{object:Pt,geometry:vt,group:He}=bt;let St=bt.material;St.allowOverride===!0&&Qe!==null&&(St=Qe),Pt.layers.test(Xe.layers)&&ht(Pt,We,Xe,vt,St,He)}}function ht(Ce,We,Xe,Qe,Ze,rt){Ce.onBeforeRender(M,We,Xe,Qe,Ze,rt),Ce.modelViewMatrix.multiplyMatrices(Xe.matrixWorldInverse,Ce.matrixWorld),Ce.normalMatrix.getNormalMatrix(Ce.modelViewMatrix),Ze.onBeforeRender(M,We,Xe,Qe,Ce,rt),Ze.transparent===!0&&Ze.side===ud&&Ze.forceSinglePass===!1?(Ze.side=Co,Ze.needsUpdate=!0,M.renderBufferDirect(Xe,We,Qe,Ze,Ce,rt),Ze.side=$h,Ze.needsUpdate=!0,M.renderBufferDirect(Xe,We,Qe,Ze,Ce,rt),Ze.side=ud):M.renderBufferDirect(Xe,We,Qe,Ze,Ce,rt),Ce.onAfterRender(M,We,Xe,Qe,Ze,rt)}function Mt(Ce,We,Xe){We.isScene!==!0&&(We=q);const Qe=fe.get(Ce),Ze=k.state.lights,rt=k.state.shadowsArray,bt=Ze.state.version,Pt=ye.getParameters(Ce,Ze.state,rt,We,Xe),vt=ye.getProgramCacheKey(Pt);let He=Qe.programs;Qe.environment=Ce.isMeshStandardMaterial?We.environment:null,Qe.fog=We.fog,Qe.envMap=(Ce.isMeshStandardMaterial?R:U).get(Ce.envMap||Qe.environment),Qe.envMapRotation=Qe.environment!==null&&Ce.envMap===null?We.environmentRotation:Ce.envMapRotation,He===void 0&&(Ce.addEventListener("dispose",Ve),He=new Map,Qe.programs=He);let St=He.get(vt);if(St!==void 0){if(Qe.currentProgram===St&&Qe.lightsStateVersion===bt)return Wt(Ce,Pt),St}else Pt.uniforms=ye.getUniforms(Ce),Ce.onBeforeCompile(Pt,M),St=ye.acquireProgram(Pt,vt),He.set(vt,St),Qe.uniforms=Pt.uniforms;const Ct=Qe.uniforms;return(!Ce.isShaderMaterial&&!Ce.isRawShaderMaterial||Ce.clipping===!0)&&(Ct.clippingPlanes=Fe.uniform),Wt(Ce,Pt),Qe.needsLights=pt(Ce),Qe.lightsStateVersion=bt,Qe.needsLights&&(Ct.ambientLightColor.value=Ze.state.ambient,Ct.lightProbe.value=Ze.state.probe,Ct.directionalLights.value=Ze.state.directional,Ct.directionalLightShadows.value=Ze.state.directionalShadow,Ct.spotLights.value=Ze.state.spot,Ct.spotLightShadows.value=Ze.state.spotShadow,Ct.rectAreaLights.value=Ze.state.rectArea,Ct.ltc_1.value=Ze.state.rectAreaLTC1,Ct.ltc_2.value=Ze.state.rectAreaLTC2,Ct.pointLights.value=Ze.state.point,Ct.pointLightShadows.value=Ze.state.pointShadow,Ct.hemisphereLights.value=Ze.state.hemi,Ct.directionalShadowMap.value=Ze.state.directionalShadowMap,Ct.directionalShadowMatrix.value=Ze.state.directionalShadowMatrix,Ct.spotShadowMap.value=Ze.state.spotShadowMap,Ct.spotLightMatrix.value=Ze.state.spotLightMatrix,Ct.spotLightMap.value=Ze.state.spotLightMap,Ct.pointShadowMap.value=Ze.state.pointShadowMap,Ct.pointShadowMatrix.value=Ze.state.pointShadowMatrix),Qe.currentProgram=St,Qe.uniformsList=null,St}function Qt(Ce){if(Ce.uniformsList===null){const We=Ce.currentProgram.getUniforms();Ce.uniformsList=Pk.seqWithValue(We.seq,Ce.uniforms)}return Ce.uniformsList}function Wt(Ce,We){const Xe=fe.get(Ce);Xe.outputColorSpace=We.outputColorSpace,Xe.batching=We.batching,Xe.batchingColor=We.batchingColor,Xe.instancing=We.instancing,Xe.instancingColor=We.instancingColor,Xe.instancingMorph=We.instancingMorph,Xe.skinning=We.skinning,Xe.morphTargets=We.morphTargets,Xe.morphNormals=We.morphNormals,Xe.morphColors=We.morphColors,Xe.morphTargetsCount=We.morphTargetsCount,Xe.numClippingPlanes=We.numClippingPlanes,Xe.numIntersection=We.numClipIntersection,Xe.vertexAlphas=We.vertexAlphas,Xe.vertexTangents=We.vertexTangents,Xe.toneMapping=We.toneMapping}function Ue(Ce,We,Xe,Qe,Ze){We.isScene!==!0&&(We=q),se.resetTextureUnits();const rt=We.fog,bt=Qe.isMeshStandardMaterial?We.environment:null,Pt=F===null?M.outputColorSpace:F.isXRRenderTarget===!0?F.texture.colorSpace:Cx,vt=(Qe.isMeshStandardMaterial?R:U).get(Qe.envMap||bt),He=Qe.vertexColors===!0&&!!Xe.attributes.color&&Xe.attributes.color.itemSize===4,St=!!Xe.attributes.tangent&&(!!Qe.normalMap||Qe.anisotropy>0),Ct=!!Xe.morphAttributes.position,Zt=!!Xe.morphAttributes.normal,Jt=!!Xe.morphAttributes.color;let Nn=Dh;Qe.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(Nn=M.toneMapping);const vn=Xe.morphAttributes.position||Xe.morphAttributes.normal||Xe.morphAttributes.color,yn=vn!==void 0?vn.length:0,an=fe.get(Qe),rn=k.state.lights;if(Y===!0&&(D===!0||Ce!==I)){const jr=Ce===I&&Qe.id===$;Fe.setState(Qe,Ce,jr)}let bn=!1;Qe.version===an.__version?(an.needsLights&&an.lightsStateVersion!==rn.state.version||an.outputColorSpace!==Pt||Ze.isBatchedMesh&&an.batching===!1||!Ze.isBatchedMesh&&an.batching===!0||Ze.isBatchedMesh&&an.batchingColor===!0&&Ze.colorTexture===null||Ze.isBatchedMesh&&an.batchingColor===!1&&Ze.colorTexture!==null||Ze.isInstancedMesh&&an.instancing===!1||!Ze.isInstancedMesh&&an.instancing===!0||Ze.isSkinnedMesh&&an.skinning===!1||!Ze.isSkinnedMesh&&an.skinning===!0||Ze.isInstancedMesh&&an.instancingColor===!0&&Ze.instanceColor===null||Ze.isInstancedMesh&&an.instancingColor===!1&&Ze.instanceColor!==null||Ze.isInstancedMesh&&an.instancingMorph===!0&&Ze.morphTexture===null||Ze.isInstancedMesh&&an.instancingMorph===!1&&Ze.morphTexture!==null||an.envMap!==vt||Qe.fog===!0&&an.fog!==rt||an.numClippingPlanes!==void 0&&(an.numClippingPlanes!==Fe.numPlanes||an.numIntersection!==Fe.numIntersection)||an.vertexAlphas!==He||an.vertexTangents!==St||an.morphTargets!==Ct||an.morphNormals!==Zt||an.morphColors!==Jt||an.toneMapping!==Nn||an.morphTargetsCount!==yn)&&(bn=!0):(bn=!0,an.__version=Qe.version);let Gn=an.currentProgram;bn===!0&&(Gn=Mt(Qe,We,Ze));let ar=!1,On=!1,mi=!1;const Rn=Gn.getUniforms(),na=an.uniforms;if(ie.useProgram(Gn.program)&&(ar=!0,On=!0,mi=!0),Qe.id!==$&&($=Qe.id,On=!0),ar||I!==Ce){ie.buffers.depth.getReversed()&&Ce.reversedDepth!==!0&&(Ce._reversedDepth=!0,Ce.updateProjectionMatrix()),Rn.setValue(G,"projectionMatrix",Ce.projectionMatrix),Rn.setValue(G,"viewMatrix",Ce.matrixWorldInverse);const In=Rn.map.cameraPosition;In!==void 0&&In.setValue(G,z.setFromMatrixPosition(Ce.matrixWorld)),J.logarithmicDepthBuffer&&Rn.setValue(G,"logDepthBufFC",2/(Math.log(Ce.far+1)/Math.LN2)),(Qe.isMeshPhongMaterial||Qe.isMeshToonMaterial||Qe.isMeshLambertMaterial||Qe.isMeshBasicMaterial||Qe.isMeshStandardMaterial||Qe.isShaderMaterial)&&Rn.setValue(G,"isOrthographic",Ce.isOrthographicCamera===!0),I!==Ce&&(I=Ce,On=!0,mi=!0)}if(Ze.isSkinnedMesh){Rn.setOptional(G,Ze,"bindMatrix"),Rn.setOptional(G,Ze,"bindMatrixInverse");const jr=Ze.skeleton;jr&&(jr.boneTexture===null&&jr.computeBoneTexture(),Rn.setValue(G,"boneTexture",jr.boneTexture,se))}Ze.isBatchedMesh&&(Rn.setOptional(G,Ze,"batchingTexture"),Rn.setValue(G,"batchingTexture",Ze._matricesTexture,se),Rn.setOptional(G,Ze,"batchingIdTexture"),Rn.setValue(G,"batchingIdTexture",Ze._indirectTexture,se),Rn.setOptional(G,Ze,"batchingColorTexture"),Ze._colorsTexture!==null&&Rn.setValue(G,"batchingColorTexture",Ze._colorsTexture,se));const ra=Xe.morphAttributes;if((ra.position!==void 0||ra.normal!==void 0||ra.color!==void 0)&&je.update(Ze,Xe,Gn),(On||an.receiveShadow!==Ze.receiveShadow)&&(an.receiveShadow=Ze.receiveShadow,Rn.setValue(G,"receiveShadow",Ze.receiveShadow)),Qe.isMeshGouraudMaterial&&Qe.envMap!==null&&(na.envMap.value=vt,na.flipEnvMap.value=vt.isCubeTexture&&vt.isRenderTargetTexture===!1?-1:1),Qe.isMeshStandardMaterial&&Qe.envMap===null&&We.environment!==null&&(na.envMapIntensity.value=We.environmentIntensity),na.dfgLUT!==void 0&&(na.dfgLUT.value=C1e()),On&&(Rn.setValue(G,"toneMappingExposure",M.toneMappingExposure),an.needsLights&&dt(na,mi),rt&&Qe.fog===!0&&Ae.refreshFogUniforms(na,rt),Ae.refreshMaterialUniforms(na,Qe,ue,le,k.state.transmissionRenderTarget[Ce.id]),Pk.upload(G,Qt(an),na,se)),Qe.isShaderMaterial&&Qe.uniformsNeedUpdate===!0&&(Pk.upload(G,Qt(an),na,se),Qe.uniformsNeedUpdate=!1),Qe.isSpriteMaterial&&Rn.setValue(G,"center",Ze.center),Rn.setValue(G,"modelViewMatrix",Ze.modelViewMatrix),Rn.setValue(G,"normalMatrix",Ze.normalMatrix),Rn.setValue(G,"modelMatrix",Ze.matrixWorld),Qe.isShaderMaterial||Qe.isRawShaderMaterial){const jr=Qe.uniformsGroups;for(let In=0,Bi=jr.length;In<Bi;In++){const Hi=jr[In];ze.update(Hi,Gn),ze.bind(Hi,Gn)}}return Gn}function dt(Ce,We){Ce.ambientLightColor.needsUpdate=We,Ce.lightProbe.needsUpdate=We,Ce.directionalLights.needsUpdate=We,Ce.directionalLightShadows.needsUpdate=We,Ce.pointLights.needsUpdate=We,Ce.pointLightShadows.needsUpdate=We,Ce.spotLights.needsUpdate=We,Ce.spotLightShadows.needsUpdate=We,Ce.rectAreaLights.needsUpdate=We,Ce.hemisphereLights.needsUpdate=We}function pt(Ce){return Ce.isMeshLambertMaterial||Ce.isMeshToonMaterial||Ce.isMeshPhongMaterial||Ce.isMeshStandardMaterial||Ce.isShadowMaterial||Ce.isShaderMaterial&&Ce.lights===!0}this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return C},this.getRenderTarget=function(){return F},this.setRenderTargetTextures=function(Ce,We,Xe){const Qe=fe.get(Ce);Qe.__autoAllocateDepthBuffer=Ce.resolveDepthBuffer===!1,Qe.__autoAllocateDepthBuffer===!1&&(Qe.__useRenderToTexture=!1),fe.get(Ce.texture).__webglTexture=We,fe.get(Ce.depthTexture).__webglTexture=Qe.__autoAllocateDepthBuffer?void 0:Xe,Qe.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(Ce,We){const Xe=fe.get(Ce);Xe.__webglFramebuffer=We,Xe.__useDefaultFramebuffer=We===void 0};const De=G.createFramebuffer();this.setRenderTarget=function(Ce,We=0,Xe=0){F=Ce,T=We,C=Xe;let Qe=!0,Ze=null,rt=!1,bt=!1;if(Ce){const vt=fe.get(Ce);if(vt.__useDefaultFramebuffer!==void 0)ie.bindFramebuffer(G.FRAMEBUFFER,null),Qe=!1;else if(vt.__webglFramebuffer===void 0)se.setupRenderTarget(Ce);else if(vt.__hasExternalTextures)se.rebindTextures(Ce,fe.get(Ce.texture).__webglTexture,fe.get(Ce.depthTexture).__webglTexture);else if(Ce.depthBuffer){const Ct=Ce.depthTexture;if(vt.__boundDepthTexture!==Ct){if(Ct!==null&&fe.has(Ct)&&(Ce.width!==Ct.image.width||Ce.height!==Ct.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");se.setupDepthRenderbuffer(Ce)}}const He=Ce.texture;(He.isData3DTexture||He.isDataArrayTexture||He.isCompressedArrayTexture)&&(bt=!0);const St=fe.get(Ce).__webglFramebuffer;Ce.isWebGLCubeRenderTarget?(Array.isArray(St[We])?Ze=St[We][Xe]:Ze=St[We],rt=!0):Ce.samples>0&&se.useMultisampledRTT(Ce)===!1?Ze=fe.get(Ce).__webglMultisampledFramebuffer:Array.isArray(St)?Ze=St[Xe]:Ze=St,X.copy(Ce.viewport),L.copy(Ce.scissor),te=Ce.scissorTest}else X.copy(oe).multiplyScalar(ue).floor(),L.copy(be).multiplyScalar(ue).floor(),te=_e;if(Xe!==0&&(Ze=De),ie.bindFramebuffer(G.FRAMEBUFFER,Ze)&&Qe&&ie.drawBuffers(Ce,Ze),ie.viewport(X),ie.scissor(L),ie.setScissorTest(te),rt){const vt=fe.get(Ce.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+We,vt.__webglTexture,Xe)}else if(bt){const vt=We;for(let He=0;He<Ce.textures.length;He++){const St=fe.get(Ce.textures[He]);G.framebufferTextureLayer(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0+He,St.__webglTexture,Xe,vt)}}else if(Ce!==null&&Xe!==0){const vt=fe.get(Ce.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,vt.__webglTexture,Xe)}$=-1},this.readRenderTargetPixels=function(Ce,We,Xe,Qe,Ze,rt,bt,Pt=0){if(!(Ce&&Ce.isWebGLRenderTarget)){Xa("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let vt=fe.get(Ce).__webglFramebuffer;if(Ce.isWebGLCubeRenderTarget&&bt!==void 0&&(vt=vt[bt]),vt){ie.bindFramebuffer(G.FRAMEBUFFER,vt);try{const He=Ce.textures[Pt],St=He.format,Ct=He.type;if(!J.textureFormatReadable(St)){Xa("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!J.textureTypeReadable(Ct)){Xa("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}We>=0&&We<=Ce.width-Qe&&Xe>=0&&Xe<=Ce.height-Ze&&(Ce.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+Pt),G.readPixels(We,Xe,Qe,Ze,Ye.convert(St),Ye.convert(Ct),rt))}finally{const He=F!==null?fe.get(F).__webglFramebuffer:null;ie.bindFramebuffer(G.FRAMEBUFFER,He)}}},this.readRenderTargetPixelsAsync=async function(Ce,We,Xe,Qe,Ze,rt,bt,Pt=0){if(!(Ce&&Ce.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let vt=fe.get(Ce).__webglFramebuffer;if(Ce.isWebGLCubeRenderTarget&&bt!==void 0&&(vt=vt[bt]),vt)if(We>=0&&We<=Ce.width-Qe&&Xe>=0&&Xe<=Ce.height-Ze){ie.bindFramebuffer(G.FRAMEBUFFER,vt);const He=Ce.textures[Pt],St=He.format,Ct=He.type;if(!J.textureFormatReadable(St))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!J.textureTypeReadable(Ct))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Zt=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,Zt),G.bufferData(G.PIXEL_PACK_BUFFER,rt.byteLength,G.STREAM_READ),Ce.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+Pt),G.readPixels(We,Xe,Qe,Ze,Ye.convert(St),Ye.convert(Ct),0);const Jt=F!==null?fe.get(F).__webglFramebuffer:null;ie.bindFramebuffer(G.FRAMEBUFFER,Jt);const Nn=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await Yye(G,Nn,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,Zt),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,rt),G.deleteBuffer(Zt),G.deleteSync(Nn),rt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(Ce,We=null,Xe=0){const Qe=Math.pow(2,-Xe),Ze=Math.floor(Ce.image.width*Qe),rt=Math.floor(Ce.image.height*Qe),bt=We!==null?We.x:0,Pt=We!==null?We.y:0;se.setTexture2D(Ce,0),G.copyTexSubImage2D(G.TEXTURE_2D,Xe,0,0,bt,Pt,Ze,rt),ie.unbindTexture()};const Le=G.createFramebuffer(),at=G.createFramebuffer();this.copyTextureToTexture=function(Ce,We,Xe=null,Qe=null,Ze=0,rt=null){rt===null&&(Ze!==0?(H0("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),rt=Ze,Ze=0):rt=0);let bt,Pt,vt,He,St,Ct,Zt,Jt,Nn;const vn=Ce.isCompressedTexture?Ce.mipmaps[rt]:Ce.image;if(Xe!==null)bt=Xe.max.x-Xe.min.x,Pt=Xe.max.y-Xe.min.y,vt=Xe.isBox3?Xe.max.z-Xe.min.z:1,He=Xe.min.x,St=Xe.min.y,Ct=Xe.isBox3?Xe.min.z:0;else{const ra=Math.pow(2,-Ze);bt=Math.floor(vn.width*ra),Pt=Math.floor(vn.height*ra),Ce.isDataArrayTexture?vt=vn.depth:Ce.isData3DTexture?vt=Math.floor(vn.depth*ra):vt=1,He=0,St=0,Ct=0}Qe!==null?(Zt=Qe.x,Jt=Qe.y,Nn=Qe.z):(Zt=0,Jt=0,Nn=0);const yn=Ye.convert(We.format),an=Ye.convert(We.type);let rn;We.isData3DTexture?(se.setTexture3D(We,0),rn=G.TEXTURE_3D):We.isDataArrayTexture||We.isCompressedArrayTexture?(se.setTexture2DArray(We,0),rn=G.TEXTURE_2D_ARRAY):(se.setTexture2D(We,0),rn=G.TEXTURE_2D),G.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,We.flipY),G.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,We.premultiplyAlpha),G.pixelStorei(G.UNPACK_ALIGNMENT,We.unpackAlignment);const bn=G.getParameter(G.UNPACK_ROW_LENGTH),Gn=G.getParameter(G.UNPACK_IMAGE_HEIGHT),ar=G.getParameter(G.UNPACK_SKIP_PIXELS),On=G.getParameter(G.UNPACK_SKIP_ROWS),mi=G.getParameter(G.UNPACK_SKIP_IMAGES);G.pixelStorei(G.UNPACK_ROW_LENGTH,vn.width),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,vn.height),G.pixelStorei(G.UNPACK_SKIP_PIXELS,He),G.pixelStorei(G.UNPACK_SKIP_ROWS,St),G.pixelStorei(G.UNPACK_SKIP_IMAGES,Ct);const Rn=Ce.isDataArrayTexture||Ce.isData3DTexture,na=We.isDataArrayTexture||We.isData3DTexture;if(Ce.isDepthTexture){const ra=fe.get(Ce),jr=fe.get(We),In=fe.get(ra.__renderTarget),Bi=fe.get(jr.__renderTarget);ie.bindFramebuffer(G.READ_FRAMEBUFFER,In.__webglFramebuffer),ie.bindFramebuffer(G.DRAW_FRAMEBUFFER,Bi.__webglFramebuffer);for(let Hi=0;Hi<vt;Hi++)Rn&&(G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,fe.get(Ce).__webglTexture,Ze,Ct+Hi),G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,fe.get(We).__webglTexture,rt,Nn+Hi)),G.blitFramebuffer(He,St,bt,Pt,Zt,Jt,bt,Pt,G.DEPTH_BUFFER_BIT,G.NEAREST);ie.bindFramebuffer(G.READ_FRAMEBUFFER,null),ie.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else if(Ze!==0||Ce.isRenderTargetTexture||fe.has(Ce)){const ra=fe.get(Ce),jr=fe.get(We);ie.bindFramebuffer(G.READ_FRAMEBUFFER,Le),ie.bindFramebuffer(G.DRAW_FRAMEBUFFER,at);for(let In=0;In<vt;In++)Rn?G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,ra.__webglTexture,Ze,Ct+In):G.framebufferTexture2D(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,ra.__webglTexture,Ze),na?G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,jr.__webglTexture,rt,Nn+In):G.framebufferTexture2D(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,jr.__webglTexture,rt),Ze!==0?G.blitFramebuffer(He,St,bt,Pt,Zt,Jt,bt,Pt,G.COLOR_BUFFER_BIT,G.NEAREST):na?G.copyTexSubImage3D(rn,rt,Zt,Jt,Nn+In,He,St,bt,Pt):G.copyTexSubImage2D(rn,rt,Zt,Jt,He,St,bt,Pt);ie.bindFramebuffer(G.READ_FRAMEBUFFER,null),ie.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else na?Ce.isDataTexture||Ce.isData3DTexture?G.texSubImage3D(rn,rt,Zt,Jt,Nn,bt,Pt,vt,yn,an,vn.data):We.isCompressedArrayTexture?G.compressedTexSubImage3D(rn,rt,Zt,Jt,Nn,bt,Pt,vt,yn,vn.data):G.texSubImage3D(rn,rt,Zt,Jt,Nn,bt,Pt,vt,yn,an,vn):Ce.isDataTexture?G.texSubImage2D(G.TEXTURE_2D,rt,Zt,Jt,bt,Pt,yn,an,vn.data):Ce.isCompressedTexture?G.compressedTexSubImage2D(G.TEXTURE_2D,rt,Zt,Jt,vn.width,vn.height,yn,vn.data):G.texSubImage2D(G.TEXTURE_2D,rt,Zt,Jt,bt,Pt,yn,an,vn);G.pixelStorei(G.UNPACK_ROW_LENGTH,bn),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,Gn),G.pixelStorei(G.UNPACK_SKIP_PIXELS,ar),G.pixelStorei(G.UNPACK_SKIP_ROWS,On),G.pixelStorei(G.UNPACK_SKIP_IMAGES,mi),rt===0&&We.generateMipmaps&&G.generateMipmap(rn),ie.unbindTexture()},this.initRenderTarget=function(Ce){fe.get(Ce).__webglFramebuffer===void 0&&se.setupRenderTarget(Ce)},this.initTexture=function(Ce){Ce.isCubeTexture?se.setTextureCube(Ce,0):Ce.isData3DTexture?se.setTexture3D(Ce,0):Ce.isDataArrayTexture||Ce.isCompressedArrayTexture?se.setTexture2DArray(Ce,0):se.setTexture2D(Ce,0),ie.unbindTexture()},this.resetState=function(){T=0,C=0,F=null,ie.reset(),ce.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return pd}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=Cr._getDrawingBufferColorSpace(e),n.unpackColorSpace=Cr._getUnpackColorSpace()}};const NH={type:"change"},OO={type:"start"},vZ={type:"end"},Z_=new jO,CH=new rh,T1e=Math.cos(70*Qye.DEG2RAD),pi=new At,xo=2*Math.PI,Vr={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Vj=1e-6;class A1e extends Uve{constructor(e,n=null){super(e,n),this.state=Vr.NONE,this.target=new At,this.cursor=new At,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:rx.ROTATE,MIDDLE:rx.DOLLY,RIGHT:rx.PAN},this.touches={ONE:Kb.ROTATE,TWO:Kb.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new At,this._lastQuaternion=new qf,this._lastTargetPosition=new At,this._quat=new qf().setFromUnitVectors(e.up,new At(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new eH,this._sphericalDelta=new eH,this._scale=1,this._panOffset=new At,this._rotateStart=new tr,this._rotateEnd=new tr,this._rotateDelta=new tr,this._panStart=new tr,this._panEnd=new tr,this._panDelta=new tr,this._dollyStart=new tr,this._dollyEnd=new tr,this._dollyDelta=new tr,this._dollyDirection=new At,this._mouse=new tr,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=j1e.bind(this),this._onPointerDown=M1e.bind(this),this._onPointerUp=E1e.bind(this),this._onContextMenu=z1e.bind(this),this._onMouseWheel=R1e.bind(this),this._onKeyDown=L1e.bind(this),this._onTouchStart=O1e.bind(this),this._onTouchMove=I1e.bind(this),this._onMouseDown=D1e.bind(this),this._onMouseMove=F1e.bind(this),this._interceptControlDown=U1e.bind(this),this._interceptControlUp=B1e.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(NH),this.update(),this.state=Vr.NONE}update(e=null){const n=this.object.position;pi.copy(n).sub(this.target),pi.applyQuaternion(this._quat),this._spherical.setFromVector3(pi),this.autoRotate&&this.state===Vr.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let r=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(r)&&isFinite(i)&&(r<-Math.PI?r+=xo:r>Math.PI&&(r-=xo),i<-Math.PI?i+=xo:i>Math.PI&&(i-=xo),r<=i?this._spherical.theta=Math.max(r,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+i)/2?Math.max(r,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(pi.setFromSpherical(this._spherical),pi.applyQuaternion(this._quatInverse),n.copy(this.target).add(pi),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=pi.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 At(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 At(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(l),this.object.updateMatrixWorld(),o=pi.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):(Z_.origin.copy(this.object.position),Z_.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Z_.direction))<T1e?this.object.lookAt(this.target):(CH.setFromNormalAndCoplanarPoint(this.object.up,this.target),Z_.intersectPlane(CH,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)>Vj||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Vj||this._lastTargetPosition.distanceToSquared(this.target)>Vj?(this.dispatchEvent(NH),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?xo/60*this.autoRotateSpeed*e:xo/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){pi.setFromMatrixColumn(n,0),pi.multiplyScalar(-e),this._panOffset.add(pi)}_panUp(e,n){this.screenSpacePanning===!0?pi.setFromMatrixColumn(n,1):(pi.setFromMatrixColumn(n,0),pi.crossVectors(this.object.up,pi)),pi.multiplyScalar(e),this._panOffset.add(pi)}_pan(e,n){const r=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;pi.copy(i).sub(this.target);let s=pi.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/r.clientHeight,this.object.matrix),this._panUp(2*n*s/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/r.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,n){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const r=this.domElement.getBoundingClientRect(),i=e-r.left,s=n-r.top,o=r.width,l=r.height;this._mouse.x=i/o*2-1,this._mouse.y=-(s/l)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(xo*this._rotateDelta.x/n.clientHeight),this._rotateUp(xo*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(xo*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(-xo*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(xo*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(-xo*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateStart.set(r,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panStart.set(r,i)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),r=e.pageX-n.x,i=e.pageY-n.y,s=Math.sqrt(r*r+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),i=.5*(e.pageX+r.x),s=.5*(e.pageY+r.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(xo*this._rotateDelta.x/n.clientHeight),this._rotateUp(xo*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panEnd.set(r,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const n=this._getSecondPointerPosition(e),r=e.pageX-n.x,i=e.pageY-n.y,s=Math.sqrt(r*r+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+n.x)*.5,l=(e.pageY+n.y)*.5;this._updateZoomParameters(o,l)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId){this._pointers.splice(n,1);return}}_isTrackingPointer(e){for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId)return!0;return!1}_trackPointer(e){let n=this._pointerPositions[e.pointerId];n===void 0&&(n=new tr,this._pointerPositions[e.pointerId]=n),n.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const n=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[n]}_customWheelEvent(e){const n=e.deltaMode,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(n){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function M1e(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 j1e(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function E1e(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(vZ),this.state=Vr.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 D1e(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 rx.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=Vr.DOLLY;break;case rx.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Vr.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Vr.ROTATE}break;case rx.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Vr.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Vr.PAN}break;default:this.state=Vr.NONE}this.state!==Vr.NONE&&this.dispatchEvent(OO)}function F1e(t){switch(this.state){case Vr.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case Vr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case Vr.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function R1e(t){this.enabled===!1||this.enableZoom===!1||this.state!==Vr.NONE||(t.preventDefault(),this.dispatchEvent(OO),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(vZ))}function L1e(t){this.enabled!==!1&&this._handleKeyDown(t)}function O1e(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case Kb.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=Vr.TOUCH_ROTATE;break;case Kb.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=Vr.TOUCH_PAN;break;default:this.state=Vr.NONE}break;case 2:switch(this.touches.TWO){case Kb.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=Vr.TOUCH_DOLLY_PAN;break;case Kb.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=Vr.TOUCH_DOLLY_ROTATE;break;default:this.state=Vr.NONE}break;default:this.state=Vr.NONE}this.state!==Vr.NONE&&this.dispatchEvent(OO)}function I1e(t){switch(this._trackPointer(t),this.state){case Vr.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case Vr.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case Vr.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case Vr.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=Vr.NONE}}function z1e(t){this.enabled!==!1&&t.preventDefault()}function U1e(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function B1e(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function H1e(t,e=!1){const n=t[0].index!==null,r=new Set(Object.keys(t[0].attributes)),i=new Set(Object.keys(t[0].morphAttributes)),s={},o={},l=t[0].morphTargetsRelative,c=new Ql;let d=0;for(let u=0;u<t.length;++u){const m=t[u];let p=0;if(n!==(m.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const f in m.attributes){if(!r.has(f))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+'. All geometries must have compatible attributes; make sure "'+f+'" attribute exists among all geometries, or in none of them.'),null;s[f]===void 0&&(s[f]=[]),s[f].push(m.attributes[f]),p++}if(p!==r.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". Make sure all geometries have the same number of attributes."),null;if(l!==m.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const f in m.morphAttributes){if(!i.has(f))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". .morphAttributes must be consistent throughout all geometries."),null;o[f]===void 0&&(o[f]=[]),o[f].push(m.morphAttributes[f])}if(e){let f;if(n)f=m.index.count;else if(m.attributes.position!==void 0)f=m.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". The geometry must have either an index or a position attribute"),null;c.addGroup(d,f,u),d+=f}}if(n){let u=0;const m=[];for(let p=0;p<t.length;++p){const f=t[p].index;for(let y=0;y<f.count;++y)m.push(f.getX(y)+u);u+=t[p].attributes.position.count}c.setIndex(m)}for(const u in s){const m=PH(s[u]);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+u+" attribute."),null;c.setAttribute(u,m)}for(const u in o){const m=o[u][0].length;if(m===0)break;c.morphAttributes=c.morphAttributes||{},c.morphAttributes[u]=[];for(let p=0;p<m;++p){const f=[];for(let v=0;v<o[u].length;++v)f.push(o[u][v][p]);const y=PH(f);if(!y)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+u+" morphAttribute."),null;c.morphAttributes[u].push(y)}}return c}function PH(t){let e,n,r,i=-1,s=0;for(let d=0;d<t.length;++d){const u=t[d];if(e===void 0&&(e=u.array.constructor),e!==u.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(n===void 0&&(n=u.itemSize),n!==u.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(r===void 0&&(r=u.normalized),r!==u.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=u.gpuType),i!==u.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=u.count*n}const o=new e(s),l=new Zs(o,n,r);let c=0;for(let d=0;d<t.length;++d){const u=t[d];if(u.isInterleavedBufferAttribute){const m=c/n;for(let p=0,f=u.count;p<f;p++)for(let y=0;y<n;y++){const v=u.getComponent(p,y);l.setComponent(p+m,y,v)}}else o.set(u.array,c);c+=u.count*n}return i!==void 0&&(l.gpuType=i),l}class q1e extends LO{constructor(e){super(e)}load(e,n,r,i){const s=this,o=new Fve(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{n(s.parse(l))}catch(c){i?i(c):console.error(c),s.manager.itemError(e)}},r,i)}parse(e){function n(d){const u=new DataView(d),m=32/8*3+32/8*3*3+16/8,p=u.getUint32(80,!0);if(80+32/8+p*m===u.byteLength)return!0;const y=[115,111,108,105,100];for(let v=0;v<5;v++)if(r(y,u,v))return!1;return!0}function r(d,u,m){for(let p=0,f=d.length;p<f;p++)if(d[p]!==u.getUint8(m+p))return!1;return!0}function i(d){const u=new DataView(d),m=u.getUint32(80,!0);let p,f,y,v=!1,b,g,_,k,P;for(let $=0;$<70;$++)u.getUint32($,!1)==1129270351&&u.getUint8($+4)==82&&u.getUint8($+5)==61&&(v=!0,b=new Float32Array(m*3*3),g=u.getUint8($+6)/255,_=u.getUint8($+7)/255,k=u.getUint8($+8)/255,P=u.getUint8($+9)/255);const N=84,M=50,A=new Ql,T=new Float32Array(m*3*3),C=new Float32Array(m*3*3),F=new sr;for(let $=0;$<m;$++){const I=N+$*M,X=u.getFloat32(I,!0),L=u.getFloat32(I+4,!0),te=u.getFloat32(I+8,!0);if(v){const ae=u.getUint16(I+48,!0);(ae&32768)===0?(p=(ae&31)/31,f=(ae>>5&31)/31,y=(ae>>10&31)/31):(p=g,f=_,y=k)}for(let ae=1;ae<=3;ae++){const ee=I+ae*12,me=$*3*3+(ae-1)*3;T[me]=u.getFloat32(ee,!0),T[me+1]=u.getFloat32(ee+4,!0),T[me+2]=u.getFloat32(ee+8,!0),C[me]=X,C[me+1]=L,C[me+2]=te,v&&(F.setRGB(p,f,y,Qo),b[me]=F.r,b[me+1]=F.g,b[me+2]=F.b)}}return A.setAttribute("position",new Zs(T,3)),A.setAttribute("normal",new Zs(C,3)),v&&(A.setAttribute("color",new Zs(b,3)),A.hasColors=!0,A.alpha=P),A}function s(d){const u=new Ql,m=/solid([\s\S]*?)endsolid/g,p=/facet([\s\S]*?)endfacet/g,f=/solid\s(.+)/;let y=0;const v=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,b=new RegExp("vertex"+v+v+v,"g"),g=new RegExp("normal"+v+v+v,"g"),_=[],k=[],P=[],N=new At;let M,A=0,T=0,C=0;for(;(M=m.exec(d))!==null;){T=C;const F=M[0],$=(M=f.exec(F))!==null?M[1]:"";for(P.push($);(M=p.exec(F))!==null;){let L=0,te=0;const ae=M[0];for(;(M=g.exec(ae))!==null;)N.x=parseFloat(M[1]),N.y=parseFloat(M[2]),N.z=parseFloat(M[3]),te++;for(;(M=b.exec(ae))!==null;)_.push(parseFloat(M[1]),parseFloat(M[2]),parseFloat(M[3])),k.push(N.x,N.y,N.z),L++,C++;te!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+y),L!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+y),y++}const I=T,X=C-T;u.userData.groupNames=P,u.addGroup(I,X,A),A++}return u.setAttribute("position",new rl(_,3)),u.setAttribute("normal",new rl(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 J_(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 Gj={exports:{}};var TH;function $1e(){return TH||(TH=1,(function(t,e){(function(n){t.exports=n()})(function(){return(function n(r,i,s){function o(d,u){if(!i[d]){if(!r[d]){var m=typeof J_=="function"&&J_;if(!u&&m)return m(d,!0);if(l)return l(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var f=i[d]={exports:{}};r[d][0].call(f.exports,function(y){var v=r[d][1][y];return o(v||y)},f,f.exports,n,r,i,s)}return i[d].exports}for(var l=typeof J_=="function"&&J_,c=0;c<s.length;c++)o(s[c]);return o})({1:[function(n,r,i){var s=n("./utils"),o=n("./support"),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(c){for(var d,u,m,p,f,y,v,b=[],g=0,_=c.length,k=_,P=s.getTypeOf(c)!=="string";g<c.length;)k=_-g,m=P?(d=c[g++],u=g<_?c[g++]:0,g<_?c[g++]:0):(d=c.charCodeAt(g++),u=g<_?c.charCodeAt(g++):0,g<_?c.charCodeAt(g++):0),p=d>>2,f=(3&d)<<4|u>>4,y=1<k?(15&u)<<2|m>>6:64,v=2<k?63&m:64,b.push(l.charAt(p)+l.charAt(f)+l.charAt(y)+l.charAt(v));return b.join("")},i.decode=function(c){var d,u,m,p,f,y,v=0,b=0,g="data:";if(c.substr(0,g.length)===g)throw new Error("Invalid base64 input, it looks like a data url.");var _,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(_=o.uint8array?new Uint8Array(0|k):new Array(0|k);v<c.length;)d=l.indexOf(c.charAt(v++))<<2|(p=l.indexOf(c.charAt(v++)))>>4,u=(15&p)<<4|(f=l.indexOf(c.charAt(v++)))>>2,m=(3&f)<<6|(y=l.indexOf(c.charAt(v++))),_[b++]=d,f!==64&&(_[b++]=u),y!==64&&(_[b++]=m);return _}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),l=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,m,p,f,y){this.compressedSize=u,this.uncompressedSize=m,this.crc32=p,this.compression=f,this.compressedContent=y}d.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),m=this;return u.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,m,p){return u.pipe(new l).pipe(new c("uncompressedSize")).pipe(m.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=(function(){for(var l,c=[],d=0;d<256;d++){l=d;for(var u=0;u<8;u++)l=1&l?3988292384^l>>>1:l>>>1;c[d]=l}return c})();r.exports=function(l,c){return l!==void 0&&l.length?s.getTypeOf(l)!=="string"?(function(d,u,m,p){var f=o,y=p+m;d^=-1;for(var v=p;v<y;v++)d=d>>>8^f[255&(d^u[v])];return-1^d})(0|c,l,l.length,0):(function(d,u,m,p){var f=o,y=p+m;d^=-1;for(var v=p;v<y;v++)d=d>>>8^f[255&(d^u.charCodeAt(v))];return-1^d})(0|c,l,l.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),l=n("./utils"),c=n("./stream/GenericWorker"),d=s?"uint8array":"array";function u(m,p){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=p,this.meta={}}i.magic="\b\0",l.inherits(u,c),u.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(l.transformTo(d,m.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(p){m.push({data:p,meta:m.meta})}},i.compressWorker=function(m){return new u("Deflate",m)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(f,y){var v,b="";for(v=0;v<y;v++)b+=String.fromCharCode(255&f),f>>>=8;return b}function o(f,y,v,b,g,_){var k,P,N=f.file,M=f.compression,A=_!==d.utf8encode,T=l.transformTo("string",_(N.name)),C=l.transformTo("string",d.utf8encode(N.name)),F=N.comment,$=l.transformTo("string",_(F)),I=l.transformTo("string",d.utf8encode(F)),X=C.length!==N.name.length,L=I.length!==F.length,te="",ae="",ee="",me=N.dir,le=N.date,ue={crc32:0,compressedSize:0,uncompressedSize:0};y&&!v||(ue.crc32=f.crc32,ue.compressedSize=f.compressedSize,ue.uncompressedSize=f.uncompressedSize);var K=0;y&&(K|=8),A||!X&&!L||(K|=2048);var ne=0,oe=0;me&&(ne|=16),g==="UNIX"?(oe=798,ne|=(function(_e,B){var Y=_e;return _e||(Y=B?16893:33204),(65535&Y)<<16})(N.unixPermissions,me)):(oe=20,ne|=(function(_e){return 63&(_e||0)})(N.dosPermissions)),k=le.getUTCHours(),k<<=6,k|=le.getUTCMinutes(),k<<=5,k|=le.getUTCSeconds()/2,P=le.getUTCFullYear()-1980,P<<=4,P|=le.getUTCMonth()+1,P<<=5,P|=le.getUTCDate(),X&&(ae=s(1,1)+s(u(T),4)+C,te+="up"+s(ae.length,2)+ae),L&&(ee=s(1,1)+s(u($),4)+I,te+="uc"+s(ee.length,2)+ee);var be="";return be+=`
  3860. \0`,be+=s(K,2),be+=M.magic,be+=s(k,2),be+=s(P,2),be+=s(ue.crc32,4),be+=s(ue.compressedSize,4),be+=s(ue.uncompressedSize,4),be+=s(T.length,2),be+=s(te.length,2),{fileRecord:m.LOCAL_FILE_HEADER+be+T+te,dirRecord:m.CENTRAL_FILE_HEADER+s(oe,2)+be+s($.length,2)+"\0\0\0\0"+s(ne,4)+s(b,4)+T+te+$}}var l=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),m=n("../signature");function p(f,y,v,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=v,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 y=f.meta.percent||0,v=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:v?(y+100*(v-b-1))/v:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var y=this.streamFiles&&!f.file.dir;if(y){var v=o(f,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var y=this.streamFiles&&!f.file.dir,v=o(f,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),y)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:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,y=0;y<this.dirRecords.length;y++)this.push({data:this.dirRecords[y],meta:{percent:100}});var v=this.bytesWritten-f,b=(function(g,_,k,P,N){var M=l.transformTo("string",N(P));return m.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(g,2)+s(g,2)+s(_,4)+s(k,4)+s(M.length,2)+M})(this.dirRecords.length,v,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 y=this;return f.on("data",function(v){y.processChunk(v)}),f.on("end",function(){y.closedSource(y.previous.streamInfo),y._sources.length?y.prepareNextSource():y.end()}),f.on("error",function(v){y.error(v)}),this},p.prototype.resume=function(){return!!c.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},p.prototype.error=function(f){var y=this._sources;if(!c.prototype.error.call(this,f))return!1;for(var v=0;v<y.length;v++)try{y[v].error(f)}catch{}return!0},p.prototype.lock=function(){c.prototype.lock.call(this);for(var f=this._sources,y=0;y<f.length;y++)f[y].lock()},r.exports=p},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,r,i){var s=n("../compressions"),o=n("./ZipFileWorker");i.generateWorker=function(l,c,d){var u=new o(c.streamFiles,d,c.platform,c.encodeFileName),m=0;try{l.forEach(function(p,f){m++;var y=(function(_,k){var P=_||k,N=s[P];if(!N)throw new Error(P+" is not a valid compression method !");return N})(f.options.compression,c.compression),v=f.options.compressionOptions||c.compressionOptions||{},b=f.dir,g=f.date;f._compressWorker(y,v).withStreamInfo("file",{name:p,dir:b,date:g,comment:f.comment||"",unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions}).pipe(u)}),u.entriesCount=m}catch(p){u.error(p)}return u}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,r,i){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var o=new s;for(var l in this)typeof this[l]!="function"&&(o[l]=this[l]);return o}}(s.prototype=n("./object")).loadAsync=n("./load"),s.support=n("./support"),s.defaults=n("./defaults"),s.version="3.10.1",s.loadAsync=function(o,l){return new s().loadAsync(o,l)},s.external=n("./external"),r.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,r,i){var s=n("./utils"),o=n("./external"),l=n("./utf8"),c=n("./zipEntries"),d=n("./stream/Crc32Probe"),u=n("./nodejsUtils");function m(p){return new o.Promise(function(f,y){var v=p.decompressed.getContentWorker().pipe(new d);v.on("error",function(b){y(b)}).on("end",function(){v.streamInfo.crc32!==p.decompressed.crc32?y(new Error("Corrupted zip : CRC32 mismatch")):f()}).resume()})}r.exports=function(p,f){var y=this;return f=s.extend(f||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:l.utf8decode}),u.isNode&&u.isStream(p)?o.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):s.prepareContent("the loaded zip file",p,!0,f.optimizedBinaryString,f.base64).then(function(v){var b=new c(f);return b.load(v),b}).then(function(v){var b=[o.Promise.resolve(v)],g=v.files;if(f.checkCRC32)for(var _=0;_<g.length;_++)b.push(m(g[_]));return o.Promise.all(b)}).then(function(v){for(var b=v.shift(),g=b.files,_=0;_<g.length;_++){var k=g[_],P=k.fileNameStr,N=s.resolve(k.fileNameStr);y.file(N,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||(y.file(N).unsafeOriginalName=P)}return b.zipComment.length&&(y.comment=b.zipComment),y})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(n,r,i){var s=n("../utils"),o=n("../stream/GenericWorker");function l(c,d){o.call(this,"Nodejs stream input adapter for "+c),this._upstreamEnded=!1,this._bindStream(d)}s.inherits(l,o),l.prototype._bindStream=function(c){var d=this;(this._stream=c).pause(),c.on("data",function(u){d.push({data:u,meta:{percent:0}})}).on("error",function(u){d.isPaused?this.generatedError=u:d.error(u)}).on("end",function(){d.isPaused?d._upstreamEnded=!0:d.end()})},l.prototype.pause=function(){return!!o.prototype.pause.call(this)&&(this._stream.pause(),!0)},l.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},r.exports=l},{"../stream/GenericWorker":28,"../utils":32}],13:[function(n,r,i){var s=n("readable-stream").Readable;function o(l,c,d){s.call(this,c),this._helper=l;var u=this;l.on("data",function(m,p){u.push(m)||u._helper.pause(),d&&d(p)}).on("error",function(m){u.emit("error",m)}).on("end",function(){u.push(null)})}n("../utils").inherits(o,s),o.prototype._read=function(){this._helper.resume()},r.exports=o},{"../utils":32,"readable-stream":16}],14:[function(n,r,i){r.exports={isNode:typeof Buffer<"u",newBufferFrom:function(s,o){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(s,o);if(typeof s=="number")throw new Error('The "data" argument must not be a number');return new Buffer(s,o)},allocBuffer:function(s){if(Buffer.alloc)return Buffer.alloc(s);var o=new Buffer(s);return o.fill(0),o},isBuffer:function(s){return Buffer.isBuffer(s)},isStream:function(s){return s&&typeof s.on=="function"&&typeof s.pause=="function"&&typeof s.resume=="function"}}},{}],15:[function(n,r,i){function s(N,M,A){var T,C=l.getTypeOf(M),F=l.extend(A||{},u);F.date=F.date||new Date,F.compression!==null&&(F.compression=F.compression.toUpperCase()),typeof F.unixPermissions=="string"&&(F.unixPermissions=parseInt(F.unixPermissions,8)),F.unixPermissions&&16384&F.unixPermissions&&(F.dir=!0),F.dosPermissions&&16&F.dosPermissions&&(F.dir=!0),F.dir&&(N=g(N)),F.createFolders&&(T=b(N))&&_.call(this,T,!0);var $=C==="string"&&F.binary===!1&&F.base64===!1;A&&A.binary!==void 0||(F.binary=!$),(M instanceof m&&M.uncompressedSize===0||F.dir||!M||M.length===0)&&(F.base64=!1,F.binary=!0,M="",F.compression="STORE",C="string");var I=null;I=M instanceof m||M instanceof c?M:y.isNode&&y.isStream(M)?new v(N,M):l.prepareContent(N,M,F.binary,F.optimizedBinaryString,F.base64);var X=new p(N,I,F);this.files[N]=X}var o=n("./utf8"),l=n("./utils"),c=n("./stream/GenericWorker"),d=n("./stream/StreamHelper"),u=n("./defaults"),m=n("./compressedObject"),p=n("./zipObject"),f=n("./generate"),y=n("./nodejsUtils"),v=n("./nodejs/NodejsStreamInputAdapter"),b=function(N){N.slice(-1)==="/"&&(N=N.substring(0,N.length-1));var M=N.lastIndexOf("/");return 0<M?N.substring(0,M):""},g=function(N){return N.slice(-1)!=="/"&&(N+="/"),N},_=function(N,M){return M=M!==void 0?M:u.createFolders,N=g(N),this.files[N]||s.call(this,N,null,{dir:!0,createFolders:M}),this.files[N]};function k(N){return Object.prototype.toString.call(N)==="[object RegExp]"}var P={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(N){var M,A,T;for(M in this.files)T=this.files[M],(A=M.slice(this.root.length,M.length))&&M.slice(0,this.root.length)===this.root&&N(A,T)},filter:function(N){var M=[];return this.forEach(function(A,T){N(A,T)&&M.push(T)}),M},file:function(N,M,A){if(arguments.length!==1)return N=this.root+N,s.call(this,N,M,A),this;if(k(N)){var T=N;return this.filter(function(F,$){return!$.dir&&T.test(F)})}var C=this.files[this.root+N];return C&&!C.dir?C:null},folder:function(N){if(!N)return this;if(k(N))return this.filter(function(C,F){return F.dir&&N.test(C)});var M=this.root+N,A=_.call(this,M),T=this.clone();return T.root=A.name,T},remove:function(N){N=this.root+N;var M=this.files[N];if(M||(N.slice(-1)!=="/"&&(N+="/"),M=this.files[N]),M&&!M.dir)delete this.files[N];else for(var A=this.filter(function(C,F){return F.name.slice(0,N.length)===N}),T=0;T<A.length;T++)delete this.files[A[T].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(N){var M,A={};try{if((A=l.extend(N||{},{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 T=A.comment||this.comment||"";M=f.generateWorker(this,A,T)}catch(C){(M=new c("error")).error(C)}return new d(M,A.type||"string",A.mimeType)},generateAsync:function(N,M){return this.generateInternalStream(N).accumulate(M)},generateNodeStream:function(N,M){return(N=N||{}).type||(N.type="nodebuffer"),this.generateInternalStream(N).toNodejsStream(M)}};r.exports=P},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(n,r,i){r.exports=n("stream")},{stream:void 0}],17:[function(n,r,i){var s=n("./DataReader");function o(l){s.call(this,l);for(var c=0;c<this.data.length;c++)l[c]=255&l[c]}n("../utils").inherits(o,s),o.prototype.byteAt=function(l){return this.data[this.zero+l]},o.prototype.lastIndexOfSignature=function(l){for(var c=l.charCodeAt(0),d=l.charCodeAt(1),u=l.charCodeAt(2),m=l.charCodeAt(3),p=this.length-4;0<=p;--p)if(this.data[p]===c&&this.data[p+1]===d&&this.data[p+2]===u&&this.data[p+3]===m)return p-this.zero;return-1},o.prototype.readAndCheckSignature=function(l){var c=l.charCodeAt(0),d=l.charCodeAt(1),u=l.charCodeAt(2),m=l.charCodeAt(3),p=this.readData(4);return c===p[0]&&d===p[1]&&u===p[2]&&m===p[3]},o.prototype.readData=function(l){if(this.checkOffset(l),l===0)return[];var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./DataReader":18}],18:[function(n,r,i){var s=n("../utils");function o(l){this.data=l,this.length=l.length,this.index=0,this.zero=0}o.prototype={checkOffset:function(l){this.checkIndex(this.index+l)},checkIndex:function(l){if(this.length<this.zero+l||l<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+l+"). Corrupted zip ?")},setIndex:function(l){this.checkIndex(l),this.index=l},skip:function(l){this.setIndex(this.index+l)},byteAt:function(){},readInt:function(l){var c,d=0;for(this.checkOffset(l),c=this.index+l-1;c>=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=l,d},readString:function(l){return s.transformTo("string",this.readData(l))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var l=this.readInt(4);return new Date(Date.UTC(1980+(l>>25&127),(l>>21&15)-1,l>>16&31,l>>11&31,l>>5&63,(31&l)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.byteAt=function(l){return this.data.charCodeAt(this.zero+l)},o.prototype.lastIndexOfSignature=function(l){return this.data.lastIndexOf(l)-this.zero},o.prototype.readAndCheckSignature=function(l){return l===this.readData(4)},o.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.readData=function(l){if(this.checkOffset(l),l===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),l=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(m){var p=s.getTypeOf(m);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new d(m):o.uint8array?new u(s.transformTo("uint8array",m)):new l(s.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function l(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(l,s),l.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=l},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function l(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(l,s),l.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=l},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function l(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(l,o),l.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=l},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function l(c){o.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=s.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}s.inherits(l,o),l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},l.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},l.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},l.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=l},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,l){return this._listeners[o].push(l),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,l){if(this._listeners[o])for(var c=0;c<this._listeners[o].length;c++)this._listeners[o][c].call(this,l)},pipe:function(o){return o.registerPrevious(this)},registerPrevious:function(o){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=o.streamInfo,this.mergeStreamInfo(),this.previous=o;var l=this;return o.on("data",function(c){l.processChunk(c)}),o.on("end",function(){l.end()}),o.on("error",function(c){l.error(c)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var o=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),o=!0),this.previous&&this.previous.resume(),!o},flush:function(){},processChunk:function(o){this.push(o)},withStreamInfo:function(o,l){return this.extraStreamInfo[o]=l,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var o in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,o)&&(this.streamInfo[o]=this.extraStreamInfo[o])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var o="Worker "+this.name;return this.previous?this.previous+" -> "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),l=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),m=null;if(d.nodestream)try{m=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(y,v){return new u.Promise(function(b,g){var _=[],k=y._internalType,P=y._outputType,N=y._mimeType;y.on("data",function(M,A){_.push(M),v&&v(A)}).on("error",function(M){_=[],g(M)}).on("end",function(){try{var M=(function(A,T,C){switch(A){case"blob":return s.newBlob(s.transformTo("arraybuffer",T),C);case"base64":return c.encode(T);default:return s.transformTo(A,T)}})(P,(function(A,T){var C,F=0,$=null,I=0;for(C=0;C<T.length;C++)I+=T[C].length;switch(A){case"string":return T.join("");case"array":return Array.prototype.concat.apply([],T);case"uint8array":for($=new Uint8Array(I),C=0;C<T.length;C++)$.set(T[C],F),F+=T[C].length;return $;case"nodebuffer":return Buffer.concat(T);default:throw new Error("concat : unsupported type '"+A+"'")}})(k,_),N);b(M)}catch(A){g(A)}_=[]}).resume()})}function f(y,v,b){var g=v;switch(v){case"blob":case"arraybuffer":g="uint8array";break;case"base64":g="string"}try{this._internalType=g,this._outputType=v,this._mimeType=b,s.checkSupport(g),this._worker=y.pipe(new o(g)),y.lock()}catch(_){this._worker=new l("error"),this._worker.error(_)}}f.prototype={accumulate:function(y){return p(this,y)},on:function(y,v){var b=this;return y==="data"?this._worker.on(y,function(g){v.call(b,g.data,g.meta)}):this._worker.on(y,function(){s.delay(v,arguments,b)}),this},resume:function(){return s.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(y){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"},y)}},r.exports=f},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,r,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",i.nodebuffer=typeof Buffer<"u",i.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),l=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function m(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}i.utf8encode=function(f){return o.nodebuffer?l.newBufferFrom(f,"utf-8"):(function(y){var v,b,g,_,k,P=y.length,N=0;for(_=0;_<P;_++)(64512&(b=y.charCodeAt(_)))==55296&&_+1<P&&(64512&(g=y.charCodeAt(_+1)))==56320&&(b=65536+(b-55296<<10)+(g-56320),_++),N+=b<128?1:b<2048?2:b<65536?3:4;for(v=o.uint8array?new Uint8Array(N):new Array(N),_=k=0;k<N;_++)(64512&(b=y.charCodeAt(_)))==55296&&_+1<P&&(64512&(g=y.charCodeAt(_+1)))==56320&&(b=65536+(b-55296<<10)+(g-56320),_++),b<128?v[k++]=b:(b<2048?v[k++]=192|b>>>6:(b<65536?v[k++]=224|b>>>12:(v[k++]=240|b>>>18,v[k++]=128|b>>>12&63),v[k++]=128|b>>>6&63),v[k++]=128|63&b);return v})(f)},i.utf8decode=function(f){return o.nodebuffer?s.transformTo("nodebuffer",f).toString("utf-8"):(function(y){var v,b,g,_,k=y.length,P=new Array(2*k);for(v=b=0;v<k;)if((g=y[v++])<128)P[b++]=g;else if(4<(_=d[g]))P[b++]=65533,v+=_-1;else{for(g&=_===2?31:_===3?15:7;1<_&&v<k;)g=g<<6|63&y[v++],_--;1<_?P[b++]=65533:g<65536?P[b++]=g:(g-=65536,P[b++]=55296|g>>10&1023,P[b++]=56320|1023&g)}return P.length!==b&&(P.subarray?P=P.subarray(0,b):P.length=b),s.applyFromCharCode(P)})(f=s.transformTo(o.uint8array?"uint8array":"array",f))},s.inherits(m,c),m.prototype.processChunk=function(f){var y=s.transformTo(o.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=y;(y=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),y.set(v,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var b=(function(_,k){var P;for((k=k||_.length)>_.length&&(k=_.length),P=k-1;0<=P&&(192&_[P])==128;)P--;return P<0||P===0?k:P+d[_[P]]>k?P:k})(y),g=y;b!==y.length&&(o.uint8array?(g=y.subarray(0,b),this.leftOver=y.subarray(b,y.length)):(g=y.slice(0,b),this.leftOver=y.slice(b,y.length))),this.push({data:i.utf8decode(g),meta:f.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=m,s.inherits(p,c),p.prototype.processChunk=function(f){this.push({data:i.utf8encode(f.data),meta:f.meta})},i.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),l=n("./nodejsUtils"),c=n("./external");function d(v){return v}function u(v,b){for(var g=0;g<v.length;++g)b[g]=255&v.charCodeAt(g);return b}n("setimmediate"),i.newBlob=function(v,b){i.checkSupport("blob");try{return new Blob([v],{type:b})}catch{try{var g=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return g.append(v),g.getBlob(b)}catch{throw new Error("Bug : can't construct the Blob.")}}};var m={stringifyByChunk:function(v,b,g){var _=[],k=0,P=v.length;if(P<=g)return String.fromCharCode.apply(null,v);for(;k<P;)b==="array"||b==="nodebuffer"?_.push(String.fromCharCode.apply(null,v.slice(k,Math.min(k+g,P)))):_.push(String.fromCharCode.apply(null,v.subarray(k,Math.min(k+g,P)))),k+=g;return _.join("")},stringifyByChar:function(v){for(var b="",g=0;g<v.length;g++)b+=String.fromCharCode(v[g]);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(v){var b=65536,g=i.getTypeOf(v),_=!0;if(g==="uint8array"?_=m.applyCanBeUsed.uint8array:g==="nodebuffer"&&(_=m.applyCanBeUsed.nodebuffer),_)for(;1<b;)try{return m.stringifyByChunk(v,g,b)}catch{b=Math.floor(b/2)}return m.stringifyByChar(v)}function f(v,b){for(var g=0;g<v.length;g++)b[g]=v[g];return b}i.applyFromCharCode=p;var y={};y.string={string:d,array:function(v){return u(v,new Array(v.length))},arraybuffer:function(v){return y.string.uint8array(v).buffer},uint8array:function(v){return u(v,new Uint8Array(v.length))},nodebuffer:function(v){return u(v,l.allocBuffer(v.length))}},y.array={string:p,array:d,arraybuffer:function(v){return new Uint8Array(v).buffer},uint8array:function(v){return new Uint8Array(v)},nodebuffer:function(v){return l.newBufferFrom(v)}},y.arraybuffer={string:function(v){return p(new Uint8Array(v))},array:function(v){return f(new Uint8Array(v),new Array(v.byteLength))},arraybuffer:d,uint8array:function(v){return new Uint8Array(v)},nodebuffer:function(v){return l.newBufferFrom(new Uint8Array(v))}},y.uint8array={string:p,array:function(v){return f(v,new Array(v.length))},arraybuffer:function(v){return v.buffer},uint8array:d,nodebuffer:function(v){return l.newBufferFrom(v)}},y.nodebuffer={string:p,array:function(v){return f(v,new Array(v.length))},arraybuffer:function(v){return y.nodebuffer.uint8array(v).buffer},uint8array:function(v){return f(v,new Uint8Array(v.length))},nodebuffer:d},i.transformTo=function(v,b){if(b=b||"",!v)return b;i.checkSupport(v);var g=i.getTypeOf(b);return y[g][v](b)},i.resolve=function(v){for(var b=v.split("/"),g=[],_=0;_<b.length;_++){var k=b[_];k==="."||k===""&&_!==0&&_!==b.length-1||(k===".."?g.pop():g.push(k))}return g.join("/")},i.getTypeOf=function(v){return typeof v=="string"?"string":Object.prototype.toString.call(v)==="[object Array]"?"array":s.nodebuffer&&l.isBuffer(v)?"nodebuffer":s.uint8array&&v instanceof Uint8Array?"uint8array":s.arraybuffer&&v instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(v){if(!s[v.toLowerCase()])throw new Error(v+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(v){var b,g,_="";for(g=0;g<(v||"").length;g++)_+="\\x"+((b=v.charCodeAt(g))<16?"0":"")+b.toString(16).toUpperCase();return _},i.delay=function(v,b,g){setImmediate(function(){v.apply(g||null,b||[])})},i.inherits=function(v,b){function g(){}g.prototype=b.prototype,v.prototype=new g},i.extend=function(){var v,b,g={};for(v=0;v<arguments.length;v++)for(b in arguments[v])Object.prototype.hasOwnProperty.call(arguments[v],b)&&g[b]===void 0&&(g[b]=arguments[v][b]);return g},i.prepareContent=function(v,b,g,_,k){return c.Promise.resolve(b).then(function(P){return s.blob&&(P instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(P))!==-1)&&typeof FileReader<"u"?new c.Promise(function(N,M){var A=new FileReader;A.onload=function(T){N(T.target.result)},A.onerror=function(T){M(T.target.error)},A.readAsArrayBuffer(P)}):P}).then(function(P){var N=i.getTypeOf(P);return N?(N==="arraybuffer"?P=i.transformTo("uint8array",P):N==="string"&&(k?P=o.decode(P):g&&_!==!0&&(P=(function(M){return u(M,s.uint8array?new Uint8Array(M.length):new Array(M.length))})(P))),P):c.Promise.reject(new Error("Can't read the data of '"+v+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(n,r,i){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./signature"),c=n("./zipEntry"),d=n("./support");function u(m){this.files=[],this.loadOptions=m}u.prototype={checkSignature:function(m){if(!this.reader.readAndCheckSignature(m)){this.reader.index-=4;var p=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+o.pretty(p)+", expected "+o.pretty(m)+")")}},isSignature:function(m,p){var f=this.reader.index;this.reader.setIndex(m);var y=this.reader.readString(4)===p;return this.reader.setIndex(f),y},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,y=this.zip64EndOfCentralSize-44;0<y;)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 y=p-f;if(0<y)this.isSignature(p,l.CENTRAL_FILE_HEADER)||(this.reader.zero=y);else if(y<0)throw new Error("Corrupted zip: missing "+Math.abs(y)+" bytes.")},prepareReader:function(m){this.reader=s(m)},load:function(m){this.prepareReader(m),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},r.exports=u},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,r,i){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./compressedObject"),c=n("./crc32"),d=n("./utf8"),u=n("./compressions"),m=n("./support");function p(f,y){this.options=f,this.loadOptions=y}p.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(f){var y,v;if(f.skip(22),this.fileNameLength=f.readInt(2),v=f.readInt(2),this.fileName=f.readData(this.fileNameLength),f.skip(v),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((y=(function(b){for(var g in u)if(Object.prototype.hasOwnProperty.call(u,g)&&u[g].magic===b)return u[g];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,y,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 y=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(y),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 y,v,b,g=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4<g;)y=f.readInt(2),v=f.readInt(2),b=f.readData(v),this.extraFields[y]={id:y,length:v,value:b};f.setIndex(g)},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 y=this.findExtraFieldUnicodePath();if(y!==null)this.fileNameStr=y;else{var v=o.transformTo(f,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var g=o.transformTo(f,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(g)}}},findExtraFieldUnicodePath:function(){var f=this.extraFields[28789];if(f){var y=s(f.value);return y.readInt(1)!==1||c(this.fileName)!==y.readInt(4)?null:d.utf8decode(y.readData(f.length-5))}return null},findExtraFieldUnicodeComment:function(){var f=this.extraFields[25461];if(f){var y=s(f.value);return y.readInt(1)!==1||c(this.fileComment)!==y.readInt(4)?null:d.utf8decode(y.readData(f.length-5))}return null}},r.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(y,v,b){this.name=y,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=v,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(y){var v=null,b="string";try{if(!y)throw new Error("No output type specified.");var g=(b=y.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),v=this._decompressWorker();var _=!this._dataBinary;_&&!g&&(v=v.pipe(new c.Utf8EncodeWorker)),!_&&g&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(k){(v=new u("error")).error(k)}return new o(v,b,"")},async:function(y,v){return this.internalStream(y).accumulate(v)},nodeStream:function(y,v){return this.internalStream(y||"nodebuffer").toNodejsStream(v)},_compressWorker:function(y,v){if(this._data instanceof d&&this._data.compression.magic===y.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),d.createWorkerFrom(b,y,v)},_decompressWorker:function(){return this._data instanceof d?this._data.getContentWorker():this._data instanceof u?this._data:new l(this._data)}};for(var m=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],p=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},f=0;f<m.length;f++)s.prototype[m[f]]=p;r.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,r,i){(function(s){var o,l,c=s.MutationObserver||s.WebKitMutationObserver;if(c){var d=0,u=new c(y),m=s.document.createTextNode("");u.observe(m,{characterData:!0}),o=function(){m.data=d=++d%2}}else if(s.setImmediate||s.MessageChannel===void 0)o="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var v=s.document.createElement("script");v.onreadystatechange=function(){y(),v.onreadystatechange=null,v.parentNode.removeChild(v),v=null},s.document.documentElement.appendChild(v)}:function(){setTimeout(y,0)};else{var p=new s.MessageChannel;p.port1.onmessage=y,o=function(){p.port2.postMessage(0)}}var f=[];function y(){var v,b;l=!0;for(var g=f.length;g;){for(b=f,f=[],v=-1;++v<g;)b[v]();g=f.length}l=!1}r.exports=function(v){f.push(v)!==1||l||o()}}).call(this,typeof k_<"u"?k_:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,r,i){var s=n("immediate");function o(){}var l={},c=["REJECTED"],d=["FULFILLED"],u=["PENDING"];function m(g){if(typeof g!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,g!==o&&v(this,g)}function p(g,_,k){this.promise=g,typeof _=="function"&&(this.onFulfilled=_,this.callFulfilled=this.otherCallFulfilled),typeof k=="function"&&(this.onRejected=k,this.callRejected=this.otherCallRejected)}function f(g,_,k){s(function(){var P;try{P=_(k)}catch(N){return l.reject(g,N)}P===g?l.reject(g,new TypeError("Cannot resolve promise with itself")):l.resolve(g,P)})}function y(g){var _=g&&g.then;if(g&&(typeof g=="object"||typeof g=="function")&&typeof _=="function")return function(){_.apply(g,arguments)}}function v(g,_){var k=!1;function P(A){k||(k=!0,l.reject(g,A))}function N(A){k||(k=!0,l.resolve(g,A))}var M=b(function(){_(N,P)});M.status==="error"&&P(M.value)}function b(g,_){var k={};try{k.value=g(_),k.status="success"}catch(P){k.status="error",k.value=P}return k}(r.exports=m).prototype.finally=function(g){if(typeof g!="function")return this;var _=this.constructor;return this.then(function(k){return _.resolve(g()).then(function(){return k})},function(k){return _.resolve(g()).then(function(){throw k})})},m.prototype.catch=function(g){return this.then(null,g)},m.prototype.then=function(g,_){if(typeof g!="function"&&this.state===d||typeof _!="function"&&this.state===c)return this;var k=new this.constructor(o);return this.state!==u?f(k,this.state===d?g:_,this.outcome):this.queue.push(new p(k,g,_)),k},p.prototype.callFulfilled=function(g){l.resolve(this.promise,g)},p.prototype.otherCallFulfilled=function(g){f(this.promise,this.onFulfilled,g)},p.prototype.callRejected=function(g){l.reject(this.promise,g)},p.prototype.otherCallRejected=function(g){f(this.promise,this.onRejected,g)},l.resolve=function(g,_){var k=b(y,_);if(k.status==="error")return l.reject(g,k.value);var P=k.value;if(P)v(g,P);else{g.state=d,g.outcome=_;for(var N=-1,M=g.queue.length;++N<M;)g.queue[N].callFulfilled(_)}return g},l.reject=function(g,_){g.state=c,g.outcome=_;for(var k=-1,P=g.queue.length;++k<P;)g.queue[k].callRejected(_);return g},m.resolve=function(g){return g instanceof this?g:l.resolve(new this(o),g)},m.reject=function(g){var _=new this(o);return l.reject(_,g)},m.all=function(g){var _=this;if(Object.prototype.toString.call(g)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=g.length,P=!1;if(!k)return this.resolve([]);for(var N=new Array(k),M=0,A=-1,T=new this(o);++A<k;)C(g[A],A);return T;function C(F,$){_.resolve(F).then(function(I){N[$]=I,++M!==k||P||(P=!0,l.resolve(T,N))},function(I){P||(P=!0,l.reject(T,I))})}},m.race=function(g){var _=this;if(Object.prototype.toString.call(g)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=g.length,P=!1;if(!k)return this.resolve([]);for(var N=-1,M=new this(o);++N<k;)A=g[N],_.resolve(A).then(function(T){P||(P=!0,l.resolve(M,T))},function(T){P||(P=!0,l.reject(M,T))});var A;return M}},{immediate:36}],38:[function(n,r,i){var s={};(0,n("./lib/utils/common").assign)(s,n("./lib/deflate"),n("./lib/inflate"),n("./lib/zlib/constants")),r.exports=s},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(n,r,i){var s=n("./zlib/deflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/messages"),d=n("./zlib/zstream"),u=Object.prototype.toString,m=0,p=-1,f=0,y=8;function v(g){if(!(this instanceof v))return new v(g);this.options=o.assign({level:p,method:y,chunkSize:16384,windowBits:15,memLevel:8,strategy:f,to:""},g||{});var _=this.options;_.raw&&0<_.windowBits?_.windowBits=-_.windowBits:_.gzip&&0<_.windowBits&&_.windowBits<16&&(_.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var k=s.deflateInit2(this.strm,_.level,_.method,_.windowBits,_.memLevel,_.strategy);if(k!==m)throw new Error(c[k]);if(_.header&&s.deflateSetHeader(this.strm,_.header),_.dictionary){var P;if(P=typeof _.dictionary=="string"?l.string2buf(_.dictionary):u.call(_.dictionary)==="[object ArrayBuffer]"?new Uint8Array(_.dictionary):_.dictionary,(k=s.deflateSetDictionary(this.strm,P))!==m)throw new Error(c[k]);this._dict_set=!0}}function b(g,_){var k=new v(_);if(k.push(g,!0),k.err)throw k.msg||c[k.err];return k.result}v.prototype.push=function(g,_){var k,P,N=this.strm,M=this.options.chunkSize;if(this.ended)return!1;P=_===~~_?_:_===!0?4:0,typeof g=="string"?N.input=l.string2buf(g):u.call(g)==="[object ArrayBuffer]"?N.input=new Uint8Array(g):N.input=g,N.next_in=0,N.avail_in=N.input.length;do{if(N.avail_out===0&&(N.output=new o.Buf8(M),N.next_out=0,N.avail_out=M),(k=s.deflate(N,P))!==1&&k!==m)return this.onEnd(k),!(this.ended=!0);N.avail_out!==0&&(N.avail_in!==0||P!==4&&P!==2)||(this.options.to==="string"?this.onData(l.buf2binstring(o.shrinkBuf(N.output,N.next_out))):this.onData(o.shrinkBuf(N.output,N.next_out)))}while((0<N.avail_in||N.avail_out===0)&&k!==1);return P===4?(k=s.deflateEnd(this.strm),this.onEnd(k),this.ended=!0,k===m):P!==2||(this.onEnd(m),!(N.avail_out=0))},v.prototype.onData=function(g){this.chunks.push(g)},v.prototype.onEnd=function(g){g===m&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},i.Deflate=v,i.deflate=b,i.deflateRaw=function(g,_){return(_=_||{}).raw=!0,b(g,_)},i.gzip=function(g,_){return(_=_||{}).gzip=!0,b(g,_)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,r,i){var s=n("./zlib/inflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/constants"),d=n("./zlib/messages"),u=n("./zlib/zstream"),m=n("./zlib/gzheader"),p=Object.prototype.toString;function f(v){if(!(this instanceof f))return new f(v);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},v||{});var 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)||v&&v.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 g=s.inflateInit2(this.strm,b.windowBits);if(g!==c.Z_OK)throw new Error(d[g]);this.header=new m,s.inflateGetHeader(this.strm,this.header)}function y(v,b){var g=new f(b);if(g.push(v,!0),g.err)throw g.msg||d[g.err];return g.result}f.prototype.push=function(v,b){var g,_,k,P,N,M,A=this.strm,T=this.options.chunkSize,C=this.options.dictionary,F=!1;if(this.ended)return!1;_=b===~~b?b:b===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof v=="string"?A.input=l.binstring2buf(v):p.call(v)==="[object ArrayBuffer]"?A.input=new Uint8Array(v):A.input=v,A.next_in=0,A.avail_in=A.input.length;do{if(A.avail_out===0&&(A.output=new o.Buf8(T),A.next_out=0,A.avail_out=T),(g=s.inflate(A,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&C&&(M=typeof C=="string"?l.string2buf(C):p.call(C)==="[object ArrayBuffer]"?new Uint8Array(C):C,g=s.inflateSetDictionary(this.strm,M)),g===c.Z_BUF_ERROR&&F===!0&&(g=c.Z_OK,F=!1),g!==c.Z_STREAM_END&&g!==c.Z_OK)return this.onEnd(g),!(this.ended=!0);A.next_out&&(A.avail_out!==0&&g!==c.Z_STREAM_END&&(A.avail_in!==0||_!==c.Z_FINISH&&_!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(k=l.utf8border(A.output,A.next_out),P=A.next_out-k,N=l.buf2string(A.output,k),A.next_out=P,A.avail_out=T-P,P&&o.arraySet(A.output,A.output,k,P,0),this.onData(N)):this.onData(o.shrinkBuf(A.output,A.next_out)))),A.avail_in===0&&A.avail_out===0&&(F=!0)}while((0<A.avail_in||A.avail_out===0)&&g!==c.Z_STREAM_END);return g===c.Z_STREAM_END&&(_=c.Z_FINISH),_===c.Z_FINISH?(g=s.inflateEnd(this.strm),this.onEnd(g),this.ended=!0,g===c.Z_OK):_!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(A.avail_out=0))},f.prototype.onData=function(v){this.chunks.push(v)},f.prototype.onEnd=function(v){v===c.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=v,this.msg=this.strm.msg},i.Inflate=f,i.inflate=y,i.inflateRaw=function(v,b){return(b=b||{}).raw=!0,y(v,b)},i.ungzip=y},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";i.assign=function(c){for(var d=Array.prototype.slice.call(arguments,1);d.length;){var u=d.shift();if(u){if(typeof u!="object")throw new TypeError(u+"must be non-object");for(var m in u)u.hasOwnProperty(m)&&(c[m]=u[m])}}return c},i.shrinkBuf=function(c,d){return c.length===d?c:c.subarray?c.subarray(0,d):(c.length=d,c)};var o={arraySet:function(c,d,u,m,p){if(d.subarray&&c.subarray)c.set(d.subarray(u,u+m),p);else for(var f=0;f<m;f++)c[p+f]=d[u+f]},flattenChunks:function(c){var d,u,m,p,f,y;for(d=m=0,u=c.length;d<u;d++)m+=c[d].length;for(y=new Uint8Array(m),d=p=0,u=c.length;d<u;d++)f=c[d],y.set(f,p),p+=f.length;return y}},l={arraySet:function(c,d,u,m,p){for(var f=0;f<m;f++)c[p+f]=d[u+f]},flattenChunks:function(c){return[].concat.apply([],c)}};i.setTyped=function(c){c?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,o)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,l))},i.setTyped(s)},{}],42:[function(n,r,i){var s=n("./common"),o=!0,l=!0;try{String.fromCharCode.apply(null,[0])}catch{o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{l=!1}for(var c=new s.Buf8(256),d=0;d<256;d++)c[d]=252<=d?6:248<=d?5:240<=d?4:224<=d?3:192<=d?2:1;function u(m,p){if(p<65537&&(m.subarray&&l||!m.subarray&&o))return String.fromCharCode.apply(null,s.shrinkBuf(m,p));for(var f="",y=0;y<p;y++)f+=String.fromCharCode(m[y]);return f}c[254]=c[254]=1,i.string2buf=function(m){var p,f,y,v,b,g=m.length,_=0;for(v=0;v<g;v++)(64512&(f=m.charCodeAt(v)))==55296&&v+1<g&&(64512&(y=m.charCodeAt(v+1)))==56320&&(f=65536+(f-55296<<10)+(y-56320),v++),_+=f<128?1:f<2048?2:f<65536?3:4;for(p=new s.Buf8(_),v=b=0;b<_;v++)(64512&(f=m.charCodeAt(v)))==55296&&v+1<g&&(64512&(y=m.charCodeAt(v+1)))==56320&&(f=65536+(f-55296<<10)+(y-56320),v++),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,y=p.length;f<y;f++)p[f]=m.charCodeAt(f);return p},i.buf2string=function(m,p){var f,y,v,b,g=p||m.length,_=new Array(2*g);for(f=y=0;f<g;)if((v=m[f++])<128)_[y++]=v;else if(4<(b=c[v]))_[y++]=65533,f+=b-1;else{for(v&=b===2?31:b===3?15:7;1<b&&f<g;)v=v<<6|63&m[f++],b--;1<b?_[y++]=65533:v<65536?_[y++]=v:(v-=65536,_[y++]=55296|v>>10&1023,_[y++]=56320|1023&v)}return u(_,y)},i.utf8border=function(m,p){var f;for((p=p||m.length)>m.length&&(p=m.length),f=p-1;0<=f&&(192&m[f])==128;)f--;return f<0||f===0?p:f+c[m[f]]>p?f:p}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,l,c){for(var d=65535&s|0,u=s>>>16&65535|0,m=0;l!==0;){for(l-=m=2e3<l?2e3:l;u=u+(d=d+o[c++]|0)|0,--m;);d%=65521,u%=65521}return d|u<<16|0}},{}],44:[function(n,r,i){r.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(n,r,i){var s=(function(){for(var o,l=[],c=0;c<256;c++){o=c;for(var d=0;d<8;d++)o=1&o?3988292384^o>>>1:o>>>1;l[c]=o}return l})();r.exports=function(o,l,c,d){var u=s,m=d+c;o^=-1;for(var p=d;p<m;p++)o=o>>>8^u[255&(o^l[p])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),l=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),m=0,p=4,f=0,y=-2,v=-1,b=4,g=2,_=8,k=9,P=286,N=30,M=19,A=2*P+1,T=15,C=3,F=258,$=F+C+1,I=42,X=113,L=1,te=2,ae=3,ee=4;function me(O,G){return O.msg=u[G],G}function le(O){return(O<<1)-(4<O?9:0)}function ue(O){for(var G=O.length;0<=--G;)O[G]=0}function K(O){var G=O.state,Q=G.pending;Q>O.avail_out&&(Q=O.avail_out),Q!==0&&(o.arraySet(O.output,G.pending_buf,G.pending_out,Q,O.next_out),O.next_out+=Q,G.pending_out+=Q,O.total_out+=Q,O.avail_out-=Q,G.pending-=Q,G.pending===0&&(G.pending_out=0))}function ne(O,G){l._tr_flush_block(O,0<=O.block_start?O.block_start:-1,O.strstart-O.block_start,G),O.block_start=O.strstart,K(O.strm)}function oe(O,G){O.pending_buf[O.pending++]=G}function be(O,G){O.pending_buf[O.pending++]=G>>>8&255,O.pending_buf[O.pending++]=255&G}function _e(O,G){var Q,V,J=O.max_chain_length,ie=O.strstart,he=O.prev_length,fe=O.nice_match,se=O.strstart>O.w_size-$?O.strstart-(O.w_size-$):0,U=O.window,R=O.w_mask,re=O.prev,xe=O.strstart+F,we=U[ie+he-1],ye=U[ie+he];O.prev_length>=O.good_match&&(J>>=2),fe>O.lookahead&&(fe=O.lookahead);do if(U[(Q=G)+he]===ye&&U[Q+he-1]===we&&U[Q]===U[ie]&&U[++Q]===U[ie+1]){ie+=2,Q++;do;while(U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&U[++ie]===U[++Q]&&ie<xe);if(V=F-(xe-ie),ie=xe-F,he<V){if(O.match_start=G,fe<=(he=V))break;we=U[ie+he-1],ye=U[ie+he]}}while((G=re[G&R])>se&&--J!=0);return he<=O.lookahead?he:O.lookahead}function B(O){var G,Q,V,J,ie,he,fe,se,U,R,re=O.w_size;do{if(J=O.window_size-O.lookahead-O.strstart,O.strstart>=re+(re-$)){for(o.arraySet(O.window,O.window,re,re,0),O.match_start-=re,O.strstart-=re,O.block_start-=re,G=Q=O.hash_size;V=O.head[--G],O.head[G]=re<=V?V-re:0,--Q;);for(G=Q=re;V=O.prev[--G],O.prev[G]=re<=V?V-re:0,--Q;);J+=re}if(O.strm.avail_in===0)break;if(he=O.strm,fe=O.window,se=O.strstart+O.lookahead,U=J,R=void 0,R=he.avail_in,U<R&&(R=U),Q=R===0?0:(he.avail_in-=R,o.arraySet(fe,he.input,he.next_in,R,se),he.state.wrap===1?he.adler=c(he.adler,fe,R,se):he.state.wrap===2&&(he.adler=d(he.adler,fe,R,se)),he.next_in+=R,he.total_in+=R,R),O.lookahead+=Q,O.lookahead+O.insert>=C)for(ie=O.strstart-O.insert,O.ins_h=O.window[ie],O.ins_h=(O.ins_h<<O.hash_shift^O.window[ie+1])&O.hash_mask;O.insert&&(O.ins_h=(O.ins_h<<O.hash_shift^O.window[ie+C-1])&O.hash_mask,O.prev[ie&O.w_mask]=O.head[O.ins_h],O.head[O.ins_h]=ie,ie++,O.insert--,!(O.lookahead+O.insert<C)););}while(O.lookahead<$&&O.strm.avail_in!==0)}function Y(O,G){for(var Q,V;;){if(O.lookahead<$){if(B(O),O.lookahead<$&&G===m)return L;if(O.lookahead===0)break}if(Q=0,O.lookahead>=C&&(O.ins_h=(O.ins_h<<O.hash_shift^O.window[O.strstart+C-1])&O.hash_mask,Q=O.prev[O.strstart&O.w_mask]=O.head[O.ins_h],O.head[O.ins_h]=O.strstart),Q!==0&&O.strstart-Q<=O.w_size-$&&(O.match_length=_e(O,Q)),O.match_length>=C)if(V=l._tr_tally(O,O.strstart-O.match_start,O.match_length-C),O.lookahead-=O.match_length,O.match_length<=O.max_lazy_match&&O.lookahead>=C){for(O.match_length--;O.strstart++,O.ins_h=(O.ins_h<<O.hash_shift^O.window[O.strstart+C-1])&O.hash_mask,Q=O.prev[O.strstart&O.w_mask]=O.head[O.ins_h],O.head[O.ins_h]=O.strstart,--O.match_length!=0;);O.strstart++}else O.strstart+=O.match_length,O.match_length=0,O.ins_h=O.window[O.strstart],O.ins_h=(O.ins_h<<O.hash_shift^O.window[O.strstart+1])&O.hash_mask;else V=l._tr_tally(O,0,O.window[O.strstart]),O.lookahead--,O.strstart++;if(V&&(ne(O,!1),O.strm.avail_out===0))return L}return O.insert=O.strstart<C-1?O.strstart:C-1,G===p?(ne(O,!0),O.strm.avail_out===0?ae:ee):O.last_lit&&(ne(O,!1),O.strm.avail_out===0)?L:te}function D(O,G){for(var Q,V,J;;){if(O.lookahead<$){if(B(O),O.lookahead<$&&G===m)return L;if(O.lookahead===0)break}if(Q=0,O.lookahead>=C&&(O.ins_h=(O.ins_h<<O.hash_shift^O.window[O.strstart+C-1])&O.hash_mask,Q=O.prev[O.strstart&O.w_mask]=O.head[O.ins_h],O.head[O.ins_h]=O.strstart),O.prev_length=O.match_length,O.prev_match=O.match_start,O.match_length=C-1,Q!==0&&O.prev_length<O.max_lazy_match&&O.strstart-Q<=O.w_size-$&&(O.match_length=_e(O,Q),O.match_length<=5&&(O.strategy===1||O.match_length===C&&4096<O.strstart-O.match_start)&&(O.match_length=C-1)),O.prev_length>=C&&O.match_length<=O.prev_length){for(J=O.strstart+O.lookahead-C,V=l._tr_tally(O,O.strstart-1-O.prev_match,O.prev_length-C),O.lookahead-=O.prev_length-1,O.prev_length-=2;++O.strstart<=J&&(O.ins_h=(O.ins_h<<O.hash_shift^O.window[O.strstart+C-1])&O.hash_mask,Q=O.prev[O.strstart&O.w_mask]=O.head[O.ins_h],O.head[O.ins_h]=O.strstart),--O.prev_length!=0;);if(O.match_available=0,O.match_length=C-1,O.strstart++,V&&(ne(O,!1),O.strm.avail_out===0))return L}else if(O.match_available){if((V=l._tr_tally(O,0,O.window[O.strstart-1]))&&ne(O,!1),O.strstart++,O.lookahead--,O.strm.avail_out===0)return L}else O.match_available=1,O.strstart++,O.lookahead--}return O.match_available&&(V=l._tr_tally(O,0,O.window[O.strstart-1]),O.match_available=0),O.insert=O.strstart<C-1?O.strstart:C-1,G===p?(ne(O,!0),O.strm.avail_out===0?ae:ee):O.last_lit&&(ne(O,!1),O.strm.avail_out===0)?L:te}function j(O,G,Q,V,J){this.good_length=O,this.max_lazy=G,this.nice_length=Q,this.max_chain=V,this.func=J}function z(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=_,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new o.Buf16(2*A),this.dyn_dtree=new o.Buf16(2*(2*N+1)),this.bl_tree=new o.Buf16(2*(2*M+1)),ue(this.dyn_ltree),ue(this.dyn_dtree),ue(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new o.Buf16(T+1),this.heap=new o.Buf16(2*P+1),ue(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new o.Buf16(2*P+1),ue(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(O){var G;return O&&O.state?(O.total_in=O.total_out=0,O.data_type=g,(G=O.state).pending=0,G.pending_out=0,G.wrap<0&&(G.wrap=-G.wrap),G.status=G.wrap?I:X,O.adler=G.wrap===2?0:1,G.last_flush=m,l._tr_init(G),f):me(O,y)}function q(O){var G=W(O);return G===f&&(function(Q){Q.window_size=2*Q.w_size,ue(Q.head),Q.max_lazy_match=s[Q.level].max_lazy,Q.good_match=s[Q.level].good_length,Q.nice_match=s[Q.level].nice_length,Q.max_chain_length=s[Q.level].max_chain,Q.strstart=0,Q.block_start=0,Q.lookahead=0,Q.insert=0,Q.match_length=Q.prev_length=C-1,Q.match_available=0,Q.ins_h=0})(O.state),G}function de(O,G,Q,V,J,ie){if(!O)return y;var he=1;if(G===v&&(G=6),V<0?(he=0,V=-V):15<V&&(he=2,V-=16),J<1||k<J||Q!==_||V<8||15<V||G<0||9<G||ie<0||b<ie)return me(O,y);V===8&&(V=9);var fe=new z;return(O.state=fe).strm=O,fe.wrap=he,fe.gzhead=null,fe.w_bits=V,fe.w_size=1<<fe.w_bits,fe.w_mask=fe.w_size-1,fe.hash_bits=J+7,fe.hash_size=1<<fe.hash_bits,fe.hash_mask=fe.hash_size-1,fe.hash_shift=~~((fe.hash_bits+C-1)/C),fe.window=new o.Buf8(2*fe.w_size),fe.head=new o.Buf16(fe.hash_size),fe.prev=new o.Buf16(fe.w_size),fe.lit_bufsize=1<<J+6,fe.pending_buf_size=4*fe.lit_bufsize,fe.pending_buf=new o.Buf8(fe.pending_buf_size),fe.d_buf=1*fe.lit_bufsize,fe.l_buf=3*fe.lit_bufsize,fe.level=G,fe.strategy=ie,fe.method=Q,q(O)}s=[new j(0,0,0,0,function(O,G){var Q=65535;for(Q>O.pending_buf_size-5&&(Q=O.pending_buf_size-5);;){if(O.lookahead<=1){if(B(O),O.lookahead===0&&G===m)return L;if(O.lookahead===0)break}O.strstart+=O.lookahead,O.lookahead=0;var V=O.block_start+Q;if((O.strstart===0||O.strstart>=V)&&(O.lookahead=O.strstart-V,O.strstart=V,ne(O,!1),O.strm.avail_out===0)||O.strstart-O.block_start>=O.w_size-$&&(ne(O,!1),O.strm.avail_out===0))return L}return O.insert=0,G===p?(ne(O,!0),O.strm.avail_out===0?ae:ee):(O.strstart>O.block_start&&(ne(O,!1),O.strm.avail_out),L)}),new j(4,4,8,4,Y),new j(4,5,16,8,Y),new j(4,6,32,32,Y),new j(4,4,16,16,D),new j(8,16,32,32,D),new j(8,16,128,128,D),new j(8,32,128,256,D),new j(32,128,258,1024,D),new j(32,258,258,4096,D)],i.deflateInit=function(O,G){return de(O,G,_,15,8,0)},i.deflateInit2=de,i.deflateReset=q,i.deflateResetKeep=W,i.deflateSetHeader=function(O,G){return O&&O.state?O.state.wrap!==2?y:(O.state.gzhead=G,f):y},i.deflate=function(O,G){var Q,V,J,ie;if(!O||!O.state||5<G||G<0)return O?me(O,y):y;if(V=O.state,!O.output||!O.input&&O.avail_in!==0||V.status===666&&G!==p)return me(O,O.avail_out===0?-5:y);if(V.strm=O,Q=V.last_flush,V.last_flush=G,V.status===I)if(V.wrap===2)O.adler=0,oe(V,31),oe(V,139),oe(V,8),V.gzhead?(oe(V,(V.gzhead.text?1:0)+(V.gzhead.hcrc?2:0)+(V.gzhead.extra?4:0)+(V.gzhead.name?8:0)+(V.gzhead.comment?16:0)),oe(V,255&V.gzhead.time),oe(V,V.gzhead.time>>8&255),oe(V,V.gzhead.time>>16&255),oe(V,V.gzhead.time>>24&255),oe(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),oe(V,255&V.gzhead.os),V.gzhead.extra&&V.gzhead.extra.length&&(oe(V,255&V.gzhead.extra.length),oe(V,V.gzhead.extra.length>>8&255)),V.gzhead.hcrc&&(O.adler=d(O.adler,V.pending_buf,V.pending,0)),V.gzindex=0,V.status=69):(oe(V,0),oe(V,0),oe(V,0),oe(V,0),oe(V,0),oe(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),oe(V,3),V.status=X);else{var he=_+(V.w_bits-8<<4)<<8;he|=(2<=V.strategy||V.level<2?0:V.level<6?1:V.level===6?2:3)<<6,V.strstart!==0&&(he|=32),he+=31-he%31,V.status=X,be(V,he),V.strstart!==0&&(be(V,O.adler>>>16),be(V,65535&O.adler)),O.adler=1}if(V.status===69)if(V.gzhead.extra){for(J=V.pending;V.gzindex<(65535&V.gzhead.extra.length)&&(V.pending!==V.pending_buf_size||(V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),K(O),J=V.pending,V.pending!==V.pending_buf_size));)oe(V,255&V.gzhead.extra[V.gzindex]),V.gzindex++;V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),V.gzindex===V.gzhead.extra.length&&(V.gzindex=0,V.status=73)}else V.status=73;if(V.status===73)if(V.gzhead.name){J=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),K(O),J=V.pending,V.pending===V.pending_buf_size)){ie=1;break}ie=V.gzindex<V.gzhead.name.length?255&V.gzhead.name.charCodeAt(V.gzindex++):0,oe(V,ie)}while(ie!==0);V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),ie===0&&(V.gzindex=0,V.status=91)}else V.status=91;if(V.status===91)if(V.gzhead.comment){J=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),K(O),J=V.pending,V.pending===V.pending_buf_size)){ie=1;break}ie=V.gzindex<V.gzhead.comment.length?255&V.gzhead.comment.charCodeAt(V.gzindex++):0,oe(V,ie)}while(ie!==0);V.gzhead.hcrc&&V.pending>J&&(O.adler=d(O.adler,V.pending_buf,V.pending-J,J)),ie===0&&(V.status=103)}else V.status=103;if(V.status===103&&(V.gzhead.hcrc?(V.pending+2>V.pending_buf_size&&K(O),V.pending+2<=V.pending_buf_size&&(oe(V,255&O.adler),oe(V,O.adler>>8&255),O.adler=0,V.status=X)):V.status=X),V.pending!==0){if(K(O),O.avail_out===0)return V.last_flush=-1,f}else if(O.avail_in===0&&le(G)<=le(Q)&&G!==p)return me(O,-5);if(V.status===666&&O.avail_in!==0)return me(O,-5);if(O.avail_in!==0||V.lookahead!==0||G!==m&&V.status!==666){var fe=V.strategy===2?(function(se,U){for(var R;;){if(se.lookahead===0&&(B(se),se.lookahead===0)){if(U===m)return L;break}if(se.match_length=0,R=l._tr_tally(se,0,se.window[se.strstart]),se.lookahead--,se.strstart++,R&&(ne(se,!1),se.strm.avail_out===0))return L}return se.insert=0,U===p?(ne(se,!0),se.strm.avail_out===0?ae:ee):se.last_lit&&(ne(se,!1),se.strm.avail_out===0)?L:te})(V,G):V.strategy===3?(function(se,U){for(var R,re,xe,we,ye=se.window;;){if(se.lookahead<=F){if(B(se),se.lookahead<=F&&U===m)return L;if(se.lookahead===0)break}if(se.match_length=0,se.lookahead>=C&&0<se.strstart&&(re=ye[xe=se.strstart-1])===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]){we=se.strstart+F;do;while(re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&re===ye[++xe]&&xe<we);se.match_length=F-(we-xe),se.match_length>se.lookahead&&(se.match_length=se.lookahead)}if(se.match_length>=C?(R=l._tr_tally(se,1,se.match_length-C),se.lookahead-=se.match_length,se.strstart+=se.match_length,se.match_length=0):(R=l._tr_tally(se,0,se.window[se.strstart]),se.lookahead--,se.strstart++),R&&(ne(se,!1),se.strm.avail_out===0))return L}return se.insert=0,U===p?(ne(se,!0),se.strm.avail_out===0?ae:ee):se.last_lit&&(ne(se,!1),se.strm.avail_out===0)?L:te})(V,G):s[V.level].func(V,G);if(fe!==ae&&fe!==ee||(V.status=666),fe===L||fe===ae)return O.avail_out===0&&(V.last_flush=-1),f;if(fe===te&&(G===1?l._tr_align(V):G!==5&&(l._tr_stored_block(V,0,0,!1),G===3&&(ue(V.head),V.lookahead===0&&(V.strstart=0,V.block_start=0,V.insert=0))),K(O),O.avail_out===0))return V.last_flush=-1,f}return G!==p?f:V.wrap<=0?1:(V.wrap===2?(oe(V,255&O.adler),oe(V,O.adler>>8&255),oe(V,O.adler>>16&255),oe(V,O.adler>>24&255),oe(V,255&O.total_in),oe(V,O.total_in>>8&255),oe(V,O.total_in>>16&255),oe(V,O.total_in>>24&255)):(be(V,O.adler>>>16),be(V,65535&O.adler)),K(O),0<V.wrap&&(V.wrap=-V.wrap),V.pending!==0?f:1)},i.deflateEnd=function(O){var G;return O&&O.state?(G=O.state.status)!==I&&G!==69&&G!==73&&G!==91&&G!==103&&G!==X&&G!==666?me(O,y):(O.state=null,G===X?me(O,-3):f):y},i.deflateSetDictionary=function(O,G){var Q,V,J,ie,he,fe,se,U,R=G.length;if(!O||!O.state||(ie=(Q=O.state).wrap)===2||ie===1&&Q.status!==I||Q.lookahead)return y;for(ie===1&&(O.adler=c(O.adler,G,R,0)),Q.wrap=0,R>=Q.w_size&&(ie===0&&(ue(Q.head),Q.strstart=0,Q.block_start=0,Q.insert=0),U=new o.Buf8(Q.w_size),o.arraySet(U,G,R-Q.w_size,Q.w_size,0),G=U,R=Q.w_size),he=O.avail_in,fe=O.next_in,se=O.input,O.avail_in=R,O.next_in=0,O.input=G,B(Q);Q.lookahead>=C;){for(V=Q.strstart,J=Q.lookahead-(C-1);Q.ins_h=(Q.ins_h<<Q.hash_shift^Q.window[V+C-1])&Q.hash_mask,Q.prev[V&Q.w_mask]=Q.head[Q.ins_h],Q.head[Q.ins_h]=V,V++,--J;);Q.strstart=V,Q.lookahead=C-1,B(Q)}return Q.strstart+=Q.lookahead,Q.block_start=Q.strstart,Q.insert=Q.lookahead,Q.lookahead=0,Q.match_length=Q.prev_length=C-1,Q.match_available=0,O.next_in=fe,O.input=se,O.avail_in=he,Q.wrap=ie,f},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,r,i){r.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(n,r,i){r.exports=function(s,o){var l,c,d,u,m,p,f,y,v,b,g,_,k,P,N,M,A,T,C,F,$,I,X,L,te;l=s.state,c=s.next_in,L=s.input,d=c+(s.avail_in-5),u=s.next_out,te=s.output,m=u-(o-s.avail_out),p=u+(s.avail_out-257),f=l.dmax,y=l.wsize,v=l.whave,b=l.wnext,g=l.window,_=l.hold,k=l.bits,P=l.lencode,N=l.distcode,M=(1<<l.lenbits)-1,A=(1<<l.distbits)-1;e:do{k<15&&(_+=L[c++]<<k,k+=8,_+=L[c++]<<k,k+=8),T=P[_&M];t:for(;;){if(_>>>=C=T>>>24,k-=C,(C=T>>>16&255)===0)te[u++]=65535&T;else{if(!(16&C)){if((64&C)==0){T=P[(65535&T)+(_&(1<<C)-1)];continue t}if(32&C){l.mode=12;break e}s.msg="invalid literal/length code",l.mode=30;break e}F=65535&T,(C&=15)&&(k<C&&(_+=L[c++]<<k,k+=8),F+=_&(1<<C)-1,_>>>=C,k-=C),k<15&&(_+=L[c++]<<k,k+=8,_+=L[c++]<<k,k+=8),T=N[_&A];n:for(;;){if(_>>>=C=T>>>24,k-=C,!(16&(C=T>>>16&255))){if((64&C)==0){T=N[(65535&T)+(_&(1<<C)-1)];continue n}s.msg="invalid distance code",l.mode=30;break e}if($=65535&T,k<(C&=15)&&(_+=L[c++]<<k,(k+=8)<C&&(_+=L[c++]<<k,k+=8)),f<($+=_&(1<<C)-1)){s.msg="invalid distance too far back",l.mode=30;break e}if(_>>>=C,k-=C,(C=u-m)<$){if(v<(C=$-C)&&l.sane){s.msg="invalid distance too far back",l.mode=30;break e}if(X=g,(I=0)===b){if(I+=y-C,C<F){for(F-=C;te[u++]=g[I++],--C;);I=u-$,X=te}}else if(b<C){if(I+=y+b-C,(C-=b)<F){for(F-=C;te[u++]=g[I++],--C;);if(I=0,b<F){for(F-=C=b;te[u++]=g[I++],--C;);I=u-$,X=te}}}else if(I+=b-C,C<F){for(F-=C;te[u++]=g[I++],--C;);I=u-$,X=te}for(;2<F;)te[u++]=X[I++],te[u++]=X[I++],te[u++]=X[I++],F-=3;F&&(te[u++]=X[I++],1<F&&(te[u++]=X[I++]))}else{for(I=u-$;te[u++]=te[I++],te[u++]=te[I++],te[u++]=te[I++],2<(F-=3););F&&(te[u++]=te[I++],1<F&&(te[u++]=te[I++]))}break}}break}}while(c<d&&u<p);c-=F=k>>3,_&=(1<<(k-=F<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c<d?d-c+5:5-(c-d),s.avail_out=u<p?p-u+257:257-(u-p),l.hold=_,l.bits=k}},{}],49:[function(n,r,i){var s=n("../utils/common"),o=n("./adler32"),l=n("./crc32"),c=n("./inffast"),d=n("./inftrees"),u=1,m=2,p=0,f=-2,y=1,v=852,b=592;function g(I){return(I>>>24&255)+(I>>>8&65280)+((65280&I)<<8)+((255&I)<<24)}function _(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function k(I){var X;return I&&I.state?(X=I.state,I.total_in=I.total_out=X.total=0,I.msg="",X.wrap&&(I.adler=1&X.wrap),X.mode=y,X.last=0,X.havedict=0,X.dmax=32768,X.head=null,X.hold=0,X.bits=0,X.lencode=X.lendyn=new s.Buf32(v),X.distcode=X.distdyn=new s.Buf32(b),X.sane=1,X.back=-1,p):f}function P(I){var X;return I&&I.state?((X=I.state).wsize=0,X.whave=0,X.wnext=0,k(I)):f}function N(I,X){var L,te;return I&&I.state?(te=I.state,X<0?(L=0,X=-X):(L=1+(X>>4),X<48&&(X&=15)),X&&(X<8||15<X)?f:(te.window!==null&&te.wbits!==X&&(te.window=null),te.wrap=L,te.wbits=X,P(I))):f}function M(I,X){var L,te;return I?(te=new _,(I.state=te).window=null,(L=N(I,X))!==p&&(I.state=null),L):f}var A,T,C=!0;function F(I){if(C){var X;for(A=new s.Buf32(512),T=new s.Buf32(32),X=0;X<144;)I.lens[X++]=8;for(;X<256;)I.lens[X++]=9;for(;X<280;)I.lens[X++]=7;for(;X<288;)I.lens[X++]=8;for(d(u,I.lens,0,288,A,0,I.work,{bits:9}),X=0;X<32;)I.lens[X++]=5;d(m,I.lens,0,32,T,0,I.work,{bits:5}),C=!1}I.lencode=A,I.lenbits=9,I.distcode=T,I.distbits=5}function $(I,X,L,te){var ae,ee=I.state;return ee.window===null&&(ee.wsize=1<<ee.wbits,ee.wnext=0,ee.whave=0,ee.window=new s.Buf8(ee.wsize)),te>=ee.wsize?(s.arraySet(ee.window,X,L-ee.wsize,ee.wsize,0),ee.wnext=0,ee.whave=ee.wsize):(te<(ae=ee.wsize-ee.wnext)&&(ae=te),s.arraySet(ee.window,X,L-te,ae,ee.wnext),(te-=ae)?(s.arraySet(ee.window,X,L-te,te,0),ee.wnext=te,ee.whave=ee.wsize):(ee.wnext+=ae,ee.wnext===ee.wsize&&(ee.wnext=0),ee.whave<ee.wsize&&(ee.whave+=ae))),0}i.inflateReset=P,i.inflateReset2=N,i.inflateResetKeep=k,i.inflateInit=function(I){return M(I,15)},i.inflateInit2=M,i.inflate=function(I,X){var L,te,ae,ee,me,le,ue,K,ne,oe,be,_e,B,Y,D,j,z,W,q,de,O,G,Q,V,J=0,ie=new s.Buf8(4),he=[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),me=I.next_out,ae=I.output,ue=I.avail_out,ee=I.next_in,te=I.input,le=I.avail_in,K=L.hold,ne=L.bits,oe=le,be=ue,G=p;e:for(;;)switch(L.mode){case y:if(L.wrap===0){L.mode=13;break}for(;ne<16;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(2&L.wrap&&K===35615){ie[L.check=0]=255&K,ie[1]=K>>>8&255,L.check=l(L.check,ie,2,0),ne=K=0,L.mode=2;break}if(L.flags=0,L.head&&(L.head.done=!1),!(1&L.wrap)||(((255&K)<<8)+(K>>8))%31){I.msg="incorrect header check",L.mode=30;break}if((15&K)!=8){I.msg="unknown compression method",L.mode=30;break}if(ne-=4,O=8+(15&(K>>>=4)),L.wbits===0)L.wbits=O;else if(O>L.wbits){I.msg="invalid window size",L.mode=30;break}L.dmax=1<<O,I.adler=L.check=1,L.mode=512&K?10:12,ne=K=0;break;case 2:for(;ne<16;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(L.flags=K,(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=K>>8&1),512&L.flags&&(ie[0]=255&K,ie[1]=K>>>8&255,L.check=l(L.check,ie,2,0)),ne=K=0,L.mode=3;case 3:for(;ne<32;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.head&&(L.head.time=K),512&L.flags&&(ie[0]=255&K,ie[1]=K>>>8&255,ie[2]=K>>>16&255,ie[3]=K>>>24&255,L.check=l(L.check,ie,4,0)),ne=K=0,L.mode=4;case 4:for(;ne<16;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.head&&(L.head.xflags=255&K,L.head.os=K>>8),512&L.flags&&(ie[0]=255&K,ie[1]=K>>>8&255,L.check=l(L.check,ie,2,0)),ne=K=0,L.mode=5;case 5:if(1024&L.flags){for(;ne<16;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.length=K,L.head&&(L.head.extra_len=K),512&L.flags&&(ie[0]=255&K,ie[1]=K>>>8&255,L.check=l(L.check,ie,2,0)),ne=K=0}else L.head&&(L.head.extra=null);L.mode=6;case 6:if(1024&L.flags&&(le<(_e=L.length)&&(_e=le),_e&&(L.head&&(O=L.head.extra_len-L.length,L.head.extra||(L.head.extra=new Array(L.head.extra_len)),s.arraySet(L.head.extra,te,ee,_e,O)),512&L.flags&&(L.check=l(L.check,te,_e,ee)),le-=_e,ee+=_e,L.length-=_e),L.length))break e;L.length=0,L.mode=7;case 7:if(2048&L.flags){if(le===0)break e;for(_e=0;O=te[ee+_e++],L.head&&O&&L.length<65536&&(L.head.name+=String.fromCharCode(O)),O&&_e<le;);if(512&L.flags&&(L.check=l(L.check,te,_e,ee)),le-=_e,ee+=_e,O)break e}else L.head&&(L.head.name=null);L.length=0,L.mode=8;case 8:if(4096&L.flags){if(le===0)break e;for(_e=0;O=te[ee+_e++],L.head&&O&&L.length<65536&&(L.head.comment+=String.fromCharCode(O)),O&&_e<le;);if(512&L.flags&&(L.check=l(L.check,te,_e,ee)),le-=_e,ee+=_e,O)break e}else L.head&&(L.head.comment=null);L.mode=9;case 9:if(512&L.flags){for(;ne<16;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(K!==(65535&L.check)){I.msg="header crc mismatch",L.mode=30;break}ne=K=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(;ne<32;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}I.adler=L.check=g(K),ne=K=0,L.mode=11;case 11:if(L.havedict===0)return I.next_out=me,I.avail_out=ue,I.next_in=ee,I.avail_in=le,L.hold=K,L.bits=ne,2;I.adler=L.check=1,L.mode=12;case 12:if(X===5||X===6)break e;case 13:if(L.last){K>>>=7&ne,ne-=7&ne,L.mode=27;break}for(;ne<3;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}switch(L.last=1&K,ne-=1,3&(K>>>=1)){case 0:L.mode=14;break;case 1:if(F(L),L.mode=20,X!==6)break;K>>>=2,ne-=2;break e;case 2:L.mode=17;break;case 3:I.msg="invalid block type",L.mode=30}K>>>=2,ne-=2;break;case 14:for(K>>>=7&ne,ne-=7&ne;ne<32;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if((65535&K)!=(K>>>16^65535)){I.msg="invalid stored block lengths",L.mode=30;break}if(L.length=65535&K,ne=K=0,L.mode=15,X===6)break e;case 15:L.mode=16;case 16:if(_e=L.length){if(le<_e&&(_e=le),ue<_e&&(_e=ue),_e===0)break e;s.arraySet(ae,te,ee,_e,me),le-=_e,ee+=_e,ue-=_e,me+=_e,L.length-=_e;break}L.mode=12;break;case 17:for(;ne<14;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(L.nlen=257+(31&K),K>>>=5,ne-=5,L.ndist=1+(31&K),K>>>=5,ne-=5,L.ncode=4+(15&K),K>>>=4,ne-=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(;ne<3;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.lens[he[L.have++]]=7&K,K>>>=3,ne-=3}for(;L.have<19;)L.lens[he[L.have++]]=0;if(L.lencode=L.lendyn,L.lenbits=7,Q={bits:L.lenbits},G=d(0,L.lens,0,19,L.lencode,0,L.work,Q),L.lenbits=Q.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(;j=(J=L.lencode[K&(1<<L.lenbits)-1])>>>16&255,z=65535&J,!((D=J>>>24)<=ne);){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(z<16)K>>>=D,ne-=D,L.lens[L.have++]=z;else{if(z===16){for(V=D+2;ne<V;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(K>>>=D,ne-=D,L.have===0){I.msg="invalid bit length repeat",L.mode=30;break}O=L.lens[L.have-1],_e=3+(3&K),K>>>=2,ne-=2}else if(z===17){for(V=D+3;ne<V;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}ne-=D,O=0,_e=3+(7&(K>>>=D)),K>>>=3,ne-=3}else{for(V=D+7;ne<V;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}ne-=D,O=0,_e=11+(127&(K>>>=D)),K>>>=7,ne-=7}if(L.have+_e>L.nlen+L.ndist){I.msg="invalid bit length repeat",L.mode=30;break}for(;_e--;)L.lens[L.have++]=O}}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,Q={bits:L.lenbits},G=d(u,L.lens,0,L.nlen,L.lencode,0,L.work,Q),L.lenbits=Q.bits,G){I.msg="invalid literal/lengths set",L.mode=30;break}if(L.distbits=6,L.distcode=L.distdyn,Q={bits:L.distbits},G=d(m,L.lens,L.nlen,L.ndist,L.distcode,0,L.work,Q),L.distbits=Q.bits,G){I.msg="invalid distances set",L.mode=30;break}if(L.mode=20,X===6)break e;case 20:L.mode=21;case 21:if(6<=le&&258<=ue){I.next_out=me,I.avail_out=ue,I.next_in=ee,I.avail_in=le,L.hold=K,L.bits=ne,c(I,be),me=I.next_out,ae=I.output,ue=I.avail_out,ee=I.next_in,te=I.input,le=I.avail_in,K=L.hold,ne=L.bits,L.mode===12&&(L.back=-1);break}for(L.back=0;j=(J=L.lencode[K&(1<<L.lenbits)-1])>>>16&255,z=65535&J,!((D=J>>>24)<=ne);){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(j&&(240&j)==0){for(W=D,q=j,de=z;j=(J=L.lencode[de+((K&(1<<W+q)-1)>>W)])>>>16&255,z=65535&J,!(W+(D=J>>>24)<=ne);){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}K>>>=W,ne-=W,L.back+=W}if(K>>>=D,ne-=D,L.back+=D,L.length=z,j===0){L.mode=26;break}if(32&j){L.back=-1,L.mode=12;break}if(64&j){I.msg="invalid literal/length code",L.mode=30;break}L.extra=15&j,L.mode=22;case 22:if(L.extra){for(V=L.extra;ne<V;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.length+=K&(1<<L.extra)-1,K>>>=L.extra,ne-=L.extra,L.back+=L.extra}L.was=L.length,L.mode=23;case 23:for(;j=(J=L.distcode[K&(1<<L.distbits)-1])>>>16&255,z=65535&J,!((D=J>>>24)<=ne);){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if((240&j)==0){for(W=D,q=j,de=z;j=(J=L.distcode[de+((K&(1<<W+q)-1)>>W)])>>>16&255,z=65535&J,!(W+(D=J>>>24)<=ne);){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}K>>>=W,ne-=W,L.back+=W}if(K>>>=D,ne-=D,L.back+=D,64&j){I.msg="invalid distance code",L.mode=30;break}L.offset=z,L.extra=15&j,L.mode=24;case 24:if(L.extra){for(V=L.extra;ne<V;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}L.offset+=K&(1<<L.extra)-1,K>>>=L.extra,ne-=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(ue===0)break e;if(_e=be-ue,L.offset>_e){if((_e=L.offset-_e)>L.whave&&L.sane){I.msg="invalid distance too far back",L.mode=30;break}B=_e>L.wnext?(_e-=L.wnext,L.wsize-_e):L.wnext-_e,_e>L.length&&(_e=L.length),Y=L.window}else Y=ae,B=me-L.offset,_e=L.length;for(ue<_e&&(_e=ue),ue-=_e,L.length-=_e;ae[me++]=Y[B++],--_e;);L.length===0&&(L.mode=21);break;case 26:if(ue===0)break e;ae[me++]=L.length,ue--,L.mode=21;break;case 27:if(L.wrap){for(;ne<32;){if(le===0)break e;le--,K|=te[ee++]<<ne,ne+=8}if(be-=ue,I.total_out+=be,L.total+=be,be&&(I.adler=L.check=L.flags?l(L.check,ae,be,me-be):o(L.check,ae,be,me-be)),be=ue,(L.flags?K:g(K))!==L.check){I.msg="incorrect data check",L.mode=30;break}ne=K=0}L.mode=28;case 28:if(L.wrap&&L.flags){for(;ne<32;){if(le===0)break e;le--,K+=te[ee++]<<ne,ne+=8}if(K!==(4294967295&L.total)){I.msg="incorrect length check",L.mode=30;break}ne=K=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=me,I.avail_out=ue,I.next_in=ee,I.avail_in=le,L.hold=K,L.bits=ne,(L.wsize||be!==I.avail_out&&L.mode<30&&(L.mode<27||X!==4))&&$(I,I.output,I.next_out,be-I.avail_out)?(L.mode=31,-4):(oe-=I.avail_in,be-=I.avail_out,I.total_in+=oe,I.total_out+=be,L.total+=be,L.wrap&&be&&(I.adler=L.check=L.flags?l(L.check,ae,be,I.next_out-be):o(L.check,ae,be,I.next_out-be)),I.data_type=L.bits+(L.last?64:0)+(L.mode===12?128:0)+(L.mode===20||L.mode===15?256:0),(oe==0&&be===0||X===4)&&G===p&&(G=-5),G)},i.inflateEnd=function(I){if(!I||!I.state)return f;var X=I.state;return X.window&&(X.window=null),I.state=null,p},i.inflateGetHeader=function(I,X){var L;return I&&I.state?(2&(L=I.state).wrap)==0?f:((L.head=X).done=!1,p):f},i.inflateSetDictionary=function(I,X){var L,te=X.length;return I&&I.state?(L=I.state).wrap!==0&&L.mode!==11?f:L.mode===11&&o(1,X,te,0)!==L.check?-3:$(I,X,te,te)?(L.mode=31,-4):(L.havedict=1,p):f},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(n,r,i){var s=n("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],c=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],d=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];r.exports=function(u,m,p,f,y,v,b,g){var _,k,P,N,M,A,T,C,F,$=g.bits,I=0,X=0,L=0,te=0,ae=0,ee=0,me=0,le=0,ue=0,K=0,ne=null,oe=0,be=new s.Buf16(16),_e=new s.Buf16(16),B=null,Y=0;for(I=0;I<=15;I++)be[I]=0;for(X=0;X<f;X++)be[m[p+X]]++;for(ae=$,te=15;1<=te&&be[te]===0;te--);if(te<ae&&(ae=te),te===0)return y[v++]=20971520,y[v++]=20971520,g.bits=1,0;for(L=1;L<te&&be[L]===0;L++);for(ae<L&&(ae=L),I=le=1;I<=15;I++)if(le<<=1,(le-=be[I])<0)return-1;if(0<le&&(u===0||te!==1))return-1;for(_e[1]=0,I=1;I<15;I++)_e[I+1]=_e[I]+be[I];for(X=0;X<f;X++)m[p+X]!==0&&(b[_e[m[p+X]]++]=X);if(A=u===0?(ne=B=b,19):u===1?(ne=o,oe-=257,B=l,Y-=257,256):(ne=c,B=d,-1),I=L,M=v,me=X=K=0,P=-1,N=(ue=1<<(ee=ae))-1,u===1&&852<ue||u===2&&592<ue)return 1;for(;;){for(T=I-me,F=b[X]<A?(C=0,b[X]):b[X]>A?(C=B[Y+b[X]],ne[oe+b[X]]):(C=96,0),_=1<<I-me,L=k=1<<ee;y[M+(K>>me)+(k-=_)]=T<<24|C<<16|F|0,k!==0;);for(_=1<<I-1;K&_;)_>>=1;if(_!==0?(K&=_-1,K+=_):K=0,X++,--be[I]==0){if(I===te)break;I=m[p+b[X]]}if(ae<I&&(K&N)!==P){for(me===0&&(me=ae),M+=L,le=1<<(ee=I-me);ee+me<te&&!((le-=be[ee+me])<=0);)ee++,le<<=1;if(ue+=1<<ee,u===1&&852<ue||u===2&&592<ue)return 1;y[P=K&N]=ae<<24|ee<<16|M-v|0}}return K!==0&&(y[M+K]=I-me<<24|64<<16|0),g.bits=ae,0}},{"../utils/common":41}],51:[function(n,r,i){r.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(n,r,i){var s=n("../utils/common"),o=0,l=1;function c(J){for(var ie=J.length;0<=--ie;)J[ie]=0}var d=0,u=29,m=256,p=m+1+u,f=30,y=19,v=2*p+1,b=15,g=16,_=7,k=256,P=16,N=17,M=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],T=[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],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],F=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],$=new Array(2*(p+2));c($);var I=new Array(2*f);c(I);var X=new Array(512);c(X);var L=new Array(256);c(L);var te=new Array(u);c(te);var ae,ee,me,le=new Array(f);function ue(J,ie,he,fe,se){this.static_tree=J,this.extra_bits=ie,this.extra_base=he,this.elems=fe,this.max_length=se,this.has_stree=J&&J.length}function K(J,ie){this.dyn_tree=J,this.max_code=0,this.stat_desc=ie}function ne(J){return J<256?X[J]:X[256+(J>>>7)]}function oe(J,ie){J.pending_buf[J.pending++]=255&ie,J.pending_buf[J.pending++]=ie>>>8&255}function be(J,ie,he){J.bi_valid>g-he?(J.bi_buf|=ie<<J.bi_valid&65535,oe(J,J.bi_buf),J.bi_buf=ie>>g-J.bi_valid,J.bi_valid+=he-g):(J.bi_buf|=ie<<J.bi_valid&65535,J.bi_valid+=he)}function _e(J,ie,he){be(J,he[2*ie],he[2*ie+1])}function B(J,ie){for(var he=0;he|=1&J,J>>>=1,he<<=1,0<--ie;);return he>>>1}function Y(J,ie,he){var fe,se,U=new Array(b+1),R=0;for(fe=1;fe<=b;fe++)U[fe]=R=R+he[fe-1]<<1;for(se=0;se<=ie;se++){var re=J[2*se+1];re!==0&&(J[2*se]=B(U[re]++,re))}}function D(J){var ie;for(ie=0;ie<p;ie++)J.dyn_ltree[2*ie]=0;for(ie=0;ie<f;ie++)J.dyn_dtree[2*ie]=0;for(ie=0;ie<y;ie++)J.bl_tree[2*ie]=0;J.dyn_ltree[2*k]=1,J.opt_len=J.static_len=0,J.last_lit=J.matches=0}function j(J){8<J.bi_valid?oe(J,J.bi_buf):0<J.bi_valid&&(J.pending_buf[J.pending++]=J.bi_buf),J.bi_buf=0,J.bi_valid=0}function z(J,ie,he,fe){var se=2*ie,U=2*he;return J[se]<J[U]||J[se]===J[U]&&fe[ie]<=fe[he]}function W(J,ie,he){for(var fe=J.heap[he],se=he<<1;se<=J.heap_len&&(se<J.heap_len&&z(ie,J.heap[se+1],J.heap[se],J.depth)&&se++,!z(ie,fe,J.heap[se],J.depth));)J.heap[he]=J.heap[se],he=se,se<<=1;J.heap[he]=fe}function q(J,ie,he){var fe,se,U,R,re=0;if(J.last_lit!==0)for(;fe=J.pending_buf[J.d_buf+2*re]<<8|J.pending_buf[J.d_buf+2*re+1],se=J.pending_buf[J.l_buf+re],re++,fe===0?_e(J,se,ie):(_e(J,(U=L[se])+m+1,ie),(R=A[U])!==0&&be(J,se-=te[U],R),_e(J,U=ne(--fe),he),(R=T[U])!==0&&be(J,fe-=le[U],R)),re<J.last_lit;);_e(J,k,ie)}function de(J,ie){var he,fe,se,U=ie.dyn_tree,R=ie.stat_desc.static_tree,re=ie.stat_desc.has_stree,xe=ie.stat_desc.elems,we=-1;for(J.heap_len=0,J.heap_max=v,he=0;he<xe;he++)U[2*he]!==0?(J.heap[++J.heap_len]=we=he,J.depth[he]=0):U[2*he+1]=0;for(;J.heap_len<2;)U[2*(se=J.heap[++J.heap_len]=we<2?++we:0)]=1,J.depth[se]=0,J.opt_len--,re&&(J.static_len-=R[2*se+1]);for(ie.max_code=we,he=J.heap_len>>1;1<=he;he--)W(J,U,he);for(se=xe;he=J.heap[1],J.heap[1]=J.heap[J.heap_len--],W(J,U,1),fe=J.heap[1],J.heap[--J.heap_max]=he,J.heap[--J.heap_max]=fe,U[2*se]=U[2*he]+U[2*fe],J.depth[se]=(J.depth[he]>=J.depth[fe]?J.depth[he]:J.depth[fe])+1,U[2*he+1]=U[2*fe+1]=se,J.heap[1]=se++,W(J,U,1),2<=J.heap_len;);J.heap[--J.heap_max]=J.heap[1],(function(ye,Ae){var ve,Te,Fe,Ee,Se,je,qe=Ae.dyn_tree,Re=Ae.max_code,Ye=Ae.stat_desc.static_tree,ce=Ae.stat_desc.has_stree,ze=Ae.stat_desc.extra_bits,Ne=Ae.stat_desc.extra_base,Ge=Ae.stat_desc.max_length,$e=0;for(Ee=0;Ee<=b;Ee++)ye.bl_count[Ee]=0;for(qe[2*ye.heap[ye.heap_max]+1]=0,ve=ye.heap_max+1;ve<v;ve++)Ge<(Ee=qe[2*qe[2*(Te=ye.heap[ve])+1]+1]+1)&&(Ee=Ge,$e++),qe[2*Te+1]=Ee,Re<Te||(ye.bl_count[Ee]++,Se=0,Ne<=Te&&(Se=ze[Te-Ne]),je=qe[2*Te],ye.opt_len+=je*(Ee+Se),ce&&(ye.static_len+=je*(Ye[2*Te+1]+Se)));if($e!==0){do{for(Ee=Ge-1;ye.bl_count[Ee]===0;)Ee--;ye.bl_count[Ee]--,ye.bl_count[Ee+1]+=2,ye.bl_count[Ge]--,$e-=2}while(0<$e);for(Ee=Ge;Ee!==0;Ee--)for(Te=ye.bl_count[Ee];Te!==0;)Re<(Fe=ye.heap[--ve])||(qe[2*Fe+1]!==Ee&&(ye.opt_len+=(Ee-qe[2*Fe+1])*qe[2*Fe],qe[2*Fe+1]=Ee),Te--)}})(J,ie),Y(U,we,J.bl_count)}function O(J,ie,he){var fe,se,U=-1,R=ie[1],re=0,xe=7,we=4;for(R===0&&(xe=138,we=3),ie[2*(he+1)+1]=65535,fe=0;fe<=he;fe++)se=R,R=ie[2*(fe+1)+1],++re<xe&&se===R||(re<we?J.bl_tree[2*se]+=re:se!==0?(se!==U&&J.bl_tree[2*se]++,J.bl_tree[2*P]++):re<=10?J.bl_tree[2*N]++:J.bl_tree[2*M]++,U=se,we=(re=0)===R?(xe=138,3):se===R?(xe=6,3):(xe=7,4))}function G(J,ie,he){var fe,se,U=-1,R=ie[1],re=0,xe=7,we=4;for(R===0&&(xe=138,we=3),fe=0;fe<=he;fe++)if(se=R,R=ie[2*(fe+1)+1],!(++re<xe&&se===R)){if(re<we)for(;_e(J,se,J.bl_tree),--re!=0;);else se!==0?(se!==U&&(_e(J,se,J.bl_tree),re--),_e(J,P,J.bl_tree),be(J,re-3,2)):re<=10?(_e(J,N,J.bl_tree),be(J,re-3,3)):(_e(J,M,J.bl_tree),be(J,re-11,7));U=se,we=(re=0)===R?(xe=138,3):se===R?(xe=6,3):(xe=7,4)}}c(le);var Q=!1;function V(J,ie,he,fe){be(J,(d<<1)+(fe?1:0),3),(function(se,U,R,re){j(se),oe(se,R),oe(se,~R),s.arraySet(se.pending_buf,se.window,U,R,se.pending),se.pending+=R})(J,ie,he)}i._tr_init=function(J){Q||((function(){var ie,he,fe,se,U,R=new Array(b+1);for(se=fe=0;se<u-1;se++)for(te[se]=fe,ie=0;ie<1<<A[se];ie++)L[fe++]=se;for(L[fe-1]=se,se=U=0;se<16;se++)for(le[se]=U,ie=0;ie<1<<T[se];ie++)X[U++]=se;for(U>>=7;se<f;se++)for(le[se]=U<<7,ie=0;ie<1<<T[se]-7;ie++)X[256+U++]=se;for(he=0;he<=b;he++)R[he]=0;for(ie=0;ie<=143;)$[2*ie+1]=8,ie++,R[8]++;for(;ie<=255;)$[2*ie+1]=9,ie++,R[9]++;for(;ie<=279;)$[2*ie+1]=7,ie++,R[7]++;for(;ie<=287;)$[2*ie+1]=8,ie++,R[8]++;for(Y($,p+1,R),ie=0;ie<f;ie++)I[2*ie+1]=5,I[2*ie]=B(ie,5);ae=new ue($,A,m+1,p,b),ee=new ue(I,T,0,f,b),me=new ue(new Array(0),C,0,y,_)})(),Q=!0),J.l_desc=new K(J.dyn_ltree,ae),J.d_desc=new K(J.dyn_dtree,ee),J.bl_desc=new K(J.bl_tree,me),J.bi_buf=0,J.bi_valid=0,D(J)},i._tr_stored_block=V,i._tr_flush_block=function(J,ie,he,fe){var se,U,R=0;0<J.level?(J.strm.data_type===2&&(J.strm.data_type=(function(re){var xe,we=4093624447;for(xe=0;xe<=31;xe++,we>>>=1)if(1&we&&re.dyn_ltree[2*xe]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return l;for(xe=32;xe<m;xe++)if(re.dyn_ltree[2*xe]!==0)return l;return o})(J)),de(J,J.l_desc),de(J,J.d_desc),R=(function(re){var xe;for(O(re,re.dyn_ltree,re.l_desc.max_code),O(re,re.dyn_dtree,re.d_desc.max_code),de(re,re.bl_desc),xe=y-1;3<=xe&&re.bl_tree[2*F[xe]+1]===0;xe--);return re.opt_len+=3*(xe+1)+5+5+4,xe})(J),se=J.opt_len+3+7>>>3,(U=J.static_len+3+7>>>3)<=se&&(se=U)):se=U=he+5,he+4<=se&&ie!==-1?V(J,ie,he,fe):J.strategy===4||U===se?(be(J,2+(fe?1:0),3),q(J,$,I)):(be(J,4+(fe?1:0),3),(function(re,xe,we,ye){var Ae;for(be(re,xe-257,5),be(re,we-1,5),be(re,ye-4,4),Ae=0;Ae<ye;Ae++)be(re,re.bl_tree[2*F[Ae]+1],3);G(re,re.dyn_ltree,xe-1),G(re,re.dyn_dtree,we-1)})(J,J.l_desc.max_code+1,J.d_desc.max_code+1,R+1),q(J,J.dyn_ltree,J.dyn_dtree)),D(J),fe&&j(J)},i._tr_tally=function(J,ie,he){return J.pending_buf[J.d_buf+2*J.last_lit]=ie>>>8&255,J.pending_buf[J.d_buf+2*J.last_lit+1]=255&ie,J.pending_buf[J.l_buf+J.last_lit]=255&he,J.last_lit++,ie===0?J.dyn_ltree[2*he]++:(J.matches++,ie--,J.dyn_ltree[2*(L[he]+m+1)]++,J.dyn_dtree[2*ne(ie)]++),J.last_lit===J.lit_bufsize-1},i._tr_align=function(J){be(J,2,3),_e(J,k,$),(function(ie){ie.bi_valid===16?(oe(ie,ie.bi_buf),ie.bi_buf=0,ie.bi_valid=0):8<=ie.bi_valid&&(ie.pending_buf[ie.pending++]=255&ie.bi_buf,ie.bi_buf>>=8,ie.bi_valid-=8)})(J)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,l){if(!o.setImmediate){var c,d,u,m,p=1,f={},y=!1,v=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(P){process.nextTick(function(){_(P)})}:(function(){if(o.postMessage&&!o.importScripts){var P=!0,N=o.onmessage;return o.onmessage=function(){P=!1},o.postMessage("","*"),o.onmessage=N,P}})()?(m="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",k,!1):o.attachEvent("onmessage",k),function(P){o.postMessage(m+P,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(P){_(P.data)},function(P){u.port2.postMessage(P)}):v&&"onreadystatechange"in v.createElement("script")?(d=v.documentElement,function(P){var N=v.createElement("script");N.onreadystatechange=function(){_(P),N.onreadystatechange=null,d.removeChild(N),N=null},d.appendChild(N)}):function(P){setTimeout(_,0,P)},b.setImmediate=function(P){typeof P!="function"&&(P=new Function(""+P));for(var N=new Array(arguments.length-1),M=0;M<N.length;M++)N[M]=arguments[M+1];var A={callback:P,args:N};return f[p]=A,c(p),p++},b.clearImmediate=g}function g(P){delete f[P]}function _(P){if(y)setTimeout(_,0,P);else{var N=f[P];if(N){y=!0;try{(function(M){var A=M.callback,T=M.args;switch(T.length){case 0:A();break;case 1:A(T[0]);break;case 2:A(T[0],T[1]);break;case 3:A(T[0],T[1],T[2]);break;default:A.apply(l,T)}})(N)}finally{g(P),y=!1}}}}function k(P){P.source===o&&typeof P.data=="string"&&P.data.indexOf(m)===0&&_(+P.data.slice(m.length))}})(typeof self>"u"?s===void 0?this:s:self)}).call(this,typeof k_<"u"?k_:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Gj)),Gj.exports}var V1e=$1e();const G1e=rc(V1e);function W1e(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 AH=W1e;async function MH(t,e=0){const n=[],r=t.getElementsByTagName("mesh");for(let i=0;i<r.length;i++){const s=r[i],o=[],l=[],c=s.getElementsByTagName("vertex");for(let u=0;u<c.length;u++){const m=c[u];o.push(parseFloat(m.getAttribute("x")||"0"),parseFloat(m.getAttribute("y")||"0"),parseFloat(m.getAttribute("z")||"0"))}const d=s.getElementsByTagName("triangle");for(let u=0;u<d.length;u++){const m=d[u];l.push(parseInt(m.getAttribute("v1")||"0"),parseInt(m.getAttribute("v2")||"0"),parseInt(m.getAttribute("v3")||"0"))}o.length>0&&l.length>0&&n.push({vertices:o,triangles:l,extruder:e})}return n}function jH(t){const e=Array.from(t.attributes).find(r=>{const i=r.name.toLowerCase();return i==="plate_id"||i==="plater_id"||i==="plateid"||i==="platerid"||i.endsWith(":plate_id")||i.endsWith(":plater_id")});if(!e?.value)return null;const n=Number.parseInt(e.value,10);return Number.isFinite(n)?n:null}async function K1e(t){let e;try{e=await G1e.loadAsync(t)}catch{throw new Error("Unsupported file format")}const n=new Map,r=[],i=new Map,s=new Map,o=new DOMParser;async function l(k){const P=k.startsWith("/")?k.slice(1):k,N=e.files[P];if(!N)return null;const M=await N.async("string");return o.parseFromString(M,"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"),P=o.parseFromString(k,"application/xml"),N=P.getElementsByTagName("object");for(let A=0;A<N.length;A++){const T=N[A],C=T.getAttribute("id");if(!C)continue;const F=Array.from(T.children).filter(L=>L.tagName==="metadata"&&L.getAttribute("key")==="extruder");if(F.length>0){const L=F[0].getAttribute("value");L&&c.set(C,Math.max(0,parseInt(L,10)-1))}const I=Array.from(T.children).find(L=>L.tagName==="metadata"&&L.getAttribute("key")==="name")?.getAttribute("value");I&&u.set(C,I);const X=T.getElementsByTagName("part");for(let L=0;L<X.length;L++){const te=X[L],ae=te.getAttribute("id");if(!ae)continue;const ee=Array.from(te.children).filter(me=>me.tagName==="metadata"&&me.getAttribute("key")==="extruder");if(ee.length>0){const me=ee[0].getAttribute("value");me&&d.set(`${C}:${ae}`,Math.max(0,parseInt(me,10)-1))}}}const M=P.getElementsByTagName("plate");for(let A=0;A<M.length;A++){const T=M[A];let C=null;const F=T.getElementsByTagName("metadata");let $=0,I=0;for(let L=0;L<F.length;L++){const te=F[L],ae=te.getAttribute("key");if(ae==="plater_id"||ae==="plate_id"){const ee=te.getAttribute("value");if(ee){const me=Number.parseInt(ee,10);Number.isFinite(me)&&(C=me)}}else if(ae==="pos_x"){const ee=te.getAttribute("value"),me=ee?Number.parseFloat(ee):Number.NaN;Number.isFinite(me)&&($=me)}else if(ae==="pos_y"){const ee=te.getAttribute("value"),me=ee?Number.parseFloat(ee):Number.NaN;Number.isFinite(me)&&(I=me)}}if(C==null)continue;($!==0||I!==0)&&s.set(C,{offsetX:$,offsetY:I});const X=T.getElementsByTagName("model_instance");for(let L=0;L<X.length;L++){const ae=X[L].getElementsByTagName("metadata");for(let ee=0;ee<ae.length;ee++){const me=ae[ee];if(me.getAttribute("key")==="object_id"){const le=me.getAttribute("value");le&&m.set(le,C)}}}}}catch{}const f=new Map,y=Object.keys(e.files).filter(k=>k.startsWith("Metadata/plate_")&&k.endsWith(".json"));for(const k of y){const P=k.match(/^Metadata\/plate_(\d+)\.json$/);if(!P)continue;const N=Number.parseInt(P[1],10);if(Number.isFinite(N))try{const M=await e.files[k].async("string"),A=JSON.parse(M),T=A.bbox_objects??[];for(const C of T)C?.name&&f.set(C.name,N);if(Array.isArray(A.bbox_all)&&A.bbox_all.length>=4){const[C,F,$,I]=A.bbox_all;[C,F,$,I].every(X=>Number.isFinite(X))&&i.set(N,{minX:C,minY:F,maxX:$,maxY:I})}}catch{}}const v=Object.keys(e.files).find(k=>k==="3D/3dmodel.model"||k.endsWith("/3dmodel.model"));if(!v){const k=Object.keys(e.files).find(P=>P.endsWith(".model"));if(k){const P=await l(k);if(P){const N=await MH(P,0);N.length>0&&n.set("1",{id:"1",meshes:N,defaultExtruder:0})}}return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s}}const b=await l(v);if(!b)return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s};const g=b.getElementsByTagName("object");for(let k=0;k<g.length;k++){const P=g[k],N=P.getAttribute("id");if(!N)continue;const M=jH(P)??m.get(N)??null;let A=c.get(N)??-1;if(A<0){const $=P.getAttribute("p:extruder")||P.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","extruder")||"1";A=Math.max(0,parseInt($,10)-1)}const T=[],C=P.getElementsByTagName("mesh");for(let $=0;$<C.length;$++){const I=C[$],X=[],L=[],te=I.getElementsByTagName("vertex");for(let ee=0;ee<te.length;ee++){const me=te[ee];X.push(parseFloat(me.getAttribute("x")||"0"),parseFloat(me.getAttribute("y")||"0"),parseFloat(me.getAttribute("z")||"0"))}const ae=I.getElementsByTagName("triangle");for(let ee=0;ee<ae.length;ee++){const me=ae[ee];L.push(parseInt(me.getAttribute("v1")||"0"),parseInt(me.getAttribute("v2")||"0"),parseInt(me.getAttribute("v3")||"0"))}X.length>0&&L.length>0&&T.push({vertices:X,triangles:L,extruder:A})}const F=P.getElementsByTagName("component");for(let $=0;$<F.length;$++){const I=F[$],X=I.getAttribute("p:path")||I.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","path"),L=I.getAttribute("objectid");if(X){const te=await l(X);if(te){const ae=L?`${N}:${L}`:null,ee=ae?d.get(ae)??A:A,me=await MH(te,ee),le=I.getAttribute("transform"),ue=AH(le);for(const K of me)if(le){const ne=[];for(let oe=0;oe<K.vertices.length;oe+=3){const be=new At(K.vertices[oe],K.vertices[oe+1],K.vertices[oe+2]);be.applyMatrix4(ue),ne.push(be.x,be.y,be.z)}T.push({vertices:ne,triangles:K.triangles,extruder:K.extruder})}else T.push(K)}}}T.length>0&&n.set(N,{id:N,meshes:T,defaultExtruder:A,plateId:M})}const _=b.getElementsByTagName("build");if(_.length>0){const k=_[0].getElementsByTagName("item");for(let P=0;P<k.length;P++){const N=k[P],M=N.getAttribute("objectid");if(!M)continue;const A=AH(N.getAttribute("transform")),T=jH(N),C=n.get(M)?.plateId??null,F=u.get(M),$=F?f.get(F)??null:null;r.push({objectId:M,transform:A,plateId:T??C??$??null})}}return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s}}function EH(t){const e=new Ql,n=new Float32Array(t.vertices.length);for(let r=0;r<t.vertices.length;r+=3)n[r]=t.vertices[r],n[r+1]=t.vertices[r+2],n[r+2]=t.vertices[r+1];return e.setAttribute("position",new Zs(n,3)),e.setIndex(t.triangles),e.computeVertexNormals(),e}function Y1e(t){t.traverse(e=>{if(e instanceof Zl)if(e.geometry.dispose(),Array.isArray(e.material))for(const n of e.material)n.dispose();else e.material.dispose()})}function X1e(t,e,n){const{objects:r,buildItems:i}=t,s=new Yb,o=m=>{const f=n?.[m]||"#00ae42",y=new sr(f);return new mZ({color:y,shininess:30,flatShading:!1})},l=new Map,c=i.some(m=>m.plateId!=null),d=e==null||!c?i:i.filter(m=>m.plateId===e),u=d.length>0?d:i;if(u.length>0)for(const m of u){const p=r.get(m.objectId);if(p)for(const f of p.meshes){const y=m.extruder??f.extruder,v=[];for(let g=0;g<f.vertices.length;g+=3){const _=new At(f.vertices[g],f.vertices[g+1],f.vertices[g+2]);_.applyMatrix4(m.transform),v.push(_.x,_.y,_.z)}const b=EH({vertices:v,triangles:f.triangles});l.has(y)||l.set(y,[]),l.get(y).push(b)}}else for(const m of r.values())for(const p of m.meshes){const f=p.extruder,y=EH(p);l.has(f)||l.set(f,[]),l.get(f).push(y)}for(const[m,p]of l){if(p.length===0)continue;const f=p.length===1?p[0]:H1e(p,!1);if(f){const y=o(m),v=new Zl(f,y);s.add(v)}if(p.length>1)for(const y of p)y.dispose()}return s}function wZ({url:t,fileType:e,buildVolume:n={x:256,y:256,z:256},filamentColors:r,selectedPlateId:i=null,className:s=""}){const{t:o}=Lt(),l=w.useRef(null),c=w.useRef(null),d=w.useRef(null),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=w.useRef(null),y=w.useRef(null),[v,b]=w.useState(!0),[g,_]=w.useState(null),[k,P]=w.useState(null),[N,M]=w.useState(null);w.useEffect(()=>{if(!l.current)return;const C=l.current,F=C.clientWidth,$=C.clientHeight,I=new Sve;I.background=new sr(1710618),d.current=I;const X=new Rl(45,F/$,.1,1e4);X.position.set(150,150,150),u.current=X;const L=new P1e({antialias:!0});L.setSize(F,$),L.setPixelRatio(window.devicePixelRatio),C.appendChild(L.domElement),c.current=L;const te=new A1e(X,L.domElement);te.enableDamping=!0,te.dampingFactor=.05,m.current=te;const ae=new Ove(16777215,.6);I.add(ae);const ee=new J6(16777215,.8);ee.position.set(100,100,100),I.add(ee);const me=new J6(16777215,.4);me.position.set(-100,50,-100),I.add(me);const le=Math.max(n.x,n.y),ue=Math.ceil(le/16),K=new zve(le,ue,4473924,3355443);I.add(K),y.current=K;const ne=new RO(n.x,n.y),oe=new EO({color:44610,transparent:!0,opacity:.15,side:ud}),be=new Zl(ne,oe);be.rotation.x=-Math.PI/2,be.position.y=-.5,I.add(be),f.current=be;let _e;const B=()=>{_e=requestAnimationFrame(B),te.update(),L.render(I,X)};B(),b(!0),_(null),P(null),M(null);const Y=(e||t.split("?")[0].split(".").pop()||"").toLowerCase(),D={},j=Yu();j&&(D.Authorization=`Bearer ${j}`),Y==="stl"?fetch(t,{headers:D}).then(q=>{if(!q.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return q.arrayBuffer()}).then(q=>{const O=new q1e().parse(q);O.computeVertexNormals(),O.rotateX(-Math.PI/2),M(O)}).catch(q=>{_(q.message),b(!1)}):Y==="3mf"?fetch(t,{headers:D}).then(q=>{if(!q.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return q.arrayBuffer()}).then(K1e).then(q=>{if(q.objects.size===0)throw new Error(o("modelViewer.errors.noMeshes"));P(q)}).catch(q=>{_(q.message),b(!1)}):(_(o("modelViewer.errors.unsupportedFormat")),b(!1));const z=()=>{if(!C)return;const q=C.clientWidth,de=C.clientHeight;q===0||de===0||(X.aspect=q/de,X.updateProjectionMatrix(),L.setSize(q,de))};window.addEventListener("resize",z);const W=new ResizeObserver(()=>{z()});return W.observe(C),()=>{window.removeEventListener("resize",z),W.disconnect(),cancelAnimationFrame(_e),te.dispose(),L.dispose(),C.removeChild(L.domElement),p.current=null,f.current=null,y.current=null}},[t,n,e,o]),w.useEffect(()=>{if(!d.current||!u.current||!m.current||!k&&!N)return;p.current&&(d.current.remove(p.current),Y1e(p.current));const C=!!N,F=C?(()=>{const Y=r?.[0]||"#00ae42",D=new mZ({color:new sr(Y),shininess:30}),j=new Zl(N,D),z=new Yb;return z.add(j),z})():X1e(k,i??null,r);p.current=F,d.current.add(F);const $=new Fh().setFromObject(F),I=$.getCenter(new At);F.position.y=-$.min.y;const X=!C&&i!=null&&k.buildItems.length>0?k.plateBounds.get(i):void 0,L=!C&&i!=null?k.plateOffsets.get(i):void 0,te=C||k.buildItems.length===0||i!=null&&!X&&!L,ae=te?-I.x:0,ee=te?-I.z:0;let me=0,le=0;if(!C&&i!=null&&k.buildItems.length>0&&X){const Y=new Fh().setFromObject(F);me=Y.min.x-X.minX,le=Y.min.z-X.minY}const ue=n.x/2,K=n.y/2;!C&&i!=null&&k.buildItems.length>0&&X?(F.position.x=ae-me,F.position.z=ee-le):!C&&i!=null&&L?(F.position.x=ae+(ue-L.offsetX),F.position.z=ee+(K-L.offsetY)):te?(F.position.x=ae+ue,F.position.z=ee+K):(F.position.x=ae,F.position.z=ee),f.current&&(f.current.position.x=ue,f.current.position.z=K),y.current&&(y.current.position.x=ue,y.current.position.z=K);const ne=new Fh().setFromObject(F),oe=ne.getCenter(new At),be=ne.getSize(new At),B=Math.max(be.x,be.y,be.z)*1.8;u.current.position.set(oe.x+B*.7,oe.y+B*.5,oe.z+B*.7),m.current.target.copy(oe),m.current.update(),b(!1)},[k,N,i,r,n]);const A=()=>{u.current&&m.current&&(u.current.position.set(150,150,150),m.current.target.set(0,50,0),m.current.update())},T=C=>{u.current&&u.current.position.multiplyScalar(C)};return a.jsxs("div",{className:`relative ${s}`,children:[a.jsx("div",{ref:l,className:"w-full h-full min-h-[400px]"}),v&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}),g&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx("p",{className:"text-red-400",children:g})}),!v&&!g&&a.jsxs("div",{className:"absolute bottom-4 right-4 flex gap-2",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>T(.8),children:a.jsx(bO,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>T(1.25),children:a.jsx(xO,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:A,children:a.jsx(jo,{className:"w-4 h-4"})})]})]})}const DP="159",ub={ROTATE:0,DOLLY:1,PAN:2},mb={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Q1e=0,DH=1,Z1e=2,SZ=1,J1e=2,xu=3,Gh=0,Po=1,ku=2,Rh=0,sx=1,FH=2,RH=3,LH=4,eke=5,ef=100,tke=101,nke=102,OH=103,IH=104,rke=200,ake=201,ike=202,ske=203,zF=204,UF=205,oke=206,lke=207,cke=208,dke=209,uke=210,mke=211,hke=212,pke=213,fke=214,gke=0,bke=1,xke=2,hN=3,yke=4,vke=5,wke=6,Ske=7,IO=0,_ke=1,kke=2,Lh=0,Nke=1,Cke=2,Pke=3,Tke=4,Ake=5,_Z=300,Tx=301,Ax=302,BF=303,HF=304,FP=306,qF=1e3,wc=1001,$F=1002,ns=1003,zH=1004,Wj=1005,Ll=1006,Mke=1007,q0=1008,Oh=1009,jke=1010,Eke=1011,zO=1012,kZ=1013,vh=1014,ju=1015,$0=1016,NZ=1017,CZ=1018,wf=1020,Dke=1021,Ol=1023,Fke=1024,Rke=1025,Sf=1026,Mx=1027,Lke=1028,PZ=1029,Oke=1030,TZ=1031,AZ=1033,Kj=33776,Yj=33777,Xj=33778,Qj=33779,UH=35840,BH=35841,HH=35842,qH=35843,MZ=36196,$H=37492,VH=37496,GH=37808,WH=37809,KH=37810,YH=37811,XH=37812,QH=37813,ZH=37814,JH=37815,eq=37816,tq=37817,nq=37818,rq=37819,aq=37820,iq=37821,Zj=36492,sq=36494,oq=36495,Ike=36283,lq=36284,cq=36285,dq=36286,jZ=3e3,_f=3001,zke=3200,Uke=3201,EZ=0,Bke=1,Il="",rs="srgb",Qu="srgb-linear",UO="display-p3",RP="display-p3-linear",pN="linear",ua="srgb",fN="rec709",gN="p3",hb=7680,uq=519,Hke=512,qke=513,$ke=514,DZ=515,Vke=516,Gke=517,Wke=518,Kke=519,VF=35044,mq="300 es",GF=1035,fd=2e3,V0=2001;class ug{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(n)===-1&&r[e].push(n)}hasEventListener(e,n){if(this._listeners===void 0)return!1;const r=this._listeners;return r[e]!==void 0&&r[e].indexOf(n)!==-1}removeEventListener(e,n){if(this._listeners===void 0)return;const i=this._listeners[e];if(i!==void 0){const s=i.indexOf(n);s!==-1&&i.splice(s,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const r=this._listeners[e.type];if(r!==void 0){e.target=this;const i=r.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}}const _s=["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 hq=1234567;const o0=Math.PI/180,G0=180/Math.PI;function zu(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(_s[t&255]+_s[t>>8&255]+_s[t>>16&255]+_s[t>>24&255]+"-"+_s[e&255]+_s[e>>8&255]+"-"+_s[e>>16&15|64]+_s[e>>24&255]+"-"+_s[n&63|128]+_s[n>>8&255]+"-"+_s[n>>16&255]+_s[n>>24&255]+_s[r&255]+_s[r>>8&255]+_s[r>>16&255]+_s[r>>24&255]).toLowerCase()}function as(t,e,n){return Math.max(e,Math.min(n,t))}function BO(t,e){return(t%e+e)%e}function Yke(t,e,n,r,i){return r+(t-e)*(i-r)/(n-e)}function Xke(t,e,n){return t!==e?(n-t)/(e-t):0}function l0(t,e,n){return(1-n)*t+n*e}function Qke(t,e,n,r){return l0(t,e,1-Math.exp(-n*r))}function Zke(t,e=1){return e-Math.abs(BO(t,e*2)-e)}function Jke(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function eNe(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function tNe(t,e){return t+Math.floor(Math.random()*(e-t+1))}function nNe(t,e){return t+Math.random()*(e-t)}function rNe(t){return t*(.5-Math.random())}function aNe(t){t!==void 0&&(hq=t);let e=hq+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function iNe(t){return t*o0}function sNe(t){return t*G0}function WF(t){return(t&t-1)===0&&t!==0}function oNe(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function bN(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function lNe(t,e,n,r,i){const s=Math.cos,o=Math.sin,l=s(n/2),c=o(n/2),d=s((e+r)/2),u=o((e+r)/2),m=s((e-r)/2),p=o((e-r)/2),f=s((r-e)/2),y=o((r-e)/2);switch(i){case"XYX":t.set(l*u,c*m,c*p,l*d);break;case"YZY":t.set(c*p,l*u,c*m,l*d);break;case"ZXZ":t.set(c*m,c*p,l*u,l*d);break;case"XZX":t.set(l*u,c*y,c*f,l*d);break;case"YXY":t.set(c*f,l*u,c*y,l*d);break;case"ZYZ":t.set(c*y,c*f,l*u,l*d);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function md(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 qr(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 FZ={DEG2RAD:o0,RAD2DEG:G0,generateUUID:zu,clamp:as,euclideanModulo:BO,mapLinear:Yke,inverseLerp:Xke,lerp:l0,damp:Qke,pingpong:Zke,smoothstep:Jke,smootherstep:eNe,randInt:tNe,randFloat:nNe,randFloatSpread:rNe,seededRandom:aNe,degToRad:iNe,radToDeg:sNe,isPowerOfTwo:WF,ceilPowerOfTwo:oNe,floorPowerOfTwo:bN,setQuaternionFromProperEuler:lNe,normalize:qr,denormalize:md};class Hn{constructor(e=0,n=0){Hn.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(as(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class lr{constructor(e,n,r,i,s,o,l,c,d){lr.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d)}set(e,n,r,i,s,o,l,c,d){const u=this.elements;return u[0]=e,u[1]=i,u[2]=l,u[3]=n,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=d,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],d=r[1],u=r[4],m=r[7],p=r[2],f=r[5],y=r[8],v=i[0],b=i[3],g=i[6],_=i[1],k=i[4],P=i[7],N=i[2],M=i[5],A=i[8];return s[0]=o*v+l*_+c*N,s[3]=o*b+l*k+c*M,s[6]=o*g+l*P+c*A,s[1]=d*v+u*_+m*N,s[4]=d*b+u*k+m*M,s[7]=d*g+u*P+m*A,s[2]=p*v+f*_+y*N,s[5]=p*b+f*k+y*M,s[8]=p*g+f*P+y*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],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8];return n*o*u-n*l*d-r*s*u+r*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=u*o-l*d,p=l*c-u*s,f=d*s-o*c,y=n*m+r*p+i*f;if(y===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/y;return e[0]=m*v,e[1]=(i*d-u*r)*v,e[2]=(l*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*c)*v,e[5]=(i*s-l*n)*v,e[6]=f*v,e[7]=(r*c-d*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(r*c,r*d,-r*(c*o+d*l)+o+e,-i*d,i*c,-i*(-d*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(Jj.makeScale(e,n)),this}rotate(e){return this.premultiply(Jj.makeRotation(-e)),this}translate(e,n){return this.premultiply(Jj.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<9;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Jj=new lr;function RZ(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function xN(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function cNe(){const t=xN("canvas");return t.style.display="block",t}const pq={};function c0(t){t in pq||(pq[t]=!0,console.warn(t))}const fq=new lr().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),gq=new lr().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),e1={[Qu]:{transfer:pN,primaries:fN,toReference:t=>t,fromReference:t=>t},[rs]:{transfer:ua,primaries:fN,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[RP]:{transfer:pN,primaries:gN,toReference:t=>t.applyMatrix3(gq),fromReference:t=>t.applyMatrix3(fq)},[UO]:{transfer:ua,primaries:gN,toReference:t=>t.convertSRGBToLinear().applyMatrix3(gq),fromReference:t=>t.applyMatrix3(fq).convertLinearToSRGB()}},dNe=new Set([Qu,RP]),$r={enabled:!0,_workingColorSpace:Qu,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(!dNe.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(this.enabled===!1||e===n||!e||!n)return t;const r=e1[e].toReference,i=e1[n].fromReference;return i(r(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return e1[t].primaries},getTransfer:function(t){return t===Il?pN:e1[t].transfer}};function ox(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function eE(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let pb;class LZ{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{pb===void 0&&(pb=xN("canvas")),pb.width=e.width,pb.height=e.height;const r=pb.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=pb}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=xN("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=ox(s[o]/255)*255;return r.putImageData(i,0,0),n}else if(e.data){const n=e.data.slice(0);for(let r=0;r<n.length;r++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[r]=Math.floor(ox(n[r]/255)*255):n[r]=ox(n[r]);return{data:n,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let uNe=0;class OZ{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:uNe++}),this.uuid=zu(),this.data=e,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const r={uuid:this.uuid,url:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,l=i.length;o<l;o++)i[o].isDataTexture?s.push(tE(i[o].image)):s.push(tE(i[o]))}else s=tE(i);r.url=s}return n||(e.images[this.uuid]=r),r}}function tE(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?LZ.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 mNe=0;class To extends ug{constructor(e=To.DEFAULT_IMAGE,n=To.DEFAULT_MAPPING,r=wc,i=wc,s=Ll,o=q0,l=Ol,c=Oh,d=To.DEFAULT_ANISOTROPY,u=Il){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:mNe++}),this.uuid=zu(),this.name="",this.source=new OZ(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new Hn(0,0),this.repeat=new Hn(1,1),this.center=new Hn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new lr,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof u=="string"?this.colorSpace=u:(c0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=u===_f?rs:Il),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const r={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==_Z)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case qF:e.x=e.x-Math.floor(e.x);break;case wc:e.x=e.x<0?0:1;break;case $F:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case qF:e.y=e.y-Math.floor(e.y);break;case wc:e.y=e.y<0?0:1;break;case $F: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 c0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===rs?_f:jZ}set encoding(e){c0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===_f?rs:Il}}To.DEFAULT_IMAGE=null;To.DEFAULT_MAPPING=_Z;To.DEFAULT_ANISOTROPY=1;class Gr{constructor(e=0,n=0,r=0,i=1){Gr.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,i){return this.x=e,this.y=n,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+o[15]*s,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],y=c[9],v=c[2],b=c[6],g=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-v)<.01&&Math.abs(y-b)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+v)<.1&&Math.abs(y+b)<.1&&Math.abs(d+f+g-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const k=(d+1)/2,P=(f+1)/2,N=(g+1)/2,M=(u+p)/4,A=(m+v)/4,T=(y+b)/4;return k>P&&k>N?k<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(k),i=M/r,s=A/r):P>N?P<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(P),r=M/i,s=T/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=A/s,i=T/s),this.set(r,i,s,n),this}let _=Math.sqrt((b-y)*(b-y)+(m-v)*(m-v)+(p-u)*(p-u));return Math.abs(_)<.001&&(_=1),this.x=(b-y)/_,this.y=(m-v)/_,this.z=(p-u)/_,this.w=Math.acos((d+f+g-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this.w=Math.max(e.w,Math.min(n.w,this.w)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this.w=Math.max(e,Math.min(n,this.w)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class hNe extends ug{constructor(e=1,n=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new Gr(0,0,e,n),this.scissorTest=!1,this.viewport=new Gr(0,0,e,n);const i={width:e,height:n,depth:1};r.encoding!==void 0&&(c0("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),r.colorSpace=r.encoding===_f?rs:Il),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ll,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},r),this.texture=new To(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=r.generateMipmaps,this.texture.internalFormat=r.internalFormat,this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.depthTexture=r.depthTexture,this.samples=r.samples}setSize(e,n,r=1){(this.width!==e||this.height!==n||this.depth!==r)&&(this.width=e,this.height=n,this.depth=r,this.texture.image.width=e,this.texture.image.height=n,this.texture.image.depth=r,this.dispose()),this.viewport.set(0,0,e,n),this.scissor.set(0,0,e,n)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const n=Object.assign({},e.texture.image);return this.texture.source=new OZ(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 Vf extends hNe{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}}class IZ extends To{constructor(e=null,n=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=ns,this.minFilter=ns,this.wrapR=wc,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class pNe extends To{constructor(e=null,n=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=ns,this.minFilter=ns,this.wrapR=wc,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Gf{constructor(e=0,n=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=i}static slerpFlat(e,n,r,i,s,o,l){let c=r[i+0],d=r[i+1],u=r[i+2],m=r[i+3];const p=s[o+0],f=s[o+1],y=s[o+2],v=s[o+3];if(l===0){e[n+0]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m;return}if(l===1){e[n+0]=p,e[n+1]=f,e[n+2]=y,e[n+3]=v;return}if(m!==v||c!==p||d!==f||u!==y){let b=1-l;const g=c*p+d*f+u*y+m*v,_=g>=0?1:-1,k=1-g*g;if(k>Number.EPSILON){const N=Math.sqrt(k),M=Math.atan2(N,g*_);b=Math.sin(b*M)/N,l=Math.sin(l*M)/N}const P=l*_;if(c=c*b+p*P,d=d*b+f*P,u=u*b+y*P,m=m*b+v*P,b===1-l){const N=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=N,d*=N,u*=N,m*=N}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,r,i,s,o){const l=r[i],c=r[i+1],d=r[i+2],u=r[i+3],m=s[o],p=s[o+1],f=s[o+2],y=s[o+3];return e[n]=l*y+u*m+c*f-d*p,e[n+1]=c*y+u*p+d*m-l*f,e[n+2]=d*y+u*f+l*p-c*m,e[n+3]=u*y-l*m-c*p-d*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,i){return this._x=e,this._y=n,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n){const r=e._x,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(r/2),u=l(i/2),m=l(s/2),p=c(r/2),f=c(i/2),y=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m-p*f*y;break;case"YXZ":this._x=p*u*m+d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m+p*f*y;break;case"ZXY":this._x=p*u*m-d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m-p*f*y;break;case"ZYX":this._x=p*u*m-d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m+p*f*y;break;case"YZX":this._x=p*u*m+d*f*y,this._y=d*f*m+p*u*y,this._z=d*u*y-p*f*m,this._w=d*u*m-p*f*y;break;case"XZY":this._x=p*u*m-d*f*y,this._y=d*f*m-p*u*y,this._z=d*u*y+p*f*m,this._w=d*u*m+p*f*y;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n!==!1&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],l=n[5],c=n[9],d=n[2],u=n[6],m=n[10],p=r+l+m;if(p>0){const f=.5/Math.sqrt(p+1);this._w=.25/f,this._x=(u-c)*f,this._y=(s-d)*f,this._z=(o-i)*f}else if(r>l&&r>m){const f=2*Math.sqrt(1+r-l-m);this._w=(u-c)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+d)/f}else if(l>m){const f=2*Math.sqrt(1+l-r-m);this._w=(s-d)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(c+u)/f}else{const f=2*Math.sqrt(1+m-r-l);this._w=(o-i)/f,this._x=(s+d)/f,this._y=(c+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return r<Number.EPSILON?(r=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(as(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,i=e._y,s=e._z,o=e._w,l=n._x,c=n._y,d=n._z,u=n._w;return this._x=r*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-r*d,this._z=s*u+o*d+r*c-i*l,this._w=o*u-r*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let l=o*e._w+r*e._x+i*e._y+s*e._z;if(l<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,l=-l):this.copy(e),l>=1)return this._w=o,this._x=r,this._y=i,this._z=s,this;const c=1-l*l;if(c<=Number.EPSILON){const f=1-n;return this._w=f*o+n*this._w,this._x=f*r+n*this._x,this._y=f*i+n*this._y,this._z=f*s+n*this._z,this.normalize(),this._onChangeCallback(),this}const d=Math.sqrt(c),u=Math.atan2(d,l),m=Math.sin((1-n)*u)/d,p=Math.sin(n*u)/d;return this._w=o*m+this._w*p,this._x=r*m+this._x*p,this._y=i*m+this._y*p,this._z=s*m+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=Math.random(),n=Math.sqrt(1-e),r=Math.sqrt(e),i=2*Math.PI*Math.random(),s=2*Math.PI*Math.random();return this.set(n*Math.cos(i),r*Math.sin(s),r*Math.cos(s),n*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class ot{constructor(e=0,n=0,r=0){ot.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(bq.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(bq.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*r),u=2*(l*n-s*i),m=2*(s*r-o*n);return this.x=n+c*d+o*m-l*u,this.y=r+c*u+l*d-s*m,this.z=i+c*m+s*u-o*d,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,i=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=i*c-s*l,this.y=s*o-r*c,this.z=r*l-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return nE.copy(this).projectOnVector(e),this.sub(nE)}reflect(e){return this.sub(nE.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(as(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,n=Math.random()*Math.PI*2,r=Math.sqrt(1-e**2);return this.x=r*Math.cos(n),this.y=r*Math.sin(n),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const nE=new ot,bq=new Gf;class $l{constructor(e=new ot(1/0,1/0,1/0),n=new ot(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n+=3)this.expandByPoint(gc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(gc.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const r=gc.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}setFromObject(e,n=!1){return this.makeEmpty(),this.expandByObject(e,n)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,n=!1){e.updateWorldMatrix(!1,!1);const r=e.geometry;if(r!==void 0){const s=r.getAttribute("position");if(n===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,l=s.count;o<l;o++)e.isMesh===!0?e.getVertexPosition(o,gc):gc.fromBufferAttribute(s,o),gc.applyMatrix4(e.matrixWorld),this.expandByPoint(gc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),t1.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),t1.copy(r.boundingBox)),t1.applyMatrix4(e.matrixWorld),this.union(t1)}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,gc),gc.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(yv),n1.subVectors(this.max,yv),fb.subVectors(e.a,yv),gb.subVectors(e.b,yv),bb.subVectors(e.c,yv),Gm.subVectors(gb,fb),Wm.subVectors(bb,gb),Op.subVectors(fb,bb);let n=[0,-Gm.z,Gm.y,0,-Wm.z,Wm.y,0,-Op.z,Op.y,Gm.z,0,-Gm.x,Wm.z,0,-Wm.x,Op.z,0,-Op.x,-Gm.y,Gm.x,0,-Wm.y,Wm.x,0,-Op.y,Op.x,0];return!rE(n,fb,gb,bb,n1)||(n=[1,0,0,0,1,0,0,0,1],!rE(n,fb,gb,bb,n1))?!1:(r1.crossVectors(Gm,Wm),n=[r1.x,r1.y,r1.z],rE(n,fb,gb,bb,n1))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,gc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(gc).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:(lu[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),lu[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),lu[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),lu[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),lu[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),lu[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),lu[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),lu[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(lu),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 lu=[new ot,new ot,new ot,new ot,new ot,new ot,new ot,new ot],gc=new ot,t1=new $l,fb=new ot,gb=new ot,bb=new ot,Gm=new ot,Wm=new ot,Op=new ot,yv=new ot,n1=new ot,r1=new ot,Ip=new ot;function rE(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){Ip.fromArray(t,s);const l=i.x*Math.abs(Ip.x)+i.y*Math.abs(Ip.y)+i.z*Math.abs(Ip.z),c=e.dot(Ip),d=n.dot(Ip),u=r.dot(Ip);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const fNe=new $l,vv=new ot,aE=new ot;class vd{constructor(e=new ot,n=-1){this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):fNe.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const n=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=n*n}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,n){const r=this.center.distanceToSquared(e);return n.copy(e),r>this.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;vv.subVectors(e,this.center);const n=vv.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(vv,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(aE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(vv.copy(e.center).add(aE)),this.expandByPoint(vv.copy(e.center).sub(aE))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const cu=new ot,iE=new ot,a1=new ot,Km=new ot,sE=new ot,i1=new ot,oE=new ot;class HO{constructor(e=new ot,n=new ot(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,cu)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=cu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(cu.copy(this.origin).addScaledVector(this.direction,n),cu.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){iE.copy(e).add(n).multiplyScalar(.5),a1.copy(n).sub(e).normalize(),Km.copy(this.origin).sub(iE);const s=e.distanceTo(n)*.5,o=-this.direction.dot(a1),l=Km.dot(this.direction),c=-Km.dot(a1),d=Km.lengthSq(),u=Math.abs(1-o*o);let m,p,f,y;if(u>0)if(m=o*c-l,p=o*l-c,y=s*u,m>=0)if(p>=-y)if(p<=y){const v=1/u;m*=v,p*=v,f=m*(m+o*p+2*l)+p*(o*m+p+2*c)+d}else p=s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p=-s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p<=-y?(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<=y?(m=0,p=Math.min(Math.max(-s,-c),s),f=p*(p+2*c)+d):(m=Math.max(0,-(o*s+l)),p=m>0?s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d);else p=o>0?-s:s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;return r&&r.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(iE).addScaledVector(a1,p),f}intersectSphere(e,n){cu.subVectors(e.center,this.origin);const r=cu.dot(this.direction),i=cu.dot(cu)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),l=r-o,c=r+o;return c<0?null:l<0?this.at(c,n):this.at(l,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,i,s,o,l,c;const d=1/this.direction.x,u=1/this.direction.y,m=1/this.direction.z,p=this.origin;return d>=0?(r=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(r=(e.max.x-p.x)*d,i=(e.min.x-p.x)*d),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o<i||isNaN(i))&&(i=o),m>=0?(l=(e.min.z-p.z)*m,c=(e.max.z-p.z)*m):(l=(e.max.z-p.z)*m,c=(e.min.z-p.z)*m),r>c||l>i)||((l>r||r!==r)&&(r=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(r>=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,cu)!==null}intersectTriangle(e,n,r,i,s){sE.subVectors(n,e),i1.subVectors(r,e),oE.crossVectors(sE,i1);let o=this.direction.dot(oE),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Km.subVectors(this.origin,e);const c=l*this.direction.dot(i1.crossVectors(Km,i1));if(c<0)return null;const d=l*this.direction.dot(sE.cross(Km));if(d<0||c+d>o)return null;const u=-l*Km.dot(oE);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 oa{constructor(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b){oa.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b)}set(e,n,r,i,s,o,l,c,d,u,m,p,f,y,v,b){const g=this.elements;return g[0]=e,g[4]=n,g[8]=r,g[12]=i,g[1]=s,g[5]=o,g[9]=l,g[13]=c,g[2]=d,g[6]=u,g[10]=m,g[14]=p,g[3]=f,g[7]=y,g[11]=v,g[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 oa().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,i=1/xb.setFromMatrixColumn(e,0).length(),s=1/xb.setFromMatrixColumn(e,1).length(),o=1/xb.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(i),d=Math.sin(i),u=Math.cos(s),m=Math.sin(s);if(e.order==="XYZ"){const p=o*u,f=o*m,y=l*u,v=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+y*d,n[5]=p-v*d,n[9]=-l*c,n[2]=v-p*d,n[6]=y+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,y=d*u,v=d*m;n[0]=p+v*l,n[4]=y*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-y,n[6]=v+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,y=d*u,v=d*m;n[0]=p-v*l,n[4]=-o*m,n[8]=y+f*l,n[1]=f+y*l,n[5]=o*u,n[9]=v-p*l,n[2]=-o*d,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const p=o*u,f=o*m,y=l*u,v=l*m;n[0]=c*u,n[4]=y*d-f,n[8]=p*d+v,n[1]=c*m,n[5]=v*d+p,n[9]=f*d-y,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,y=l*c,v=l*d;n[0]=c*u,n[4]=v-p*m,n[8]=y*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+y,n[10]=p-v*m}else if(e.order==="XZY"){const p=o*c,f=o*d,y=l*c,v=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+v,n[5]=o*u,n[9]=f*m-y,n[2]=y*m-f,n[6]=l*u,n[10]=v*m+p}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(gNe,e,bNe)}lookAt(e,n,r){const i=this.elements;return Ko.subVectors(e,n),Ko.lengthSq()===0&&(Ko.z=1),Ko.normalize(),Ym.crossVectors(r,Ko),Ym.lengthSq()===0&&(Math.abs(r.z)===1?Ko.x+=1e-4:Ko.z+=1e-4,Ko.normalize(),Ym.crossVectors(r,Ko)),Ym.normalize(),s1.crossVectors(Ko,Ym),i[0]=Ym.x,i[4]=s1.x,i[8]=Ko.x,i[1]=Ym.y,i[5]=s1.y,i[9]=Ko.y,i[2]=Ym.z,i[6]=s1.z,i[10]=Ko.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],d=r[12],u=r[1],m=r[5],p=r[9],f=r[13],y=r[2],v=r[6],b=r[10],g=r[14],_=r[3],k=r[7],P=r[11],N=r[15],M=i[0],A=i[4],T=i[8],C=i[12],F=i[1],$=i[5],I=i[9],X=i[13],L=i[2],te=i[6],ae=i[10],ee=i[14],me=i[3],le=i[7],ue=i[11],K=i[15];return s[0]=o*M+l*F+c*L+d*me,s[4]=o*A+l*$+c*te+d*le,s[8]=o*T+l*I+c*ae+d*ue,s[12]=o*C+l*X+c*ee+d*K,s[1]=u*M+m*F+p*L+f*me,s[5]=u*A+m*$+p*te+f*le,s[9]=u*T+m*I+p*ae+f*ue,s[13]=u*C+m*X+p*ee+f*K,s[2]=y*M+v*F+b*L+g*me,s[6]=y*A+v*$+b*te+g*le,s[10]=y*T+v*I+b*ae+g*ue,s[14]=y*C+v*X+b*ee+g*K,s[3]=_*M+k*F+P*L+N*me,s[7]=_*A+k*$+P*te+N*le,s[11]=_*T+k*I+P*ae+N*ue,s[15]=_*C+k*X+P*ee+N*K,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],i=e[8],s=e[12],o=e[1],l=e[5],c=e[9],d=e[13],u=e[2],m=e[6],p=e[10],f=e[14],y=e[3],v=e[7],b=e[11],g=e[15];return y*(+s*c*m-i*d*m-s*l*p+r*d*p+i*l*f-r*c*f)+v*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+b*(+n*d*m-n*l*f-s*o*m+r*o*f+s*l*u-r*d*u)+g*(-i*l*u-n*c*m+n*l*p+i*o*m-r*o*p+r*c*u)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=e[9],p=e[10],f=e[11],y=e[12],v=e[13],b=e[14],g=e[15],_=m*b*d-v*p*d+v*c*f-l*b*f-m*c*g+l*p*g,k=y*p*d-u*b*d-y*c*f+o*b*f+u*c*g-o*p*g,P=u*v*d-y*m*d+y*l*f-o*v*f-u*l*g+o*m*g,N=y*m*c-u*v*c-y*l*p+o*v*p+u*l*b-o*m*b,M=n*_+r*k+i*P+s*N;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/M;return e[0]=_*A,e[1]=(v*p*s-m*b*s-v*i*f+r*b*f+m*i*g-r*p*g)*A,e[2]=(l*b*s-v*c*s+v*i*d-r*b*d-l*i*g+r*c*g)*A,e[3]=(m*c*s-l*p*s-m*i*d+r*p*d+l*i*f-r*c*f)*A,e[4]=k*A,e[5]=(u*b*s-y*p*s+y*i*f-n*b*f-u*i*g+n*p*g)*A,e[6]=(y*c*s-o*b*s-y*i*d+n*b*d+o*i*g-n*c*g)*A,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*A,e[8]=P*A,e[9]=(y*m*s-u*v*s-y*r*f+n*v*f+u*r*g-n*m*g)*A,e[10]=(o*v*s-y*l*s+y*r*d-n*v*d-o*r*g+n*l*g)*A,e[11]=(u*l*s-o*m*s-u*r*d+n*m*d+o*r*f-n*l*f)*A,e[12]=N*A,e[13]=(u*v*i-y*m*i+y*r*p-n*v*p-u*r*b+n*m*b)*A,e[14]=(y*l*i-o*v*i-y*r*c+n*v*c+o*r*b-n*l*b)*A,e[15]=(o*m*i-u*l*i+u*r*c-n*m*c-o*r*p+n*l*p)*A,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),i=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+r,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+r,u*c-i*o,0,d*c-i*l,u*c+i*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,d=s+s,u=o+o,m=l+l,p=s*d,f=s*u,y=s*m,v=o*u,b=o*m,g=l*m,_=c*d,k=c*u,P=c*m,N=r.x,M=r.y,A=r.z;return i[0]=(1-(v+g))*N,i[1]=(f+P)*N,i[2]=(y-k)*N,i[3]=0,i[4]=(f-P)*M,i[5]=(1-(p+g))*M,i[6]=(b+_)*M,i[7]=0,i[8]=(y+k)*A,i[9]=(b-_)*A,i[10]=(1-(p+v))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=xb.set(i[0],i[1],i[2]).length();const o=xb.set(i[4],i[5],i[6]).length(),l=xb.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],bc.copy(this);const d=1/s,u=1/o,m=1/l;return bc.elements[0]*=d,bc.elements[1]*=d,bc.elements[2]*=d,bc.elements[4]*=u,bc.elements[5]*=u,bc.elements[6]*=u,bc.elements[8]*=m,bc.elements[9]*=m,bc.elements[10]*=m,n.setFromRotationMatrix(bc),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,i,s,o,l=fd){const c=this.elements,d=2*s/(n-e),u=2*s/(r-i),m=(n+e)/(n-e),p=(r+i)/(r-i);let f,y;if(l===fd)f=-(o+s)/(o-s),y=-2*o*s/(o-s);else if(l===V0)f=-o/(o-s),y=-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]=y,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,n,r,i,s,o,l=fd){const c=this.elements,d=1/(n-e),u=1/(r-i),m=1/(o-s),p=(n+e)*d,f=(r+i)*u;let y,v;if(l===fd)y=(o+s)*m,v=-2*m;else if(l===V0)y=s*m,v=-1*m;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return c[0]=2*d,c[4]=0,c[8]=0,c[12]=-p,c[1]=0,c[5]=2*u,c[9]=0,c[13]=-f,c[2]=0,c[6]=0,c[10]=v,c[14]=-y,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<16;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}}const xb=new ot,bc=new oa,gNe=new ot(0,0,0),bNe=new ot(1,1,1),Ym=new ot,s1=new ot,Ko=new ot,xq=new oa,yq=new Gf;class zw{constructor(e=0,n=0,r=0,i=zw.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],l=i[8],c=i[1],d=i[5],u=i[9],m=i[2],p=i[6],f=i[10];switch(n){case"XYZ":this._y=Math.asin(as(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(-as(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(as(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(-as(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(as(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(-as(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,d),this._y=Math.atan2(l,s)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return xq.makeRotationFromQuaternion(e),this.setFromRotationMatrix(xq,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return yq.setFromEuler(this),this.setFromQuaternion(yq,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}}zw.DEFAULT_ORDER="XYZ";class zZ{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 xNe=0;const vq=new ot,yb=new Gf,du=new oa,o1=new ot,wv=new ot,yNe=new ot,vNe=new Gf,wq=new ot(1,0,0),Sq=new ot(0,1,0),_q=new ot(0,0,1),wNe={type:"added"},SNe={type:"removed"};class Js extends ug{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:xNe++}),this.uuid=zu(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Js.DEFAULT_UP.clone();const e=new ot,n=new zw,r=new Gf,i=new ot(1,1,1);function s(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(s),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new oa},normalMatrix:{value:new lr}}),this.matrix=new oa,this.matrixWorld=new oa,this.matrixAutoUpdate=Js.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Js.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new zZ,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 yb.setFromAxisAngle(e,n),this.quaternion.multiply(yb),this}rotateOnWorldAxis(e,n){return yb.setFromAxisAngle(e,n),this.quaternion.premultiply(yb),this}rotateX(e){return this.rotateOnAxis(wq,e)}rotateY(e){return this.rotateOnAxis(Sq,e)}rotateZ(e){return this.rotateOnAxis(_q,e)}translateOnAxis(e,n){return vq.copy(e).applyQuaternion(this.quaternion),this.position.add(vq.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(wq,e)}translateY(e){return this.translateOnAxis(Sq,e)}translateZ(e){return this.translateOnAxis(_q,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(du.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?o1.copy(e):o1.set(e,n,r);const i=this.parent;this.updateWorldMatrix(!0,!1),wv.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?du.lookAt(wv,o1,this.up):du.lookAt(o1,wv,this.up),this.quaternion.setFromRotationMatrix(du),i&&(du.extractRotation(i.matrixWorld),yb.setFromRotationMatrix(du),this.quaternion.premultiply(yb.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(wNe)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.remove(arguments[r]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(SNe)),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),du.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),du.multiply(e.parent.matrixWorld)),e.applyMatrix4(du),this.add(e),e.updateWorldMatrix(!1,!0),this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,n){if(this[e]===n)return this;for(let r=0,i=this.children.length;r<i;r++){const o=this.children[r].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,r=[]){this[e]===n&&r.push(this);const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,n,r);return r}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(wv,e,yNe),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(wv,vNe,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const n=this.matrixWorld.elements;return e.set(n[8],n[9],n[10]).normalize()}raycast(){}traverse(e){e(this);const n=this.children;for(let r=0,i=n.length;r<i;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,i=n.length;r<i;r++)n[r].traverseVisible(e)}traverseAncestors(e){const n=this.parent;n!==null&&(e(n),n.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const n=this.children;for(let r=0,i=n.length;r<i;r++){const s=n[r];(s.matrixWorldAutoUpdate===!0||e===!0)&&s.updateMatrixWorld(e)}}updateWorldMatrix(e,n){const r=this.parent;if(e===!0&&r!==null&&r.matrixWorldAutoUpdate===!0&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),n===!0){const i=this.children;for(let s=0,o=i.length;s<o;s++){const l=i[s];l.matrixWorldAutoUpdate===!0&&l.updateWorldMatrix(!1,!0)}}}toJSON(e){const n=e===void 0||typeof e=="string",r={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},r.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(l=>({boxInitialized:l.boxInitialized,boxMin:l.box.min.toArray(),boxMax:l.box.max.toArray(),sphereInitialized:l.sphereInitialized,sphereRadius:l.sphere.radius,sphereCenter:l.sphere.center.toArray()})),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(l,c){return l[c.uuid]===void 0&&(l[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const l=this.geometry.parameters;if(l!==void 0&&l.shapes!==void 0){const c=l.shapes;if(Array.isArray(c))for(let d=0,u=c.length;d<u;d++){const m=c[d];s(e.shapes,m)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,d=this.material.length;c<d;c++)l.push(s(e.materials,this.material[c]));i.material=l}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let l=0;l<this.children.length;l++)i.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];i.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),d=o(e.textures),u=o(e.images),m=o(e.shapes),p=o(e.skeletons),f=o(e.animations),y=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),d.length>0&&(r.textures=d),u.length>0&&(r.images=u),m.length>0&&(r.shapes=m),p.length>0&&(r.skeletons=p),f.length>0&&(r.animations=f),y.length>0&&(r.nodes=y)}return r.object=i,r;function o(l){const c=[];for(const d in l){const u=l[d];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r<e.children.length;r++){const i=e.children[r];this.add(i.clone())}return this}}Js.DEFAULT_UP=new ot(0,1,0);Js.DEFAULT_MATRIX_AUTO_UPDATE=!0;Js.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const xc=new ot,uu=new ot,lE=new ot,mu=new ot,vb=new ot,wb=new ot,kq=new ot,cE=new ot,dE=new ot,uE=new ot;let l1=!1;class vc{constructor(e=new ot,n=new ot,r=new ot){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,i){i.subVectors(r,n),xc.subVectors(e,n),i.cross(xc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){xc.subVectors(i,n),uu.subVectors(r,n),lE.subVectors(e,n);const o=xc.dot(xc),l=xc.dot(uu),c=xc.dot(lE),d=uu.dot(uu),u=uu.dot(lE),m=o*d-l*l;if(m===0)return s.set(-2,-1,-1);const p=1/m,f=(d*c-l*u)*p,y=(o*u-l*c)*p;return s.set(1-f-y,y,f)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,mu),mu.x>=0&&mu.y>=0&&mu.x+mu.y<=1}static getUV(e,n,r,i,s,o,l,c){return l1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),l1=!0),this.getInterpolation(e,n,r,i,s,o,l,c)}static getInterpolation(e,n,r,i,s,o,l,c){return this.getBarycoord(e,n,r,i,mu),c.setScalar(0),c.addScaledVector(s,mu.x),c.addScaledVector(o,mu.y),c.addScaledVector(l,mu.z),c}static isFrontFacing(e,n,r,i){return xc.subVectors(r,n),uu.subVectors(e,n),xc.cross(uu).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return xc.subVectors(this.c,this.b),uu.subVectors(this.a,this.b),xc.cross(uu).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return vc.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return vc.getBarycoord(e,this.a,this.b,this.c,n)}getUV(e,n,r,i,s){return l1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),l1=!0),vc.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}getInterpolation(e,n,r,i,s){return vc.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return vc.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return vc.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,l;vb.subVectors(i,r),wb.subVectors(s,r),cE.subVectors(e,r);const c=vb.dot(cE),d=wb.dot(cE);if(c<=0&&d<=0)return n.copy(r);dE.subVectors(e,i);const u=vb.dot(dE),m=wb.dot(dE);if(u>=0&&m<=u)return n.copy(i);const p=c*m-u*d;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),n.copy(r).addScaledVector(vb,o);uE.subVectors(e,s);const f=vb.dot(uE),y=wb.dot(uE);if(y>=0&&f<=y)return n.copy(s);const v=f*d-c*y;if(v<=0&&d>=0&&y<=0)return l=d/(d-y),n.copy(r).addScaledVector(wb,l);const b=u*y-f*m;if(b<=0&&m-u>=0&&f-y>=0)return kq.subVectors(s,i),l=(m-u)/(m-u+(f-y)),n.copy(i).addScaledVector(kq,l);const g=1/(b+v+p);return o=v*g,l=p*g,n.copy(r).addScaledVector(vb,o).addScaledVector(wb,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const UZ={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},Xm={h:0,s:0,l:0},c1={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 An=class{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=rs){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,$r.toWorkingColorSpace(this,n),this}setRGB(e,n,r,i=$r.workingColorSpace){return this.r=e,this.g=n,this.b=r,$r.toWorkingColorSpace(this,i),this}setHSL(e,n,r,i=$r.workingColorSpace){if(e=BO(e,1),n=as(n,0,1),r=as(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=mE(o,s,e+1/3),this.g=mE(o,s,e),this.b=mE(o,s,e-1/3)}return $r.toWorkingColorSpace(this,i),this}setStyle(e,n=rs){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],l=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,n);if(o===6)return this.setHex(parseInt(s,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=rs){const r=UZ[e.toLowerCase()];return r!==void 0?this.setHex(r,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=ox(e.r),this.g=ox(e.g),this.b=ox(e.b),this}copyLinearToSRGB(e){return this.r=eE(e.r),this.g=eE(e.g),this.b=eE(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=rs){return $r.fromWorkingColorSpace(ks.copy(this),e),Math.round(as(ks.r*255,0,255))*65536+Math.round(as(ks.g*255,0,255))*256+Math.round(as(ks.b*255,0,255))}getHexString(e=rs){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=$r.workingColorSpace){$r.fromWorkingColorSpace(ks.copy(this),n);const r=ks.r,i=ks.g,s=ks.b,o=Math.max(r,i,s),l=Math.min(r,i,s);let c,d;const u=(l+o)/2;if(l===o)c=0,d=0;else{const m=o-l;switch(d=u<=.5?m/(o+l):m/(2-o-l),o){case r:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-r)/m+2;break;case s:c=(r-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=$r.workingColorSpace){return $r.fromWorkingColorSpace(ks.copy(this),n),e.r=ks.r,e.g=ks.g,e.b=ks.b,e}getStyle(e=rs){$r.fromWorkingColorSpace(ks.copy(this),e);const n=ks.r,r=ks.g,i=ks.b;return e!==rs?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(i*255)})`}offsetHSL(e,n,r){return this.getHSL(Xm),this.setHSL(Xm.h+e,Xm.s+n,Xm.l+r)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,n){return this.r=e.r+n.r,this.g=e.g+n.g,this.b=e.b+n.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,n){return this.r+=(e.r-this.r)*n,this.g+=(e.g-this.g)*n,this.b+=(e.b-this.b)*n,this}lerpColors(e,n,r){return this.r=e.r+(n.r-e.r)*r,this.g=e.g+(n.g-e.g)*r,this.b=e.b+(n.b-e.b)*r,this}lerpHSL(e,n){this.getHSL(Xm),e.getHSL(c1);const r=l0(Xm.h,c1.h,n),i=l0(Xm.s,c1.s,n),s=l0(Xm.l,c1.l,n);return this.setHSL(r,i,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const n=this.r,r=this.g,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*i,this.g=s[1]*n+s[4]*r+s[7]*i,this.b=s[2]*n+s[5]*r+s[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,n=0){return this.r=e[n],this.g=e[n+1],this.b=e[n+2],this}toArray(e=[],n=0){return e[n]=this.r,e[n+1]=this.g,e[n+2]=this.b,e}fromBufferAttribute(e,n){return this.r=e.getX(n),this.g=e.getY(n),this.b=e.getZ(n),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const ks=new An;An.NAMES=UZ;let _Ne=0;class sy extends ug{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:_Ne++}),this.uuid=zu(),this.name="",this.type="Material",this.blending=sx,this.side=Gh,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=zF,this.blendDst=UF,this.blendEquation=ef,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new An(0,0,0),this.blendAlpha=0,this.depthFunc=hN,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=uq,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=hb,this.stencilZFail=hb,this.stencilZPass=hb,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==sx&&(r.blending=this.blending),this.side!==Gh&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==zF&&(r.blendSrc=this.blendSrc),this.blendDst!==UF&&(r.blendDst=this.blendDst),this.blendEquation!==ef&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==hN&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==uq&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==hb&&(r.stencilFail=this.stencilFail),this.stencilZFail!==hb&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==hb&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const i=n.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class BZ extends sy{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new An(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=IO,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 ai=new ot,d1=new Hn;class al{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=VF,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=ju,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.BufferAttribute: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[r+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,r=this.count;n<r;n++)d1.fromBufferAttribute(this,n),d1.applyMatrix3(e),this.setXY(n,d1.x,d1.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)ai.fromBufferAttribute(this,n),ai.applyMatrix3(e),this.setXYZ(n,ai.x,ai.y,ai.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)ai.fromBufferAttribute(this,n),ai.applyMatrix4(e),this.setXYZ(n,ai.x,ai.y,ai.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)ai.fromBufferAttribute(this,n),ai.applyNormalMatrix(e),this.setXYZ(n,ai.x,ai.y,ai.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)ai.fromBufferAttribute(this,n),ai.transformDirection(e),this.setXYZ(n,ai.x,ai.y,ai.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let r=this.array[e*this.itemSize+n];return this.normalized&&(r=md(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=qr(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=md(n,this.array)),n}setX(e,n){return this.normalized&&(n=qr(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=md(n,this.array)),n}setY(e,n){return this.normalized&&(n=qr(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=md(n,this.array)),n}setZ(e,n){return this.normalized&&(n=qr(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=md(n,this.array)),n}setW(e,n){return this.normalized&&(n=qr(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,i){return e*=this.itemSize,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array),i=qr(i,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e*=this.itemSize,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array),i=qr(i,this.array),s=qr(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==VF&&(e.usage=this.usage),e}}class HZ extends al{constructor(e,n,r){super(new Uint16Array(e),n,r)}}class qZ extends al{constructor(e,n,r){super(new Uint32Array(e),n,r)}}class Qa extends al{constructor(e,n,r){super(new Float32Array(e),n,r)}}let kNe=0;const _l=new oa,hE=new Js,Sb=new ot,Yo=new $l,Sv=new $l,Mi=new ot;class Rs extends ug{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:kNe++}),this.uuid=zu(),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(RZ(e)?qZ:HZ)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,n){return this.attributes[e]=n,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,n,r=0){this.groups.push({start:e,count:n,materialIndex:r})}clearGroups(){this.groups=[]}setDrawRange(e,n){this.drawRange.start=e,this.drawRange.count=n}applyMatrix4(e){const n=this.attributes.position;n!==void 0&&(n.applyMatrix4(e),n.needsUpdate=!0);const r=this.attributes.normal;if(r!==void 0){const s=new lr().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return _l.makeRotationFromQuaternion(e),this.applyMatrix4(_l),this}rotateX(e){return _l.makeRotationX(e),this.applyMatrix4(_l),this}rotateY(e){return _l.makeRotationY(e),this.applyMatrix4(_l),this}rotateZ(e){return _l.makeRotationZ(e),this.applyMatrix4(_l),this}translate(e,n,r){return _l.makeTranslation(e,n,r),this.applyMatrix4(_l),this}scale(e,n,r){return _l.makeScale(e,n,r),this.applyMatrix4(_l),this}lookAt(e){return hE.lookAt(e),hE.updateMatrix(),this.applyMatrix4(hE.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Sb).negate(),this.translate(Sb.x,Sb.y,Sb.z),this}setFromPoints(e){const n=[];for(let r=0,i=e.length;r<i;r++){const s=e[r];n.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new Qa(n,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new $l);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 ot(-1/0,-1/0,-1/0),new ot(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r<i;r++){const s=n[r];Yo.setFromBufferAttribute(s),this.morphTargetsRelative?(Mi.addVectors(this.boundingBox.min,Yo.min),this.boundingBox.expandByPoint(Mi),Mi.addVectors(this.boundingBox.max,Yo.max),this.boundingBox.expandByPoint(Mi)):(this.boundingBox.expandByPoint(Yo.min),this.boundingBox.expandByPoint(Yo.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new vd);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 ot,1/0);return}if(e){const r=this.boundingSphere.center;if(Yo.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];Sv.setFromBufferAttribute(l),this.morphTargetsRelative?(Mi.addVectors(Yo.min,Sv.min),Yo.expandByPoint(Mi),Mi.addVectors(Yo.max,Sv.max),Yo.expandByPoint(Mi)):(Yo.expandByPoint(Sv.min),Yo.expandByPoint(Sv.max))}Yo.getCenter(r);let i=0;for(let s=0,o=e.count;s<o;s++)Mi.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(Mi));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++)Mi.fromBufferAttribute(l,d),c&&(Sb.fromBufferAttribute(e,d),Mi.add(Sb)),i=Math.max(i,r.distanceToSquared(Mi))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,n=this.attributes;if(e===null||n.position===void 0||n.normal===void 0||n.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const r=e.array,i=n.position.array,s=n.normal.array,o=n.uv.array,l=i.length/3;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new al(new Float32Array(4*l),4));const c=this.getAttribute("tangent").array,d=[],u=[];for(let F=0;F<l;F++)d[F]=new ot,u[F]=new ot;const m=new ot,p=new ot,f=new ot,y=new Hn,v=new Hn,b=new Hn,g=new ot,_=new ot;function k(F,$,I){m.fromArray(i,F*3),p.fromArray(i,$*3),f.fromArray(i,I*3),y.fromArray(o,F*2),v.fromArray(o,$*2),b.fromArray(o,I*2),p.sub(m),f.sub(m),v.sub(y),b.sub(y);const X=1/(v.x*b.y-b.x*v.y);isFinite(X)&&(g.copy(p).multiplyScalar(b.y).addScaledVector(f,-v.y).multiplyScalar(X),_.copy(f).multiplyScalar(v.x).addScaledVector(p,-b.x).multiplyScalar(X),d[F].add(g),d[$].add(g),d[I].add(g),u[F].add(_),u[$].add(_),u[I].add(_))}let P=this.groups;P.length===0&&(P=[{start:0,count:r.length}]);for(let F=0,$=P.length;F<$;++F){const I=P[F],X=I.start,L=I.count;for(let te=X,ae=X+L;te<ae;te+=3)k(r[te+0],r[te+1],r[te+2])}const N=new ot,M=new ot,A=new ot,T=new ot;function C(F){A.fromArray(s,F*3),T.copy(A);const $=d[F];N.copy($),N.sub(A.multiplyScalar(A.dot($))).normalize(),M.crossVectors(T,$);const X=M.dot(u[F])<0?-1:1;c[F*4]=N.x,c[F*4+1]=N.y,c[F*4+2]=N.z,c[F*4+3]=X}for(let F=0,$=P.length;F<$;++F){const I=P[F],X=I.start,L=I.count;for(let te=X,ae=X+L;te<ae;te+=3)C(r[te+0]),C(r[te+1]),C(r[te+2])}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let r=this.getAttribute("normal");if(r===void 0)r=new al(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let p=0,f=r.count;p<f;p++)r.setXYZ(p,0,0,0);const i=new ot,s=new ot,o=new ot,l=new ot,c=new ot,d=new ot,u=new ot,m=new ot;if(e)for(let p=0,f=e.count;p<f;p+=3){const y=e.getX(p+0),v=e.getX(p+1),b=e.getX(p+2);i.fromBufferAttribute(n,y),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,b),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(r,y),c.fromBufferAttribute(r,v),d.fromBufferAttribute(r,b),l.add(u),c.add(u),d.add(u),r.setXYZ(y,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.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),r.setXYZ(p+0,u.x,u.y,u.z),r.setXYZ(p+1,u.x,u.y,u.z),r.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Mi.fromBufferAttribute(e,n),Mi.normalize(),e.setXYZ(n,Mi.x,Mi.y,Mi.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,y=0;for(let v=0,b=c.length;v<b;v++){l.isInterleavedBufferAttribute?f=c[v]*l.data.stride+l.offset:f=c[v]*u;for(let g=0;g<u;g++)p[y++]=d[f++]}return new al(p,u,m)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new Rs,r=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,r);n.setAttribute(l,d)}const s=this.morphAttributes;for(const l in s){const c=[],d=s[l];for(let u=0,m=d.length;u<m;u++){const p=d[u],f=e(p,r);c.push(f)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const d=o[l];n.addGroup(d.start,d.count,d.materialIndex)}return n}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const d in c)c[d]!==void 0&&(e[d]=c[d]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const c in r){const d=r[c];e.data.attributes[c]=d.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const d=this.morphAttributes[c],u=[];for(let m=0,p=d.length;m<p;m++){const f=d[m];u.push(f.toJSON(e.data))}u.length>0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const l=this.boundingSphere;return l!==null&&(e.data.boundingSphere={center:l.center.toArray(),radius:l.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(n));const i=e.attributes;for(const d in i){const u=i[d];this.setAttribute(d,u.clone(n))}const s=e.morphAttributes;for(const d in s){const u=[],m=s[d];for(let p=0,f=m.length;p<f;p++)u.push(m[p].clone(n));this.morphAttributes[d]=u}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let d=0,u=o.length;d<u;d++){const m=o[d];this.addGroup(m.start,m.count,m.materialIndex)}const l=e.boundingBox;l!==null&&(this.boundingBox=l.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Nq=new oa,zp=new HO,u1=new vd,Cq=new ot,_b=new ot,kb=new ot,Nb=new ot,pE=new ot,m1=new ot,h1=new Hn,p1=new Hn,f1=new Hn,Pq=new ot,Tq=new ot,Aq=new ot,g1=new ot,b1=new ot;class Ac extends Js{constructor(e=new Rs,n=new BZ){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,i=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){m1.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(pE.fromBufferAttribute(m,e),o?m1.addScaledVector(pE,u):m1.addScaledVector(pE.sub(n),u))}n.add(m1)}return n}raycast(e,n){const r=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),u1.copy(r.boundingSphere),u1.applyMatrix4(s),zp.copy(e.ray).recast(e.near),!(u1.containsPoint(zp.origin)===!1&&(zp.intersectSphere(u1,Cq)===null||zp.origin.distanceToSquared(Cq)>(e.far-e.near)**2))&&(Nq.copy(s).invert(),zp.copy(e.ray).applyMatrix4(Nq),!(r.boundingBox!==null&&zp.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,zp)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,d=s.attributes.uv,u=s.attributes.uv1,m=s.attributes.normal,p=s.groups,f=s.drawRange;if(l!==null)if(Array.isArray(o))for(let y=0,v=p.length;y<v;y++){const b=p[y],g=o[b.materialIndex],_=Math.max(b.start,f.start),k=Math.min(l.count,Math.min(b.start+b.count,f.start+f.count));for(let P=_,N=k;P<N;P+=3){const M=l.getX(P),A=l.getX(P+1),T=l.getX(P+2);i=x1(this,g,e,r,d,u,m,M,A,T),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const y=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let b=y,g=v;b<g;b+=3){const _=l.getX(b),k=l.getX(b+1),P=l.getX(b+2);i=x1(this,o,e,r,d,u,m,_,k,P),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let y=0,v=p.length;y<v;y++){const b=p[y],g=o[b.materialIndex],_=Math.max(b.start,f.start),k=Math.min(c.count,Math.min(b.start+b.count,f.start+f.count));for(let P=_,N=k;P<N;P+=3){const M=P,A=P+1,T=P+2;i=x1(this,g,e,r,d,u,m,M,A,T),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const y=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let b=y,g=v;b<g;b+=3){const _=b,k=b+1,P=b+2;i=x1(this,o,e,r,d,u,m,_,k,P),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}}}function NNe(t,e,n,r,i,s,o,l){let c;if(e.side===Po?c=r.intersectTriangle(o,s,i,!0,l):c=r.intersectTriangle(i,s,o,e.side===Gh,l),c===null)return null;b1.copy(l),b1.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(b1);return d<n.near||d>n.far?null:{distance:d,point:b1.clone(),object:t}}function x1(t,e,n,r,i,s,o,l,c,d){t.getVertexPosition(l,_b),t.getVertexPosition(c,kb),t.getVertexPosition(d,Nb);const u=NNe(t,e,n,r,_b,kb,Nb,g1);if(u){i&&(h1.fromBufferAttribute(i,l),p1.fromBufferAttribute(i,c),f1.fromBufferAttribute(i,d),u.uv=vc.getInterpolation(g1,_b,kb,Nb,h1,p1,f1,new Hn)),s&&(h1.fromBufferAttribute(s,l),p1.fromBufferAttribute(s,c),f1.fromBufferAttribute(s,d),u.uv1=vc.getInterpolation(g1,_b,kb,Nb,h1,p1,f1,new Hn),u.uv2=u.uv1),o&&(Pq.fromBufferAttribute(o,l),Tq.fromBufferAttribute(o,c),Aq.fromBufferAttribute(o,d),u.normal=vc.getInterpolation(g1,_b,kb,Nb,Pq,Tq,Aq,new ot),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const m={a:l,b:c,c:d,normal:new ot,materialIndex:0};vc.getNormal(_b,kb,Nb,m.normal),u.face=m}return u}class Uw extends Rs{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const l=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],d=[],u=[],m=[];let p=0,f=0;y("z","y","x",-1,-1,r,n,e,o,s,0),y("z","y","x",1,-1,r,n,-e,o,s,1),y("x","z","y",1,1,e,r,n,i,o,2),y("x","z","y",1,-1,e,r,-n,i,o,3),y("x","y","z",1,-1,e,n,r,i,s,4),y("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new Qa(d,3)),this.setAttribute("normal",new Qa(u,3)),this.setAttribute("uv",new Qa(m,2));function y(v,b,g,_,k,P,N,M,A,T,C){const F=P/A,$=N/T,I=P/2,X=N/2,L=M/2,te=A+1,ae=T+1;let ee=0,me=0;const le=new ot;for(let ue=0;ue<ae;ue++){const K=ue*$-X;for(let ne=0;ne<te;ne++){const oe=ne*F-I;le[v]=oe*_,le[b]=K*k,le[g]=L,d.push(le.x,le.y,le.z),le[v]=0,le[b]=0,le[g]=M>0?1:-1,u.push(le.x,le.y,le.z),m.push(ne/A),m.push(1-ue/T),ee+=1}}for(let ue=0;ue<T;ue++)for(let K=0;K<A;K++){const ne=p+K+te*ue,oe=p+K+te*(ue+1),be=p+(K+1)+te*(ue+1),_e=p+(K+1)+te*ue;c.push(ne,oe,_e),c.push(oe,be,_e),me+=6}l.addGroup(f,me,C),f+=me,p+=ee}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Uw(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function jx(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const i=t[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=i.clone():Array.isArray(i)?e[n][r]=i.slice():e[n][r]=i}}return e}function Gs(t){const e={};for(let n=0;n<t.length;n++){const r=jx(t[n]);for(const i in r)e[i]=r[i]}return e}function CNe(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function $Z(t){return t.getRenderTarget()===null?t.outputColorSpace:$r.workingColorSpace}const qO={clone:jx,merge:Gs};var PNe=`void main() {
  3861. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  3862. }`,TNe=`void main() {
  3863. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  3864. }`;class Wh extends sy{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=PNe,this.fragmentShader=TNe,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=jx(e.uniforms),this.uniformsGroups=CNe(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const n=super.toJSON(e);n.glslVersion=this.glslVersion,n.uniforms={};for(const i in this.uniforms){const o=this.uniforms[i].value;o&&o.isTexture?n.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[i]={type:"m4",value:o.toArray()}:n.uniforms[i]={value:o}}Object.keys(this.defines).length>0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}}class VZ extends Js{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new oa,this.projectionMatrix=new oa,this.projectionMatrixInverse=new oa,this.coordinateSystem=fd}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 Zo extends VZ{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=G0*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(o0*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return G0*2*Math.atan(Math.tan(o0*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,n,r,i,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(o0*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,d=o.fullHeight;s+=o.offsetX*i/c,n-=o.offsetY*r/d,i*=o.width/c,r*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const Cb=-90,Pb=1;class ANe extends Js{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Zo(Cb,Pb,e,n);i.layers=this.layers,this.add(i);const s=new Zo(Cb,Pb,e,n);s.layers=this.layers,this.add(s);const o=new Zo(Cb,Pb,e,n);o.layers=this.layers,this.add(o);const l=new Zo(Cb,Pb,e,n);l.layers=this.layers,this.add(l);const c=new Zo(Cb,Pb,e,n);c.layers=this.layers,this.add(c);const d=new Zo(Cb,Pb,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===fd)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),l.up.set(0,1,0),l.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===V0)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),l.up.set(0,-1,0),l.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const d of n)this.add(d),d.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,d,u]=this.children,m=e.getRenderTarget(),p=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),y=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,l),e.setRenderTarget(r,3,i),e.render(n,c),e.setRenderTarget(r,4,i),e.render(n,d),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=y,r.texture.needsPMREMUpdate=!0}}class GZ extends To{constructor(e,n,r,i,s,o,l,c,d,u){e=e!==void 0?e:[],n=n!==void 0?n:Tx,super(e,n,r,i,s,o,l,c,d,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class MNe extends Vf{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];n.encoding!==void 0&&(c0("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===_f?rs:Il),this.texture=new GZ(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:Ll}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:`
  3865. varying vec3 vWorldDirection;
  3866. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  3867. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  3868. }
  3869. void main() {
  3870. vWorldDirection = transformDirection( position, modelMatrix );
  3871. #include <begin_vertex>
  3872. #include <project_vertex>
  3873. }
  3874. `,fragmentShader:`
  3875. uniform sampler2D tEquirect;
  3876. varying vec3 vWorldDirection;
  3877. #include <common>
  3878. void main() {
  3879. vec3 direction = normalize( vWorldDirection );
  3880. vec2 sampleUV = equirectUv( direction );
  3881. gl_FragColor = texture2D( tEquirect, sampleUV );
  3882. }
  3883. `},i=new Uw(5,5,5),s=new Wh({name:"CubemapFromEquirect",uniforms:jx(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:Po,blending:Rh});s.uniforms.tEquirect.value=n;const o=new Ac(i,s),l=n.minFilter;return n.minFilter===q0&&(n.minFilter=Ll),new ANe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}}const fE=new ot,jNe=new ot,ENe=new lr;class ah{constructor(e=new ot(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=fE.subVectors(r,n).cross(jNe.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(fE),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||ENe.getNormalMatrix(e),i=this.coplanarPoint(fE).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Up=new vd,y1=new ot;class LP{constructor(e=new ah,n=new ah,r=new ah,i=new ah,s=new ah,o=new ah){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(i),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=fd){const r=this.planes,i=e.elements,s=i[0],o=i[1],l=i[2],c=i[3],d=i[4],u=i[5],m=i[6],p=i[7],f=i[8],y=i[9],v=i[10],b=i[11],g=i[12],_=i[13],k=i[14],P=i[15];if(r[0].setComponents(c-s,p-d,b-f,P-g).normalize(),r[1].setComponents(c+s,p+d,b+f,P+g).normalize(),r[2].setComponents(c+o,p+u,b+y,P+_).normalize(),r[3].setComponents(c-o,p-u,b-y,P-_).normalize(),r[4].setComponents(c-l,p-m,b-v,P-k).normalize(),n===fd)r[5].setComponents(c+l,p+m,b+v,P+k).normalize();else if(n===V0)r[5].setComponents(l,m,v,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(),Up.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Up.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Up)}intersectsSprite(e){return Up.center.set(0,0,0),Up.radius=.7071067811865476,Up.applyMatrix4(e.matrixWorld),this.intersectsSphere(Up)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const i=n[r];if(y1.x=i.normal.x>0?e.max.x:e.min.x,y1.y=i.normal.y>0?e.max.y:e.min.y,y1.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(y1)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function WZ(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function DNe(t,e){const n=e.isWebGL2,r=new WeakMap;function i(d,u){const m=d.array,p=d.usage,f=m.byteLength,y=t.createBuffer();t.bindBuffer(u,y),t.bufferData(u,m,p),d.onUploadCallback();let v;if(m instanceof Float32Array)v=t.FLOAT;else if(m instanceof Uint16Array)if(d.isFloat16BufferAttribute)if(n)v=t.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else v=t.UNSIGNED_SHORT;else if(m instanceof Int16Array)v=t.SHORT;else if(m instanceof Uint32Array)v=t.UNSIGNED_INT;else if(m instanceof Int32Array)v=t.INT;else if(m instanceof Int8Array)v=t.BYTE;else if(m instanceof Uint8Array)v=t.UNSIGNED_BYTE;else if(m instanceof Uint8ClampedArray)v=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+m);return{buffer:y,type:v,bytesPerElement:m.BYTES_PER_ELEMENT,version:d.version,size:f}}function s(d,u,m){const p=u.array,f=u._updateRange,y=u.updateRanges;if(t.bindBuffer(m,d),f.count===-1&&y.length===0&&t.bufferSubData(m,0,p),y.length!==0){for(let v=0,b=y.length;v<b;v++){const g=y[v];n?t.bufferSubData(m,g.start*p.BYTES_PER_ELEMENT,p,g.start,g.count):t.bufferSubData(m,g.start*p.BYTES_PER_ELEMENT,p.subarray(g.start,g.start+g.count))}u.clearUpdateRanges()}f.count!==-1&&(n?t.bufferSubData(m,f.offset*p.BYTES_PER_ELEMENT,p,f.offset,f.count):t.bufferSubData(m,f.offset*p.BYTES_PER_ELEMENT,p.subarray(f.offset,f.offset+f.count)),f.count=-1),u.onUploadCallback()}function o(d){return d.isInterleavedBufferAttribute&&(d=d.data),r.get(d)}function l(d){d.isInterleavedBufferAttribute&&(d=d.data);const u=r.get(d);u&&(t.deleteBuffer(u.buffer),r.delete(d))}function c(d,u){if(d.isGLBufferAttribute){const p=r.get(d);(!p||p.version<d.version)&&r.set(d,{buffer:d.buffer,type:d.type,bytesPerElement:d.elementSize,version:d.version});return}d.isInterleavedBufferAttribute&&(d=d.data);const m=r.get(d);if(m===void 0)r.set(d,i(d,u));else if(m.version<d.version){if(m.size!==d.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");s(m.buffer,d,u),m.version=d.version}}return{get:o,remove:l,update:c}}class $O extends Rs{constructor(e=1,n=1,r=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],y=[],v=[],b=[];for(let g=0;g<u;g++){const _=g*p-o;for(let k=0;k<d;k++){const P=k*m-s;y.push(P,-_,0),v.push(0,0,1),b.push(k/l),b.push(1-g/c)}}for(let g=0;g<c;g++)for(let _=0;_<l;_++){const k=_+d*g,P=_+d*(g+1),N=_+1+d*(g+1),M=_+1+d*g;f.push(k,P,M),f.push(P,N,M)}this.setIndex(f),this.setAttribute("position",new Qa(y,3)),this.setAttribute("normal",new Qa(v,3)),this.setAttribute("uv",new Qa(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new $O(e.width,e.height,e.widthSegments,e.heightSegments)}}var FNe=`#ifdef USE_ALPHAHASH
  3884. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  3885. #endif`,RNe=`#ifdef USE_ALPHAHASH
  3886. const float ALPHA_HASH_SCALE = 0.05;
  3887. float hash2D( vec2 value ) {
  3888. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  3889. }
  3890. float hash3D( vec3 value ) {
  3891. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  3892. }
  3893. float getAlphaHashThreshold( vec3 position ) {
  3894. float maxDeriv = max(
  3895. length( dFdx( position.xyz ) ),
  3896. length( dFdy( position.xyz ) )
  3897. );
  3898. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  3899. vec2 pixScales = vec2(
  3900. exp2( floor( log2( pixScale ) ) ),
  3901. exp2( ceil( log2( pixScale ) ) )
  3902. );
  3903. vec2 alpha = vec2(
  3904. hash3D( floor( pixScales.x * position.xyz ) ),
  3905. hash3D( floor( pixScales.y * position.xyz ) )
  3906. );
  3907. float lerpFactor = fract( log2( pixScale ) );
  3908. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  3909. float a = min( lerpFactor, 1.0 - lerpFactor );
  3910. vec3 cases = vec3(
  3911. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  3912. ( x - 0.5 * a ) / ( 1.0 - a ),
  3913. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  3914. );
  3915. float threshold = ( x < ( 1.0 - a ) )
  3916. ? ( ( x < a ) ? cases.x : cases.y )
  3917. : cases.z;
  3918. return clamp( threshold , 1.0e-6, 1.0 );
  3919. }
  3920. #endif`,LNe=`#ifdef USE_ALPHAMAP
  3921. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  3922. #endif`,ONe=`#ifdef USE_ALPHAMAP
  3923. uniform sampler2D alphaMap;
  3924. #endif`,INe=`#ifdef USE_ALPHATEST
  3925. if ( diffuseColor.a < alphaTest ) discard;
  3926. #endif`,zNe=`#ifdef USE_ALPHATEST
  3927. uniform float alphaTest;
  3928. #endif`,UNe=`#ifdef USE_AOMAP
  3929. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  3930. reflectedLight.indirectDiffuse *= ambientOcclusion;
  3931. #if defined( USE_CLEARCOAT )
  3932. clearcoatSpecularIndirect *= ambientOcclusion;
  3933. #endif
  3934. #if defined( USE_SHEEN )
  3935. sheenSpecularIndirect *= ambientOcclusion;
  3936. #endif
  3937. #if defined( USE_ENVMAP ) && defined( STANDARD )
  3938. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  3939. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  3940. #endif
  3941. #endif`,BNe=`#ifdef USE_AOMAP
  3942. uniform sampler2D aoMap;
  3943. uniform float aoMapIntensity;
  3944. #endif`,HNe=`#ifdef USE_BATCHING
  3945. attribute float batchId;
  3946. uniform highp sampler2D batchingTexture;
  3947. mat4 getBatchingMatrix( const in float i ) {
  3948. int size = textureSize( batchingTexture, 0 ).x;
  3949. int j = int( i ) * 4;
  3950. int x = j % size;
  3951. int y = j / size;
  3952. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  3953. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  3954. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  3955. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  3956. return mat4( v1, v2, v3, v4 );
  3957. }
  3958. #endif`,qNe=`#ifdef USE_BATCHING
  3959. mat4 batchingMatrix = getBatchingMatrix( batchId );
  3960. #endif`,$Ne=`vec3 transformed = vec3( position );
  3961. #ifdef USE_ALPHAHASH
  3962. vPosition = vec3( position );
  3963. #endif`,VNe=`vec3 objectNormal = vec3( normal );
  3964. #ifdef USE_TANGENT
  3965. vec3 objectTangent = vec3( tangent.xyz );
  3966. #endif`,GNe=`float G_BlinnPhong_Implicit( ) {
  3967. return 0.25;
  3968. }
  3969. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  3970. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  3971. }
  3972. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  3973. vec3 halfDir = normalize( lightDir + viewDir );
  3974. float dotNH = saturate( dot( normal, halfDir ) );
  3975. float dotVH = saturate( dot( viewDir, halfDir ) );
  3976. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  3977. float G = G_BlinnPhong_Implicit( );
  3978. float D = D_BlinnPhong( shininess, dotNH );
  3979. return F * ( G * D );
  3980. } // validated`,WNe=`#ifdef USE_IRIDESCENCE
  3981. const mat3 XYZ_TO_REC709 = mat3(
  3982. 3.2404542, -0.9692660, 0.0556434,
  3983. -1.5371385, 1.8760108, -0.2040259,
  3984. -0.4985314, 0.0415560, 1.0572252
  3985. );
  3986. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  3987. vec3 sqrtF0 = sqrt( fresnel0 );
  3988. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  3989. }
  3990. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  3991. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  3992. }
  3993. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  3994. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  3995. }
  3996. vec3 evalSensitivity( float OPD, vec3 shift ) {
  3997. float phase = 2.0 * PI * OPD * 1.0e-9;
  3998. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  3999. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  4000. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  4001. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  4002. 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 ) );
  4003. xyz /= 1.0685e-7;
  4004. vec3 rgb = XYZ_TO_REC709 * xyz;
  4005. return rgb;
  4006. }
  4007. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  4008. vec3 I;
  4009. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  4010. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  4011. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  4012. if ( cosTheta2Sq < 0.0 ) {
  4013. return vec3( 1.0 );
  4014. }
  4015. float cosTheta2 = sqrt( cosTheta2Sq );
  4016. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  4017. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  4018. float T121 = 1.0 - R12;
  4019. float phi12 = 0.0;
  4020. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  4021. float phi21 = PI - phi12;
  4022. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  4023. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  4024. vec3 phi23 = vec3( 0.0 );
  4025. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  4026. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  4027. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  4028. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  4029. vec3 phi = vec3( phi21 ) + phi23;
  4030. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  4031. vec3 r123 = sqrt( R123 );
  4032. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  4033. vec3 C0 = R12 + Rs;
  4034. I = C0;
  4035. vec3 Cm = Rs - T121;
  4036. for ( int m = 1; m <= 2; ++ m ) {
  4037. Cm *= r123;
  4038. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  4039. I += Cm * Sm;
  4040. }
  4041. return max( I, vec3( 0.0 ) );
  4042. }
  4043. #endif`,KNe=`#ifdef USE_BUMPMAP
  4044. uniform sampler2D bumpMap;
  4045. uniform float bumpScale;
  4046. vec2 dHdxy_fwd() {
  4047. vec2 dSTdx = dFdx( vBumpMapUv );
  4048. vec2 dSTdy = dFdy( vBumpMapUv );
  4049. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  4050. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  4051. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  4052. return vec2( dBx, dBy );
  4053. }
  4054. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  4055. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  4056. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  4057. vec3 vN = surf_norm;
  4058. vec3 R1 = cross( vSigmaY, vN );
  4059. vec3 R2 = cross( vN, vSigmaX );
  4060. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  4061. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  4062. return normalize( abs( fDet ) * surf_norm - vGrad );
  4063. }
  4064. #endif`,YNe=`#if NUM_CLIPPING_PLANES > 0
  4065. vec4 plane;
  4066. #pragma unroll_loop_start
  4067. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  4068. plane = clippingPlanes[ i ];
  4069. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  4070. }
  4071. #pragma unroll_loop_end
  4072. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  4073. bool clipped = true;
  4074. #pragma unroll_loop_start
  4075. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  4076. plane = clippingPlanes[ i ];
  4077. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  4078. }
  4079. #pragma unroll_loop_end
  4080. if ( clipped ) discard;
  4081. #endif
  4082. #endif`,XNe=`#if NUM_CLIPPING_PLANES > 0
  4083. varying vec3 vClipPosition;
  4084. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  4085. #endif`,QNe=`#if NUM_CLIPPING_PLANES > 0
  4086. varying vec3 vClipPosition;
  4087. #endif`,ZNe=`#if NUM_CLIPPING_PLANES > 0
  4088. vClipPosition = - mvPosition.xyz;
  4089. #endif`,JNe=`#if defined( USE_COLOR_ALPHA )
  4090. diffuseColor *= vColor;
  4091. #elif defined( USE_COLOR )
  4092. diffuseColor.rgb *= vColor;
  4093. #endif`,eCe=`#if defined( USE_COLOR_ALPHA )
  4094. varying vec4 vColor;
  4095. #elif defined( USE_COLOR )
  4096. varying vec3 vColor;
  4097. #endif`,tCe=`#if defined( USE_COLOR_ALPHA )
  4098. varying vec4 vColor;
  4099. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4100. varying vec3 vColor;
  4101. #endif`,nCe=`#if defined( USE_COLOR_ALPHA )
  4102. vColor = vec4( 1.0 );
  4103. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4104. vColor = vec3( 1.0 );
  4105. #endif
  4106. #ifdef USE_COLOR
  4107. vColor *= color;
  4108. #endif
  4109. #ifdef USE_INSTANCING_COLOR
  4110. vColor.xyz *= instanceColor.xyz;
  4111. #endif`,rCe=`#define PI 3.141592653589793
  4112. #define PI2 6.283185307179586
  4113. #define PI_HALF 1.5707963267948966
  4114. #define RECIPROCAL_PI 0.3183098861837907
  4115. #define RECIPROCAL_PI2 0.15915494309189535
  4116. #define EPSILON 1e-6
  4117. #ifndef saturate
  4118. #define saturate( a ) clamp( a, 0.0, 1.0 )
  4119. #endif
  4120. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  4121. float pow2( const in float x ) { return x*x; }
  4122. vec3 pow2( const in vec3 x ) { return x*x; }
  4123. float pow3( const in float x ) { return x*x*x; }
  4124. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  4125. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  4126. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  4127. highp float rand( const in vec2 uv ) {
  4128. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  4129. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  4130. return fract( sin( sn ) * c );
  4131. }
  4132. #ifdef HIGH_PRECISION
  4133. float precisionSafeLength( vec3 v ) { return length( v ); }
  4134. #else
  4135. float precisionSafeLength( vec3 v ) {
  4136. float maxComponent = max3( abs( v ) );
  4137. return length( v / maxComponent ) * maxComponent;
  4138. }
  4139. #endif
  4140. struct IncidentLight {
  4141. vec3 color;
  4142. vec3 direction;
  4143. bool visible;
  4144. };
  4145. struct ReflectedLight {
  4146. vec3 directDiffuse;
  4147. vec3 directSpecular;
  4148. vec3 indirectDiffuse;
  4149. vec3 indirectSpecular;
  4150. };
  4151. #ifdef USE_ALPHAHASH
  4152. varying vec3 vPosition;
  4153. #endif
  4154. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  4155. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  4156. }
  4157. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  4158. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  4159. }
  4160. mat3 transposeMat3( const in mat3 m ) {
  4161. mat3 tmp;
  4162. tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
  4163. tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
  4164. tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
  4165. return tmp;
  4166. }
  4167. float luminance( const in vec3 rgb ) {
  4168. const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
  4169. return dot( weights, rgb );
  4170. }
  4171. bool isPerspectiveMatrix( mat4 m ) {
  4172. return m[ 2 ][ 3 ] == - 1.0;
  4173. }
  4174. vec2 equirectUv( in vec3 dir ) {
  4175. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  4176. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  4177. return vec2( u, v );
  4178. }
  4179. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  4180. return RECIPROCAL_PI * diffuseColor;
  4181. }
  4182. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  4183. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4184. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4185. }
  4186. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  4187. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4188. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4189. } // validated`,aCe=`#ifdef ENVMAP_TYPE_CUBE_UV
  4190. #define cubeUV_minMipLevel 4.0
  4191. #define cubeUV_minTileSize 16.0
  4192. float getFace( vec3 direction ) {
  4193. vec3 absDirection = abs( direction );
  4194. float face = - 1.0;
  4195. if ( absDirection.x > absDirection.z ) {
  4196. if ( absDirection.x > absDirection.y )
  4197. face = direction.x > 0.0 ? 0.0 : 3.0;
  4198. else
  4199. face = direction.y > 0.0 ? 1.0 : 4.0;
  4200. } else {
  4201. if ( absDirection.z > absDirection.y )
  4202. face = direction.z > 0.0 ? 2.0 : 5.0;
  4203. else
  4204. face = direction.y > 0.0 ? 1.0 : 4.0;
  4205. }
  4206. return face;
  4207. }
  4208. vec2 getUV( vec3 direction, float face ) {
  4209. vec2 uv;
  4210. if ( face == 0.0 ) {
  4211. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  4212. } else if ( face == 1.0 ) {
  4213. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  4214. } else if ( face == 2.0 ) {
  4215. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  4216. } else if ( face == 3.0 ) {
  4217. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  4218. } else if ( face == 4.0 ) {
  4219. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  4220. } else {
  4221. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  4222. }
  4223. return 0.5 * ( uv + 1.0 );
  4224. }
  4225. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  4226. float face = getFace( direction );
  4227. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  4228. mipInt = max( mipInt, cubeUV_minMipLevel );
  4229. float faceSize = exp2( mipInt );
  4230. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  4231. if ( face > 2.0 ) {
  4232. uv.y += faceSize;
  4233. face -= 3.0;
  4234. }
  4235. uv.x += face * faceSize;
  4236. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  4237. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  4238. uv.x *= CUBEUV_TEXEL_WIDTH;
  4239. uv.y *= CUBEUV_TEXEL_HEIGHT;
  4240. #ifdef texture2DGradEXT
  4241. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  4242. #else
  4243. return texture2D( envMap, uv ).rgb;
  4244. #endif
  4245. }
  4246. #define cubeUV_r0 1.0
  4247. #define cubeUV_v0 0.339
  4248. #define cubeUV_m0 - 2.0
  4249. #define cubeUV_r1 0.8
  4250. #define cubeUV_v1 0.276
  4251. #define cubeUV_m1 - 1.0
  4252. #define cubeUV_r4 0.4
  4253. #define cubeUV_v4 0.046
  4254. #define cubeUV_m4 2.0
  4255. #define cubeUV_r5 0.305
  4256. #define cubeUV_v5 0.016
  4257. #define cubeUV_m5 3.0
  4258. #define cubeUV_r6 0.21
  4259. #define cubeUV_v6 0.0038
  4260. #define cubeUV_m6 4.0
  4261. float roughnessToMip( float roughness ) {
  4262. float mip = 0.0;
  4263. if ( roughness >= cubeUV_r1 ) {
  4264. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  4265. } else if ( roughness >= cubeUV_r4 ) {
  4266. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  4267. } else if ( roughness >= cubeUV_r5 ) {
  4268. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  4269. } else if ( roughness >= cubeUV_r6 ) {
  4270. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  4271. } else {
  4272. mip = - 2.0 * log2( 1.16 * roughness ); }
  4273. return mip;
  4274. }
  4275. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  4276. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  4277. float mipF = fract( mip );
  4278. float mipInt = floor( mip );
  4279. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  4280. if ( mipF == 0.0 ) {
  4281. return vec4( color0, 1.0 );
  4282. } else {
  4283. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  4284. return vec4( mix( color0, color1, mipF ), 1.0 );
  4285. }
  4286. }
  4287. #endif`,iCe=`vec3 transformedNormal = objectNormal;
  4288. #ifdef USE_TANGENT
  4289. vec3 transformedTangent = objectTangent;
  4290. #endif
  4291. #ifdef USE_BATCHING
  4292. mat3 bm = mat3( batchingMatrix );
  4293. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  4294. transformedNormal = bm * transformedNormal;
  4295. #ifdef USE_TANGENT
  4296. transformedTangent = bm * transformedTangent;
  4297. #endif
  4298. #endif
  4299. #ifdef USE_INSTANCING
  4300. mat3 im = mat3( instanceMatrix );
  4301. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  4302. transformedNormal = im * transformedNormal;
  4303. #ifdef USE_TANGENT
  4304. transformedTangent = im * transformedTangent;
  4305. #endif
  4306. #endif
  4307. transformedNormal = normalMatrix * transformedNormal;
  4308. #ifdef FLIP_SIDED
  4309. transformedNormal = - transformedNormal;
  4310. #endif
  4311. #ifdef USE_TANGENT
  4312. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  4313. #ifdef FLIP_SIDED
  4314. transformedTangent = - transformedTangent;
  4315. #endif
  4316. #endif`,sCe=`#ifdef USE_DISPLACEMENTMAP
  4317. uniform sampler2D displacementMap;
  4318. uniform float displacementScale;
  4319. uniform float displacementBias;
  4320. #endif`,oCe=`#ifdef USE_DISPLACEMENTMAP
  4321. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  4322. #endif`,lCe=`#ifdef USE_EMISSIVEMAP
  4323. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  4324. totalEmissiveRadiance *= emissiveColor.rgb;
  4325. #endif`,cCe=`#ifdef USE_EMISSIVEMAP
  4326. uniform sampler2D emissiveMap;
  4327. #endif`,dCe="gl_FragColor = linearToOutputTexel( gl_FragColor );",uCe=`
  4328. const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
  4329. vec3( 0.8224621, 0.177538, 0.0 ),
  4330. vec3( 0.0331941, 0.9668058, 0.0 ),
  4331. vec3( 0.0170827, 0.0723974, 0.9105199 )
  4332. );
  4333. const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
  4334. vec3( 1.2249401, - 0.2249404, 0.0 ),
  4335. vec3( - 0.0420569, 1.0420571, 0.0 ),
  4336. vec3( - 0.0196376, - 0.0786361, 1.0982735 )
  4337. );
  4338. vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
  4339. return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
  4340. }
  4341. vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
  4342. return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
  4343. }
  4344. vec4 LinearTransferOETF( in vec4 value ) {
  4345. return value;
  4346. }
  4347. vec4 sRGBTransferOETF( in vec4 value ) {
  4348. 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 );
  4349. }
  4350. vec4 LinearToLinear( in vec4 value ) {
  4351. return value;
  4352. }
  4353. vec4 LinearTosRGB( in vec4 value ) {
  4354. return sRGBTransferOETF( value );
  4355. }`,mCe=`#ifdef USE_ENVMAP
  4356. #ifdef ENV_WORLDPOS
  4357. vec3 cameraToFrag;
  4358. if ( isOrthographic ) {
  4359. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4360. } else {
  4361. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  4362. }
  4363. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4364. #ifdef ENVMAP_MODE_REFLECTION
  4365. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  4366. #else
  4367. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  4368. #endif
  4369. #else
  4370. vec3 reflectVec = vReflect;
  4371. #endif
  4372. #ifdef ENVMAP_TYPE_CUBE
  4373. vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  4374. #else
  4375. vec4 envColor = vec4( 0.0 );
  4376. #endif
  4377. #ifdef ENVMAP_BLENDING_MULTIPLY
  4378. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  4379. #elif defined( ENVMAP_BLENDING_MIX )
  4380. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  4381. #elif defined( ENVMAP_BLENDING_ADD )
  4382. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  4383. #endif
  4384. #endif`,hCe=`#ifdef USE_ENVMAP
  4385. uniform float envMapIntensity;
  4386. uniform float flipEnvMap;
  4387. #ifdef ENVMAP_TYPE_CUBE
  4388. uniform samplerCube envMap;
  4389. #else
  4390. uniform sampler2D envMap;
  4391. #endif
  4392. #endif`,pCe=`#ifdef USE_ENVMAP
  4393. uniform float reflectivity;
  4394. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4395. #define ENV_WORLDPOS
  4396. #endif
  4397. #ifdef ENV_WORLDPOS
  4398. varying vec3 vWorldPosition;
  4399. uniform float refractionRatio;
  4400. #else
  4401. varying vec3 vReflect;
  4402. #endif
  4403. #endif`,fCe=`#ifdef USE_ENVMAP
  4404. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4405. #define ENV_WORLDPOS
  4406. #endif
  4407. #ifdef ENV_WORLDPOS
  4408. varying vec3 vWorldPosition;
  4409. #else
  4410. varying vec3 vReflect;
  4411. uniform float refractionRatio;
  4412. #endif
  4413. #endif`,gCe=`#ifdef USE_ENVMAP
  4414. #ifdef ENV_WORLDPOS
  4415. vWorldPosition = worldPosition.xyz;
  4416. #else
  4417. vec3 cameraToVertex;
  4418. if ( isOrthographic ) {
  4419. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4420. } else {
  4421. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  4422. }
  4423. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  4424. #ifdef ENVMAP_MODE_REFLECTION
  4425. vReflect = reflect( cameraToVertex, worldNormal );
  4426. #else
  4427. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  4428. #endif
  4429. #endif
  4430. #endif`,bCe=`#ifdef USE_FOG
  4431. vFogDepth = - mvPosition.z;
  4432. #endif`,xCe=`#ifdef USE_FOG
  4433. varying float vFogDepth;
  4434. #endif`,yCe=`#ifdef USE_FOG
  4435. #ifdef FOG_EXP2
  4436. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  4437. #else
  4438. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  4439. #endif
  4440. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  4441. #endif`,vCe=`#ifdef USE_FOG
  4442. uniform vec3 fogColor;
  4443. varying float vFogDepth;
  4444. #ifdef FOG_EXP2
  4445. uniform float fogDensity;
  4446. #else
  4447. uniform float fogNear;
  4448. uniform float fogFar;
  4449. #endif
  4450. #endif`,wCe=`#ifdef USE_GRADIENTMAP
  4451. uniform sampler2D gradientMap;
  4452. #endif
  4453. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  4454. float dotNL = dot( normal, lightDirection );
  4455. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  4456. #ifdef USE_GRADIENTMAP
  4457. return vec3( texture2D( gradientMap, coord ).r );
  4458. #else
  4459. vec2 fw = fwidth( coord ) * 0.5;
  4460. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  4461. #endif
  4462. }`,SCe=`#ifdef USE_LIGHTMAP
  4463. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  4464. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  4465. reflectedLight.indirectDiffuse += lightMapIrradiance;
  4466. #endif`,_Ce=`#ifdef USE_LIGHTMAP
  4467. uniform sampler2D lightMap;
  4468. uniform float lightMapIntensity;
  4469. #endif`,kCe=`LambertMaterial material;
  4470. material.diffuseColor = diffuseColor.rgb;
  4471. material.specularStrength = specularStrength;`,NCe=`varying vec3 vViewPosition;
  4472. struct LambertMaterial {
  4473. vec3 diffuseColor;
  4474. float specularStrength;
  4475. };
  4476. 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 ) {
  4477. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4478. vec3 irradiance = dotNL * directLight.color;
  4479. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4480. }
  4481. 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 ) {
  4482. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4483. }
  4484. #define RE_Direct RE_Direct_Lambert
  4485. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,CCe=`uniform bool receiveShadow;
  4486. uniform vec3 ambientLightColor;
  4487. #if defined( USE_LIGHT_PROBES )
  4488. uniform vec3 lightProbe[ 9 ];
  4489. #endif
  4490. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  4491. float x = normal.x, y = normal.y, z = normal.z;
  4492. vec3 result = shCoefficients[ 0 ] * 0.886227;
  4493. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  4494. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  4495. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  4496. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  4497. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  4498. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  4499. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  4500. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  4501. return result;
  4502. }
  4503. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  4504. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4505. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  4506. return irradiance;
  4507. }
  4508. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  4509. vec3 irradiance = ambientLightColor;
  4510. return irradiance;
  4511. }
  4512. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  4513. #if defined ( LEGACY_LIGHTS )
  4514. if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
  4515. return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
  4516. }
  4517. return 1.0;
  4518. #else
  4519. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  4520. if ( cutoffDistance > 0.0 ) {
  4521. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  4522. }
  4523. return distanceFalloff;
  4524. #endif
  4525. }
  4526. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  4527. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  4528. }
  4529. #if NUM_DIR_LIGHTS > 0
  4530. struct DirectionalLight {
  4531. vec3 direction;
  4532. vec3 color;
  4533. };
  4534. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  4535. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  4536. light.color = directionalLight.color;
  4537. light.direction = directionalLight.direction;
  4538. light.visible = true;
  4539. }
  4540. #endif
  4541. #if NUM_POINT_LIGHTS > 0
  4542. struct PointLight {
  4543. vec3 position;
  4544. vec3 color;
  4545. float distance;
  4546. float decay;
  4547. };
  4548. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  4549. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4550. vec3 lVector = pointLight.position - geometryPosition;
  4551. light.direction = normalize( lVector );
  4552. float lightDistance = length( lVector );
  4553. light.color = pointLight.color;
  4554. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  4555. light.visible = ( light.color != vec3( 0.0 ) );
  4556. }
  4557. #endif
  4558. #if NUM_SPOT_LIGHTS > 0
  4559. struct SpotLight {
  4560. vec3 position;
  4561. vec3 direction;
  4562. vec3 color;
  4563. float distance;
  4564. float decay;
  4565. float coneCos;
  4566. float penumbraCos;
  4567. };
  4568. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  4569. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4570. vec3 lVector = spotLight.position - geometryPosition;
  4571. light.direction = normalize( lVector );
  4572. float angleCos = dot( light.direction, spotLight.direction );
  4573. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  4574. if ( spotAttenuation > 0.0 ) {
  4575. float lightDistance = length( lVector );
  4576. light.color = spotLight.color * spotAttenuation;
  4577. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  4578. light.visible = ( light.color != vec3( 0.0 ) );
  4579. } else {
  4580. light.color = vec3( 0.0 );
  4581. light.visible = false;
  4582. }
  4583. }
  4584. #endif
  4585. #if NUM_RECT_AREA_LIGHTS > 0
  4586. struct RectAreaLight {
  4587. vec3 color;
  4588. vec3 position;
  4589. vec3 halfWidth;
  4590. vec3 halfHeight;
  4591. };
  4592. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  4593. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  4594. #endif
  4595. #if NUM_HEMI_LIGHTS > 0
  4596. struct HemisphereLight {
  4597. vec3 direction;
  4598. vec3 skyColor;
  4599. vec3 groundColor;
  4600. };
  4601. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  4602. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  4603. float dotNL = dot( normal, hemiLight.direction );
  4604. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  4605. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  4606. return irradiance;
  4607. }
  4608. #endif`,PCe=`#ifdef USE_ENVMAP
  4609. vec3 getIBLIrradiance( const in vec3 normal ) {
  4610. #ifdef ENVMAP_TYPE_CUBE_UV
  4611. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4612. vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
  4613. return PI * envMapColor.rgb * envMapIntensity;
  4614. #else
  4615. return vec3( 0.0 );
  4616. #endif
  4617. }
  4618. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  4619. #ifdef ENVMAP_TYPE_CUBE_UV
  4620. vec3 reflectVec = reflect( - viewDir, normal );
  4621. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  4622. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  4623. vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
  4624. return envMapColor.rgb * envMapIntensity;
  4625. #else
  4626. return vec3( 0.0 );
  4627. #endif
  4628. }
  4629. #ifdef USE_ANISOTROPY
  4630. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  4631. #ifdef ENVMAP_TYPE_CUBE_UV
  4632. vec3 bentNormal = cross( bitangent, viewDir );
  4633. bentNormal = normalize( cross( bentNormal, bitangent ) );
  4634. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  4635. return getIBLRadiance( viewDir, bentNormal, roughness );
  4636. #else
  4637. return vec3( 0.0 );
  4638. #endif
  4639. }
  4640. #endif
  4641. #endif`,TCe=`ToonMaterial material;
  4642. material.diffuseColor = diffuseColor.rgb;`,ACe=`varying vec3 vViewPosition;
  4643. struct ToonMaterial {
  4644. vec3 diffuseColor;
  4645. };
  4646. 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 ) {
  4647. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  4648. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4649. }
  4650. 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 ) {
  4651. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4652. }
  4653. #define RE_Direct RE_Direct_Toon
  4654. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,MCe=`BlinnPhongMaterial material;
  4655. material.diffuseColor = diffuseColor.rgb;
  4656. material.specularColor = specular;
  4657. material.specularShininess = shininess;
  4658. material.specularStrength = specularStrength;`,jCe=`varying vec3 vViewPosition;
  4659. struct BlinnPhongMaterial {
  4660. vec3 diffuseColor;
  4661. vec3 specularColor;
  4662. float specularShininess;
  4663. float specularStrength;
  4664. };
  4665. 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 ) {
  4666. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4667. vec3 irradiance = dotNL * directLight.color;
  4668. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4669. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  4670. }
  4671. 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 ) {
  4672. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4673. }
  4674. #define RE_Direct RE_Direct_BlinnPhong
  4675. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,ECe=`PhysicalMaterial material;
  4676. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  4677. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  4678. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  4679. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  4680. material.roughness = min( material.roughness, 1.0 );
  4681. #ifdef IOR
  4682. material.ior = ior;
  4683. #ifdef USE_SPECULAR
  4684. float specularIntensityFactor = specularIntensity;
  4685. vec3 specularColorFactor = specularColor;
  4686. #ifdef USE_SPECULAR_COLORMAP
  4687. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  4688. #endif
  4689. #ifdef USE_SPECULAR_INTENSITYMAP
  4690. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  4691. #endif
  4692. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  4693. #else
  4694. float specularIntensityFactor = 1.0;
  4695. vec3 specularColorFactor = vec3( 1.0 );
  4696. material.specularF90 = 1.0;
  4697. #endif
  4698. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  4699. #else
  4700. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  4701. material.specularF90 = 1.0;
  4702. #endif
  4703. #ifdef USE_CLEARCOAT
  4704. material.clearcoat = clearcoat;
  4705. material.clearcoatRoughness = clearcoatRoughness;
  4706. material.clearcoatF0 = vec3( 0.04 );
  4707. material.clearcoatF90 = 1.0;
  4708. #ifdef USE_CLEARCOATMAP
  4709. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  4710. #endif
  4711. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  4712. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  4713. #endif
  4714. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  4715. material.clearcoatRoughness += geometryRoughness;
  4716. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  4717. #endif
  4718. #ifdef USE_IRIDESCENCE
  4719. material.iridescence = iridescence;
  4720. material.iridescenceIOR = iridescenceIOR;
  4721. #ifdef USE_IRIDESCENCEMAP
  4722. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  4723. #endif
  4724. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  4725. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  4726. #else
  4727. material.iridescenceThickness = iridescenceThicknessMaximum;
  4728. #endif
  4729. #endif
  4730. #ifdef USE_SHEEN
  4731. material.sheenColor = sheenColor;
  4732. #ifdef USE_SHEEN_COLORMAP
  4733. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  4734. #endif
  4735. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  4736. #ifdef USE_SHEEN_ROUGHNESSMAP
  4737. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  4738. #endif
  4739. #endif
  4740. #ifdef USE_ANISOTROPY
  4741. #ifdef USE_ANISOTROPYMAP
  4742. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  4743. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  4744. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  4745. #else
  4746. vec2 anisotropyV = anisotropyVector;
  4747. #endif
  4748. material.anisotropy = length( anisotropyV );
  4749. if( material.anisotropy == 0.0 ) {
  4750. anisotropyV = vec2( 1.0, 0.0 );
  4751. } else {
  4752. anisotropyV /= material.anisotropy;
  4753. material.anisotropy = saturate( material.anisotropy );
  4754. }
  4755. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  4756. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  4757. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  4758. #endif`,DCe=`struct PhysicalMaterial {
  4759. vec3 diffuseColor;
  4760. float roughness;
  4761. vec3 specularColor;
  4762. float specularF90;
  4763. #ifdef USE_CLEARCOAT
  4764. float clearcoat;
  4765. float clearcoatRoughness;
  4766. vec3 clearcoatF0;
  4767. float clearcoatF90;
  4768. #endif
  4769. #ifdef USE_IRIDESCENCE
  4770. float iridescence;
  4771. float iridescenceIOR;
  4772. float iridescenceThickness;
  4773. vec3 iridescenceFresnel;
  4774. vec3 iridescenceF0;
  4775. #endif
  4776. #ifdef USE_SHEEN
  4777. vec3 sheenColor;
  4778. float sheenRoughness;
  4779. #endif
  4780. #ifdef IOR
  4781. float ior;
  4782. #endif
  4783. #ifdef USE_TRANSMISSION
  4784. float transmission;
  4785. float transmissionAlpha;
  4786. float thickness;
  4787. float attenuationDistance;
  4788. vec3 attenuationColor;
  4789. #endif
  4790. #ifdef USE_ANISOTROPY
  4791. float anisotropy;
  4792. float alphaT;
  4793. vec3 anisotropyT;
  4794. vec3 anisotropyB;
  4795. #endif
  4796. };
  4797. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  4798. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  4799. vec3 sheenSpecularDirect = vec3( 0.0 );
  4800. vec3 sheenSpecularIndirect = vec3(0.0 );
  4801. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  4802. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  4803. float x2 = x * x;
  4804. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  4805. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  4806. }
  4807. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  4808. float a2 = pow2( alpha );
  4809. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  4810. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  4811. return 0.5 / max( gv + gl, EPSILON );
  4812. }
  4813. float D_GGX( const in float alpha, const in float dotNH ) {
  4814. float a2 = pow2( alpha );
  4815. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  4816. return RECIPROCAL_PI * a2 / pow2( denom );
  4817. }
  4818. #ifdef USE_ANISOTROPY
  4819. 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 ) {
  4820. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  4821. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  4822. float v = 0.5 / ( gv + gl );
  4823. return saturate(v);
  4824. }
  4825. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  4826. float a2 = alphaT * alphaB;
  4827. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  4828. highp float v2 = dot( v, v );
  4829. float w2 = a2 / v2;
  4830. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  4831. }
  4832. #endif
  4833. #ifdef USE_CLEARCOAT
  4834. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  4835. vec3 f0 = material.clearcoatF0;
  4836. float f90 = material.clearcoatF90;
  4837. float roughness = material.clearcoatRoughness;
  4838. float alpha = pow2( roughness );
  4839. vec3 halfDir = normalize( lightDir + viewDir );
  4840. float dotNL = saturate( dot( normal, lightDir ) );
  4841. float dotNV = saturate( dot( normal, viewDir ) );
  4842. float dotNH = saturate( dot( normal, halfDir ) );
  4843. float dotVH = saturate( dot( viewDir, halfDir ) );
  4844. vec3 F = F_Schlick( f0, f90, dotVH );
  4845. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4846. float D = D_GGX( alpha, dotNH );
  4847. return F * ( V * D );
  4848. }
  4849. #endif
  4850. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  4851. vec3 f0 = material.specularColor;
  4852. float f90 = material.specularF90;
  4853. float roughness = material.roughness;
  4854. float alpha = pow2( roughness );
  4855. vec3 halfDir = normalize( lightDir + viewDir );
  4856. float dotNL = saturate( dot( normal, lightDir ) );
  4857. float dotNV = saturate( dot( normal, viewDir ) );
  4858. float dotNH = saturate( dot( normal, halfDir ) );
  4859. float dotVH = saturate( dot( viewDir, halfDir ) );
  4860. vec3 F = F_Schlick( f0, f90, dotVH );
  4861. #ifdef USE_IRIDESCENCE
  4862. F = mix( F, material.iridescenceFresnel, material.iridescence );
  4863. #endif
  4864. #ifdef USE_ANISOTROPY
  4865. float dotTL = dot( material.anisotropyT, lightDir );
  4866. float dotTV = dot( material.anisotropyT, viewDir );
  4867. float dotTH = dot( material.anisotropyT, halfDir );
  4868. float dotBL = dot( material.anisotropyB, lightDir );
  4869. float dotBV = dot( material.anisotropyB, viewDir );
  4870. float dotBH = dot( material.anisotropyB, halfDir );
  4871. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  4872. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  4873. #else
  4874. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4875. float D = D_GGX( alpha, dotNH );
  4876. #endif
  4877. return F * ( V * D );
  4878. }
  4879. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  4880. const float LUT_SIZE = 64.0;
  4881. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  4882. const float LUT_BIAS = 0.5 / LUT_SIZE;
  4883. float dotNV = saturate( dot( N, V ) );
  4884. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  4885. uv = uv * LUT_SCALE + LUT_BIAS;
  4886. return uv;
  4887. }
  4888. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  4889. float l = length( f );
  4890. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  4891. }
  4892. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  4893. float x = dot( v1, v2 );
  4894. float y = abs( x );
  4895. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  4896. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  4897. float v = a / b;
  4898. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  4899. return cross( v1, v2 ) * theta_sintheta;
  4900. }
  4901. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  4902. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  4903. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  4904. vec3 lightNormal = cross( v1, v2 );
  4905. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  4906. vec3 T1, T2;
  4907. T1 = normalize( V - N * dot( V, N ) );
  4908. T2 = - cross( N, T1 );
  4909. mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
  4910. vec3 coords[ 4 ];
  4911. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  4912. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  4913. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  4914. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  4915. coords[ 0 ] = normalize( coords[ 0 ] );
  4916. coords[ 1 ] = normalize( coords[ 1 ] );
  4917. coords[ 2 ] = normalize( coords[ 2 ] );
  4918. coords[ 3 ] = normalize( coords[ 3 ] );
  4919. vec3 vectorFormFactor = vec3( 0.0 );
  4920. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  4921. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  4922. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  4923. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  4924. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  4925. return vec3( result );
  4926. }
  4927. #if defined( USE_SHEEN )
  4928. float D_Charlie( float roughness, float dotNH ) {
  4929. float alpha = pow2( roughness );
  4930. float invAlpha = 1.0 / alpha;
  4931. float cos2h = dotNH * dotNH;
  4932. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  4933. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  4934. }
  4935. float V_Neubelt( float dotNV, float dotNL ) {
  4936. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  4937. }
  4938. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  4939. vec3 halfDir = normalize( lightDir + viewDir );
  4940. float dotNL = saturate( dot( normal, lightDir ) );
  4941. float dotNV = saturate( dot( normal, viewDir ) );
  4942. float dotNH = saturate( dot( normal, halfDir ) );
  4943. float D = D_Charlie( sheenRoughness, dotNH );
  4944. float V = V_Neubelt( dotNV, dotNL );
  4945. return sheenColor * ( D * V );
  4946. }
  4947. #endif
  4948. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4949. float dotNV = saturate( dot( normal, viewDir ) );
  4950. float r2 = roughness * roughness;
  4951. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  4952. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  4953. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  4954. return saturate( DG * RECIPROCAL_PI );
  4955. }
  4956. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4957. float dotNV = saturate( dot( normal, viewDir ) );
  4958. const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  4959. const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  4960. vec4 r = roughness * c0 + c1;
  4961. float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
  4962. vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
  4963. return fab;
  4964. }
  4965. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  4966. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4967. return specularColor * fab.x + specularF90 * fab.y;
  4968. }
  4969. #ifdef USE_IRIDESCENCE
  4970. 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 ) {
  4971. #else
  4972. 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 ) {
  4973. #endif
  4974. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4975. #ifdef USE_IRIDESCENCE
  4976. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  4977. #else
  4978. vec3 Fr = specularColor;
  4979. #endif
  4980. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  4981. float Ess = fab.x + fab.y;
  4982. float Ems = 1.0 - Ess;
  4983. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  4984. singleScatter += FssEss;
  4985. multiScatter += Fms * Ems;
  4986. }
  4987. #if NUM_RECT_AREA_LIGHTS > 0
  4988. 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 ) {
  4989. vec3 normal = geometryNormal;
  4990. vec3 viewDir = geometryViewDir;
  4991. vec3 position = geometryPosition;
  4992. vec3 lightPos = rectAreaLight.position;
  4993. vec3 halfWidth = rectAreaLight.halfWidth;
  4994. vec3 halfHeight = rectAreaLight.halfHeight;
  4995. vec3 lightColor = rectAreaLight.color;
  4996. float roughness = material.roughness;
  4997. vec3 rectCoords[ 4 ];
  4998. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  4999. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  5000. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  5001. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  5002. vec4 t1 = texture2D( ltc_1, uv );
  5003. vec4 t2 = texture2D( ltc_2, uv );
  5004. mat3 mInv = mat3(
  5005. vec3( t1.x, 0, t1.y ),
  5006. vec3( 0, 1, 0 ),
  5007. vec3( t1.z, 0, t1.w )
  5008. );
  5009. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  5010. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  5011. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  5012. }
  5013. #endif
  5014. 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 ) {
  5015. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  5016. vec3 irradiance = dotNL * directLight.color;
  5017. #ifdef USE_CLEARCOAT
  5018. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  5019. vec3 ccIrradiance = dotNLcc * directLight.color;
  5020. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  5021. #endif
  5022. #ifdef USE_SHEEN
  5023. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  5024. #endif
  5025. reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
  5026. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5027. }
  5028. 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 ) {
  5029. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5030. }
  5031. 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) {
  5032. #ifdef USE_CLEARCOAT
  5033. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  5034. #endif
  5035. #ifdef USE_SHEEN
  5036. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  5037. #endif
  5038. vec3 singleScattering = vec3( 0.0 );
  5039. vec3 multiScattering = vec3( 0.0 );
  5040. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  5041. #ifdef USE_IRIDESCENCE
  5042. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  5043. #else
  5044. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  5045. #endif
  5046. vec3 totalScattering = singleScattering + multiScattering;
  5047. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  5048. reflectedLight.indirectSpecular += radiance * singleScattering;
  5049. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  5050. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  5051. }
  5052. #define RE_Direct RE_Direct_Physical
  5053. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  5054. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  5055. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  5056. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  5057. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  5058. }`,FCe=`
  5059. vec3 geometryPosition = - vViewPosition;
  5060. vec3 geometryNormal = normal;
  5061. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  5062. vec3 geometryClearcoatNormal = vec3( 0.0 );
  5063. #ifdef USE_CLEARCOAT
  5064. geometryClearcoatNormal = clearcoatNormal;
  5065. #endif
  5066. #ifdef USE_IRIDESCENCE
  5067. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  5068. if ( material.iridescenceThickness == 0.0 ) {
  5069. material.iridescence = 0.0;
  5070. } else {
  5071. material.iridescence = saturate( material.iridescence );
  5072. }
  5073. if ( material.iridescence > 0.0 ) {
  5074. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  5075. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  5076. }
  5077. #endif
  5078. IncidentLight directLight;
  5079. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  5080. PointLight pointLight;
  5081. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  5082. PointLightShadow pointLightShadow;
  5083. #endif
  5084. #pragma unroll_loop_start
  5085. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  5086. pointLight = pointLights[ i ];
  5087. getPointLightInfo( pointLight, geometryPosition, directLight );
  5088. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  5089. pointLightShadow = pointLightShadows[ i ];
  5090. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  5091. #endif
  5092. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5093. }
  5094. #pragma unroll_loop_end
  5095. #endif
  5096. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  5097. SpotLight spotLight;
  5098. vec4 spotColor;
  5099. vec3 spotLightCoord;
  5100. bool inSpotLightMap;
  5101. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  5102. SpotLightShadow spotLightShadow;
  5103. #endif
  5104. #pragma unroll_loop_start
  5105. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  5106. spotLight = spotLights[ i ];
  5107. getSpotLightInfo( spotLight, geometryPosition, directLight );
  5108. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5109. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  5110. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5111. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  5112. #else
  5113. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5114. #endif
  5115. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  5116. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  5117. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  5118. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  5119. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  5120. #endif
  5121. #undef SPOT_LIGHT_MAP_INDEX
  5122. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5123. spotLightShadow = spotLightShadows[ i ];
  5124. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5125. #endif
  5126. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5127. }
  5128. #pragma unroll_loop_end
  5129. #endif
  5130. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  5131. DirectionalLight directionalLight;
  5132. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  5133. DirectionalLightShadow directionalLightShadow;
  5134. #endif
  5135. #pragma unroll_loop_start
  5136. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  5137. directionalLight = directionalLights[ i ];
  5138. getDirectionalLightInfo( directionalLight, directLight );
  5139. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  5140. directionalLightShadow = directionalLightShadows[ i ];
  5141. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5142. #endif
  5143. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5144. }
  5145. #pragma unroll_loop_end
  5146. #endif
  5147. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  5148. RectAreaLight rectAreaLight;
  5149. #pragma unroll_loop_start
  5150. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  5151. rectAreaLight = rectAreaLights[ i ];
  5152. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5153. }
  5154. #pragma unroll_loop_end
  5155. #endif
  5156. #if defined( RE_IndirectDiffuse )
  5157. vec3 iblIrradiance = vec3( 0.0 );
  5158. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  5159. #if defined( USE_LIGHT_PROBES )
  5160. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  5161. #endif
  5162. #if ( NUM_HEMI_LIGHTS > 0 )
  5163. #pragma unroll_loop_start
  5164. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  5165. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  5166. }
  5167. #pragma unroll_loop_end
  5168. #endif
  5169. #endif
  5170. #if defined( RE_IndirectSpecular )
  5171. vec3 radiance = vec3( 0.0 );
  5172. vec3 clearcoatRadiance = vec3( 0.0 );
  5173. #endif`,RCe=`#if defined( RE_IndirectDiffuse )
  5174. #ifdef USE_LIGHTMAP
  5175. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  5176. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  5177. irradiance += lightMapIrradiance;
  5178. #endif
  5179. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  5180. iblIrradiance += getIBLIrradiance( geometryNormal );
  5181. #endif
  5182. #endif
  5183. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  5184. #ifdef USE_ANISOTROPY
  5185. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  5186. #else
  5187. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  5188. #endif
  5189. #ifdef USE_CLEARCOAT
  5190. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  5191. #endif
  5192. #endif`,LCe=`#if defined( RE_IndirectDiffuse )
  5193. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5194. #endif
  5195. #if defined( RE_IndirectSpecular )
  5196. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5197. #endif`,OCe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5198. gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  5199. #endif`,ICe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5200. uniform float logDepthBufFC;
  5201. varying float vFragDepth;
  5202. varying float vIsPerspective;
  5203. #endif`,zCe=`#ifdef USE_LOGDEPTHBUF
  5204. #ifdef USE_LOGDEPTHBUF_EXT
  5205. varying float vFragDepth;
  5206. varying float vIsPerspective;
  5207. #else
  5208. uniform float logDepthBufFC;
  5209. #endif
  5210. #endif`,UCe=`#ifdef USE_LOGDEPTHBUF
  5211. #ifdef USE_LOGDEPTHBUF_EXT
  5212. vFragDepth = 1.0 + gl_Position.w;
  5213. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  5214. #else
  5215. if ( isPerspectiveMatrix( projectionMatrix ) ) {
  5216. gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;
  5217. gl_Position.z *= gl_Position.w;
  5218. }
  5219. #endif
  5220. #endif`,BCe=`#ifdef USE_MAP
  5221. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  5222. #ifdef DECODE_VIDEO_TEXTURE
  5223. 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 );
  5224. #endif
  5225. diffuseColor *= sampledDiffuseColor;
  5226. #endif`,HCe=`#ifdef USE_MAP
  5227. uniform sampler2D map;
  5228. #endif`,qCe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5229. #if defined( USE_POINTS_UV )
  5230. vec2 uv = vUv;
  5231. #else
  5232. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  5233. #endif
  5234. #endif
  5235. #ifdef USE_MAP
  5236. diffuseColor *= texture2D( map, uv );
  5237. #endif
  5238. #ifdef USE_ALPHAMAP
  5239. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  5240. #endif`,$Ce=`#if defined( USE_POINTS_UV )
  5241. varying vec2 vUv;
  5242. #else
  5243. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5244. uniform mat3 uvTransform;
  5245. #endif
  5246. #endif
  5247. #ifdef USE_MAP
  5248. uniform sampler2D map;
  5249. #endif
  5250. #ifdef USE_ALPHAMAP
  5251. uniform sampler2D alphaMap;
  5252. #endif`,VCe=`float metalnessFactor = metalness;
  5253. #ifdef USE_METALNESSMAP
  5254. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  5255. metalnessFactor *= texelMetalness.b;
  5256. #endif`,GCe=`#ifdef USE_METALNESSMAP
  5257. uniform sampler2D metalnessMap;
  5258. #endif`,WCe=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )
  5259. vColor *= morphTargetBaseInfluence;
  5260. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5261. #if defined( USE_COLOR_ALPHA )
  5262. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  5263. #elif defined( USE_COLOR )
  5264. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  5265. #endif
  5266. }
  5267. #endif`,KCe=`#ifdef USE_MORPHNORMALS
  5268. objectNormal *= morphTargetBaseInfluence;
  5269. #ifdef MORPHTARGETS_TEXTURE
  5270. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5271. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  5272. }
  5273. #else
  5274. objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];
  5275. objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];
  5276. objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];
  5277. objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];
  5278. #endif
  5279. #endif`,YCe=`#ifdef USE_MORPHTARGETS
  5280. uniform float morphTargetBaseInfluence;
  5281. #ifdef MORPHTARGETS_TEXTURE
  5282. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  5283. uniform sampler2DArray morphTargetsTexture;
  5284. uniform ivec2 morphTargetsTextureSize;
  5285. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  5286. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  5287. int y = texelIndex / morphTargetsTextureSize.x;
  5288. int x = texelIndex - y * morphTargetsTextureSize.x;
  5289. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  5290. return texelFetch( morphTargetsTexture, morphUV, 0 );
  5291. }
  5292. #else
  5293. #ifndef USE_MORPHNORMALS
  5294. uniform float morphTargetInfluences[ 8 ];
  5295. #else
  5296. uniform float morphTargetInfluences[ 4 ];
  5297. #endif
  5298. #endif
  5299. #endif`,XCe=`#ifdef USE_MORPHTARGETS
  5300. transformed *= morphTargetBaseInfluence;
  5301. #ifdef MORPHTARGETS_TEXTURE
  5302. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5303. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  5304. }
  5305. #else
  5306. transformed += morphTarget0 * morphTargetInfluences[ 0 ];
  5307. transformed += morphTarget1 * morphTargetInfluences[ 1 ];
  5308. transformed += morphTarget2 * morphTargetInfluences[ 2 ];
  5309. transformed += morphTarget3 * morphTargetInfluences[ 3 ];
  5310. #ifndef USE_MORPHNORMALS
  5311. transformed += morphTarget4 * morphTargetInfluences[ 4 ];
  5312. transformed += morphTarget5 * morphTargetInfluences[ 5 ];
  5313. transformed += morphTarget6 * morphTargetInfluences[ 6 ];
  5314. transformed += morphTarget7 * morphTargetInfluences[ 7 ];
  5315. #endif
  5316. #endif
  5317. #endif`,QCe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  5318. #ifdef FLAT_SHADED
  5319. vec3 fdx = dFdx( vViewPosition );
  5320. vec3 fdy = dFdy( vViewPosition );
  5321. vec3 normal = normalize( cross( fdx, fdy ) );
  5322. #else
  5323. vec3 normal = normalize( vNormal );
  5324. #ifdef DOUBLE_SIDED
  5325. normal *= faceDirection;
  5326. #endif
  5327. #endif
  5328. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  5329. #ifdef USE_TANGENT
  5330. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5331. #else
  5332. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  5333. #if defined( USE_NORMALMAP )
  5334. vNormalMapUv
  5335. #elif defined( USE_CLEARCOAT_NORMALMAP )
  5336. vClearcoatNormalMapUv
  5337. #else
  5338. vUv
  5339. #endif
  5340. );
  5341. #endif
  5342. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5343. tbn[0] *= faceDirection;
  5344. tbn[1] *= faceDirection;
  5345. #endif
  5346. #endif
  5347. #ifdef USE_CLEARCOAT_NORMALMAP
  5348. #ifdef USE_TANGENT
  5349. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5350. #else
  5351. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  5352. #endif
  5353. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5354. tbn2[0] *= faceDirection;
  5355. tbn2[1] *= faceDirection;
  5356. #endif
  5357. #endif
  5358. vec3 nonPerturbedNormal = normal;`,ZCe=`#ifdef USE_NORMALMAP_OBJECTSPACE
  5359. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5360. #ifdef FLIP_SIDED
  5361. normal = - normal;
  5362. #endif
  5363. #ifdef DOUBLE_SIDED
  5364. normal = normal * faceDirection;
  5365. #endif
  5366. normal = normalize( normalMatrix * normal );
  5367. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  5368. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5369. mapN.xy *= normalScale;
  5370. normal = normalize( tbn * mapN );
  5371. #elif defined( USE_BUMPMAP )
  5372. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  5373. #endif`,JCe=`#ifndef FLAT_SHADED
  5374. varying vec3 vNormal;
  5375. #ifdef USE_TANGENT
  5376. varying vec3 vTangent;
  5377. varying vec3 vBitangent;
  5378. #endif
  5379. #endif`,ePe=`#ifndef FLAT_SHADED
  5380. varying vec3 vNormal;
  5381. #ifdef USE_TANGENT
  5382. varying vec3 vTangent;
  5383. varying vec3 vBitangent;
  5384. #endif
  5385. #endif`,tPe=`#ifndef FLAT_SHADED
  5386. vNormal = normalize( transformedNormal );
  5387. #ifdef USE_TANGENT
  5388. vTangent = normalize( transformedTangent );
  5389. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  5390. #endif
  5391. #endif`,nPe=`#ifdef USE_NORMALMAP
  5392. uniform sampler2D normalMap;
  5393. uniform vec2 normalScale;
  5394. #endif
  5395. #ifdef USE_NORMALMAP_OBJECTSPACE
  5396. uniform mat3 normalMatrix;
  5397. #endif
  5398. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  5399. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  5400. vec3 q0 = dFdx( eye_pos.xyz );
  5401. vec3 q1 = dFdy( eye_pos.xyz );
  5402. vec2 st0 = dFdx( uv.st );
  5403. vec2 st1 = dFdy( uv.st );
  5404. vec3 N = surf_norm;
  5405. vec3 q1perp = cross( q1, N );
  5406. vec3 q0perp = cross( N, q0 );
  5407. vec3 T = q1perp * st0.x + q0perp * st1.x;
  5408. vec3 B = q1perp * st0.y + q0perp * st1.y;
  5409. float det = max( dot( T, T ), dot( B, B ) );
  5410. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  5411. return mat3( T * scale, B * scale, N );
  5412. }
  5413. #endif`,rPe=`#ifdef USE_CLEARCOAT
  5414. vec3 clearcoatNormal = nonPerturbedNormal;
  5415. #endif`,aPe=`#ifdef USE_CLEARCOAT_NORMALMAP
  5416. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  5417. clearcoatMapN.xy *= clearcoatNormalScale;
  5418. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  5419. #endif`,iPe=`#ifdef USE_CLEARCOATMAP
  5420. uniform sampler2D clearcoatMap;
  5421. #endif
  5422. #ifdef USE_CLEARCOAT_NORMALMAP
  5423. uniform sampler2D clearcoatNormalMap;
  5424. uniform vec2 clearcoatNormalScale;
  5425. #endif
  5426. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  5427. uniform sampler2D clearcoatRoughnessMap;
  5428. #endif`,sPe=`#ifdef USE_IRIDESCENCEMAP
  5429. uniform sampler2D iridescenceMap;
  5430. #endif
  5431. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  5432. uniform sampler2D iridescenceThicknessMap;
  5433. #endif`,oPe=`#ifdef OPAQUE
  5434. diffuseColor.a = 1.0;
  5435. #endif
  5436. #ifdef USE_TRANSMISSION
  5437. diffuseColor.a *= material.transmissionAlpha;
  5438. #endif
  5439. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,lPe=`vec3 packNormalToRGB( const in vec3 normal ) {
  5440. return normalize( normal ) * 0.5 + 0.5;
  5441. }
  5442. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  5443. return 2.0 * rgb.xyz - 1.0;
  5444. }
  5445. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
  5446. const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
  5447. const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
  5448. const float ShiftRight8 = 1. / 256.;
  5449. vec4 packDepthToRGBA( const in float v ) {
  5450. vec4 r = vec4( fract( v * PackFactors ), v );
  5451. r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;
  5452. }
  5453. float unpackRGBAToDepth( const in vec4 v ) {
  5454. return dot( v, UnpackFactors );
  5455. }
  5456. vec2 packDepthToRG( in highp float v ) {
  5457. return packDepthToRGBA( v ).yx;
  5458. }
  5459. float unpackRGToDepth( const in highp vec2 v ) {
  5460. return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
  5461. }
  5462. vec4 pack2HalfToRGBA( vec2 v ) {
  5463. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  5464. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  5465. }
  5466. vec2 unpackRGBATo2Half( vec4 v ) {
  5467. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  5468. }
  5469. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  5470. return ( viewZ + near ) / ( near - far );
  5471. }
  5472. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5473. return depth * ( near - far ) - near;
  5474. }
  5475. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  5476. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  5477. }
  5478. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5479. return ( near * far ) / ( ( far - near ) * depth - far );
  5480. }`,cPe=`#ifdef PREMULTIPLIED_ALPHA
  5481. gl_FragColor.rgb *= gl_FragColor.a;
  5482. #endif`,dPe=`vec4 mvPosition = vec4( transformed, 1.0 );
  5483. #ifdef USE_BATCHING
  5484. mvPosition = batchingMatrix * mvPosition;
  5485. #endif
  5486. #ifdef USE_INSTANCING
  5487. mvPosition = instanceMatrix * mvPosition;
  5488. #endif
  5489. mvPosition = modelViewMatrix * mvPosition;
  5490. gl_Position = projectionMatrix * mvPosition;`,uPe=`#ifdef DITHERING
  5491. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  5492. #endif`,mPe=`#ifdef DITHERING
  5493. vec3 dithering( vec3 color ) {
  5494. float grid_position = rand( gl_FragCoord.xy );
  5495. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  5496. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  5497. return color + dither_shift_RGB;
  5498. }
  5499. #endif`,hPe=`float roughnessFactor = roughness;
  5500. #ifdef USE_ROUGHNESSMAP
  5501. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  5502. roughnessFactor *= texelRoughness.g;
  5503. #endif`,pPe=`#ifdef USE_ROUGHNESSMAP
  5504. uniform sampler2D roughnessMap;
  5505. #endif`,fPe=`#if NUM_SPOT_LIGHT_COORDS > 0
  5506. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5507. #endif
  5508. #if NUM_SPOT_LIGHT_MAPS > 0
  5509. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  5510. #endif
  5511. #ifdef USE_SHADOWMAP
  5512. #if NUM_DIR_LIGHT_SHADOWS > 0
  5513. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  5514. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5515. struct DirectionalLightShadow {
  5516. float shadowBias;
  5517. float shadowNormalBias;
  5518. float shadowRadius;
  5519. vec2 shadowMapSize;
  5520. };
  5521. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5522. #endif
  5523. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5524. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  5525. struct SpotLightShadow {
  5526. float shadowBias;
  5527. float shadowNormalBias;
  5528. float shadowRadius;
  5529. vec2 shadowMapSize;
  5530. };
  5531. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5532. #endif
  5533. #if NUM_POINT_LIGHT_SHADOWS > 0
  5534. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  5535. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5536. struct PointLightShadow {
  5537. float shadowBias;
  5538. float shadowNormalBias;
  5539. float shadowRadius;
  5540. vec2 shadowMapSize;
  5541. float shadowCameraNear;
  5542. float shadowCameraFar;
  5543. };
  5544. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5545. #endif
  5546. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  5547. return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
  5548. }
  5549. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  5550. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  5551. }
  5552. float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
  5553. float occlusion = 1.0;
  5554. vec2 distribution = texture2DDistribution( shadow, uv );
  5555. float hard_shadow = step( compare , distribution.x );
  5556. if (hard_shadow != 1.0 ) {
  5557. float distance = compare - distribution.x ;
  5558. float variance = max( 0.00000, distribution.y * distribution.y );
  5559. 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 );
  5560. }
  5561. return occlusion;
  5562. }
  5563. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  5564. float shadow = 1.0;
  5565. shadowCoord.xyz /= shadowCoord.w;
  5566. shadowCoord.z += shadowBias;
  5567. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  5568. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  5569. if ( frustumTest ) {
  5570. #if defined( SHADOWMAP_TYPE_PCF )
  5571. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5572. float dx0 = - texelSize.x * shadowRadius;
  5573. float dy0 = - texelSize.y * shadowRadius;
  5574. float dx1 = + texelSize.x * shadowRadius;
  5575. float dy1 = + texelSize.y * shadowRadius;
  5576. float dx2 = dx0 / 2.0;
  5577. float dy2 = dy0 / 2.0;
  5578. float dx3 = dx1 / 2.0;
  5579. float dy3 = dy1 / 2.0;
  5580. shadow = (
  5581. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  5582. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  5583. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  5584. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  5585. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  5586. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  5587. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  5588. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  5589. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  5590. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  5591. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  5592. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  5593. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  5594. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  5595. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  5596. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  5597. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  5598. ) * ( 1.0 / 17.0 );
  5599. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  5600. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5601. float dx = texelSize.x;
  5602. float dy = texelSize.y;
  5603. vec2 uv = shadowCoord.xy;
  5604. vec2 f = fract( uv * shadowMapSize + 0.5 );
  5605. uv -= f * texelSize;
  5606. shadow = (
  5607. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  5608. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  5609. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  5610. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  5611. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  5612. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  5613. f.x ) +
  5614. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  5615. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  5616. f.x ) +
  5617. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  5618. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  5619. f.y ) +
  5620. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  5621. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  5622. f.y ) +
  5623. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  5624. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  5625. f.x ),
  5626. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  5627. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  5628. f.x ),
  5629. f.y )
  5630. ) * ( 1.0 / 9.0 );
  5631. #elif defined( SHADOWMAP_TYPE_VSM )
  5632. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  5633. #else
  5634. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  5635. #endif
  5636. }
  5637. return shadow;
  5638. }
  5639. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  5640. vec3 absV = abs( v );
  5641. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  5642. absV *= scaleToCube;
  5643. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  5644. vec2 planar = v.xy;
  5645. float almostATexel = 1.5 * texelSizeY;
  5646. float almostOne = 1.0 - almostATexel;
  5647. if ( absV.z >= almostOne ) {
  5648. if ( v.z > 0.0 )
  5649. planar.x = 4.0 - v.x;
  5650. } else if ( absV.x >= almostOne ) {
  5651. float signX = sign( v.x );
  5652. planar.x = v.z * signX + 2.0 * signX;
  5653. } else if ( absV.y >= almostOne ) {
  5654. float signY = sign( v.y );
  5655. planar.x = v.x + 2.0 * signY + 2.0;
  5656. planar.y = v.z * signY - 2.0;
  5657. }
  5658. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  5659. }
  5660. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  5661. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  5662. vec3 lightToPosition = shadowCoord.xyz;
  5663. float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  5664. vec3 bd3D = normalize( lightToPosition );
  5665. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  5666. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  5667. return (
  5668. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  5669. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  5670. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  5671. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  5672. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  5673. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  5674. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  5675. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  5676. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  5677. ) * ( 1.0 / 9.0 );
  5678. #else
  5679. return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  5680. #endif
  5681. }
  5682. #endif`,gPe=`#if NUM_SPOT_LIGHT_COORDS > 0
  5683. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  5684. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5685. #endif
  5686. #ifdef USE_SHADOWMAP
  5687. #if NUM_DIR_LIGHT_SHADOWS > 0
  5688. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  5689. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5690. struct DirectionalLightShadow {
  5691. float shadowBias;
  5692. float shadowNormalBias;
  5693. float shadowRadius;
  5694. vec2 shadowMapSize;
  5695. };
  5696. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5697. #endif
  5698. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5699. struct SpotLightShadow {
  5700. float shadowBias;
  5701. float shadowNormalBias;
  5702. float shadowRadius;
  5703. vec2 shadowMapSize;
  5704. };
  5705. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5706. #endif
  5707. #if NUM_POINT_LIGHT_SHADOWS > 0
  5708. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  5709. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5710. struct PointLightShadow {
  5711. float shadowBias;
  5712. float shadowNormalBias;
  5713. float shadowRadius;
  5714. vec2 shadowMapSize;
  5715. float shadowCameraNear;
  5716. float shadowCameraFar;
  5717. };
  5718. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5719. #endif
  5720. #endif`,bPe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  5721. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  5722. vec4 shadowWorldPosition;
  5723. #endif
  5724. #if defined( USE_SHADOWMAP )
  5725. #if NUM_DIR_LIGHT_SHADOWS > 0
  5726. #pragma unroll_loop_start
  5727. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5728. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  5729. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  5730. }
  5731. #pragma unroll_loop_end
  5732. #endif
  5733. #if NUM_POINT_LIGHT_SHADOWS > 0
  5734. #pragma unroll_loop_start
  5735. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5736. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  5737. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  5738. }
  5739. #pragma unroll_loop_end
  5740. #endif
  5741. #endif
  5742. #if NUM_SPOT_LIGHT_COORDS > 0
  5743. #pragma unroll_loop_start
  5744. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  5745. shadowWorldPosition = worldPosition;
  5746. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5747. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  5748. #endif
  5749. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  5750. }
  5751. #pragma unroll_loop_end
  5752. #endif`,xPe=`float getShadowMask() {
  5753. float shadow = 1.0;
  5754. #ifdef USE_SHADOWMAP
  5755. #if NUM_DIR_LIGHT_SHADOWS > 0
  5756. DirectionalLightShadow directionalLight;
  5757. #pragma unroll_loop_start
  5758. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5759. directionalLight = directionalLightShadows[ i ];
  5760. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5761. }
  5762. #pragma unroll_loop_end
  5763. #endif
  5764. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5765. SpotLightShadow spotLight;
  5766. #pragma unroll_loop_start
  5767. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  5768. spotLight = spotLightShadows[ i ];
  5769. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5770. }
  5771. #pragma unroll_loop_end
  5772. #endif
  5773. #if NUM_POINT_LIGHT_SHADOWS > 0
  5774. PointLightShadow pointLight;
  5775. #pragma unroll_loop_start
  5776. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5777. pointLight = pointLightShadows[ i ];
  5778. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  5779. }
  5780. #pragma unroll_loop_end
  5781. #endif
  5782. #endif
  5783. return shadow;
  5784. }`,yPe=`#ifdef USE_SKINNING
  5785. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  5786. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  5787. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  5788. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  5789. #endif`,vPe=`#ifdef USE_SKINNING
  5790. uniform mat4 bindMatrix;
  5791. uniform mat4 bindMatrixInverse;
  5792. uniform highp sampler2D boneTexture;
  5793. mat4 getBoneMatrix( const in float i ) {
  5794. int size = textureSize( boneTexture, 0 ).x;
  5795. int j = int( i ) * 4;
  5796. int x = j % size;
  5797. int y = j / size;
  5798. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  5799. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  5800. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  5801. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  5802. return mat4( v1, v2, v3, v4 );
  5803. }
  5804. #endif`,wPe=`#ifdef USE_SKINNING
  5805. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  5806. vec4 skinned = vec4( 0.0 );
  5807. skinned += boneMatX * skinVertex * skinWeight.x;
  5808. skinned += boneMatY * skinVertex * skinWeight.y;
  5809. skinned += boneMatZ * skinVertex * skinWeight.z;
  5810. skinned += boneMatW * skinVertex * skinWeight.w;
  5811. transformed = ( bindMatrixInverse * skinned ).xyz;
  5812. #endif`,SPe=`#ifdef USE_SKINNING
  5813. mat4 skinMatrix = mat4( 0.0 );
  5814. skinMatrix += skinWeight.x * boneMatX;
  5815. skinMatrix += skinWeight.y * boneMatY;
  5816. skinMatrix += skinWeight.z * boneMatZ;
  5817. skinMatrix += skinWeight.w * boneMatW;
  5818. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  5819. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  5820. #ifdef USE_TANGENT
  5821. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  5822. #endif
  5823. #endif`,_Pe=`float specularStrength;
  5824. #ifdef USE_SPECULARMAP
  5825. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  5826. specularStrength = texelSpecular.r;
  5827. #else
  5828. specularStrength = 1.0;
  5829. #endif`,kPe=`#ifdef USE_SPECULARMAP
  5830. uniform sampler2D specularMap;
  5831. #endif`,NPe=`#if defined( TONE_MAPPING )
  5832. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  5833. #endif`,CPe=`#ifndef saturate
  5834. #define saturate( a ) clamp( a, 0.0, 1.0 )
  5835. #endif
  5836. uniform float toneMappingExposure;
  5837. vec3 LinearToneMapping( vec3 color ) {
  5838. return saturate( toneMappingExposure * color );
  5839. }
  5840. vec3 ReinhardToneMapping( vec3 color ) {
  5841. color *= toneMappingExposure;
  5842. return saturate( color / ( vec3( 1.0 ) + color ) );
  5843. }
  5844. vec3 OptimizedCineonToneMapping( vec3 color ) {
  5845. color *= toneMappingExposure;
  5846. color = max( vec3( 0.0 ), color - 0.004 );
  5847. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  5848. }
  5849. vec3 RRTAndODTFit( vec3 v ) {
  5850. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  5851. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  5852. return a / b;
  5853. }
  5854. vec3 ACESFilmicToneMapping( vec3 color ) {
  5855. const mat3 ACESInputMat = mat3(
  5856. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  5857. vec3( 0.04823, 0.01566, 0.83777 )
  5858. );
  5859. const mat3 ACESOutputMat = mat3(
  5860. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  5861. vec3( -0.07367, -0.00605, 1.07602 )
  5862. );
  5863. color *= toneMappingExposure / 0.6;
  5864. color = ACESInputMat * color;
  5865. color = RRTAndODTFit( color );
  5866. color = ACESOutputMat * color;
  5867. return saturate( color );
  5868. }
  5869. vec3 CustomToneMapping( vec3 color ) { return color; }`,PPe=`#ifdef USE_TRANSMISSION
  5870. material.transmission = transmission;
  5871. material.transmissionAlpha = 1.0;
  5872. material.thickness = thickness;
  5873. material.attenuationDistance = attenuationDistance;
  5874. material.attenuationColor = attenuationColor;
  5875. #ifdef USE_TRANSMISSIONMAP
  5876. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  5877. #endif
  5878. #ifdef USE_THICKNESSMAP
  5879. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  5880. #endif
  5881. vec3 pos = vWorldPosition;
  5882. vec3 v = normalize( cameraPosition - pos );
  5883. vec3 n = inverseTransformDirection( normal, viewMatrix );
  5884. vec4 transmitted = getIBLVolumeRefraction(
  5885. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  5886. pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,
  5887. material.attenuationColor, material.attenuationDistance );
  5888. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  5889. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  5890. #endif`,TPe=`#ifdef USE_TRANSMISSION
  5891. uniform float transmission;
  5892. uniform float thickness;
  5893. uniform float attenuationDistance;
  5894. uniform vec3 attenuationColor;
  5895. #ifdef USE_TRANSMISSIONMAP
  5896. uniform sampler2D transmissionMap;
  5897. #endif
  5898. #ifdef USE_THICKNESSMAP
  5899. uniform sampler2D thicknessMap;
  5900. #endif
  5901. uniform vec2 transmissionSamplerSize;
  5902. uniform sampler2D transmissionSamplerMap;
  5903. uniform mat4 modelMatrix;
  5904. uniform mat4 projectionMatrix;
  5905. varying vec3 vWorldPosition;
  5906. float w0( float a ) {
  5907. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  5908. }
  5909. float w1( float a ) {
  5910. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  5911. }
  5912. float w2( float a ){
  5913. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  5914. }
  5915. float w3( float a ) {
  5916. return ( 1.0 / 6.0 ) * ( a * a * a );
  5917. }
  5918. float g0( float a ) {
  5919. return w0( a ) + w1( a );
  5920. }
  5921. float g1( float a ) {
  5922. return w2( a ) + w3( a );
  5923. }
  5924. float h0( float a ) {
  5925. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  5926. }
  5927. float h1( float a ) {
  5928. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  5929. }
  5930. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  5931. uv = uv * texelSize.zw + 0.5;
  5932. vec2 iuv = floor( uv );
  5933. vec2 fuv = fract( uv );
  5934. float g0x = g0( fuv.x );
  5935. float g1x = g1( fuv.x );
  5936. float h0x = h0( fuv.x );
  5937. float h1x = h1( fuv.x );
  5938. float h0y = h0( fuv.y );
  5939. float h1y = h1( fuv.y );
  5940. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5941. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5942. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5943. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5944. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  5945. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  5946. }
  5947. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  5948. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  5949. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  5950. vec2 fLodSizeInv = 1.0 / fLodSize;
  5951. vec2 cLodSizeInv = 1.0 / cLodSize;
  5952. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  5953. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  5954. return mix( fSample, cSample, fract( lod ) );
  5955. }
  5956. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  5957. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  5958. vec3 modelScale;
  5959. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  5960. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  5961. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  5962. return normalize( refractionVector ) * thickness * modelScale;
  5963. }
  5964. float applyIorToRoughness( const in float roughness, const in float ior ) {
  5965. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  5966. }
  5967. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  5968. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  5969. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  5970. }
  5971. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  5972. if ( isinf( attenuationDistance ) ) {
  5973. return vec3( 1.0 );
  5974. } else {
  5975. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  5976. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  5977. }
  5978. }
  5979. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  5980. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  5981. const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
  5982. const in vec3 attenuationColor, const in float attenuationDistance ) {
  5983. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  5984. vec3 refractedRayExit = position + transmissionRay;
  5985. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  5986. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  5987. refractionCoords += 1.0;
  5988. refractionCoords /= 2.0;
  5989. vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  5990. vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  5991. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  5992. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  5993. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  5994. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  5995. }
  5996. #endif`,APe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  5997. varying vec2 vUv;
  5998. #endif
  5999. #ifdef USE_MAP
  6000. varying vec2 vMapUv;
  6001. #endif
  6002. #ifdef USE_ALPHAMAP
  6003. varying vec2 vAlphaMapUv;
  6004. #endif
  6005. #ifdef USE_LIGHTMAP
  6006. varying vec2 vLightMapUv;
  6007. #endif
  6008. #ifdef USE_AOMAP
  6009. varying vec2 vAoMapUv;
  6010. #endif
  6011. #ifdef USE_BUMPMAP
  6012. varying vec2 vBumpMapUv;
  6013. #endif
  6014. #ifdef USE_NORMALMAP
  6015. varying vec2 vNormalMapUv;
  6016. #endif
  6017. #ifdef USE_EMISSIVEMAP
  6018. varying vec2 vEmissiveMapUv;
  6019. #endif
  6020. #ifdef USE_METALNESSMAP
  6021. varying vec2 vMetalnessMapUv;
  6022. #endif
  6023. #ifdef USE_ROUGHNESSMAP
  6024. varying vec2 vRoughnessMapUv;
  6025. #endif
  6026. #ifdef USE_ANISOTROPYMAP
  6027. varying vec2 vAnisotropyMapUv;
  6028. #endif
  6029. #ifdef USE_CLEARCOATMAP
  6030. varying vec2 vClearcoatMapUv;
  6031. #endif
  6032. #ifdef USE_CLEARCOAT_NORMALMAP
  6033. varying vec2 vClearcoatNormalMapUv;
  6034. #endif
  6035. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6036. varying vec2 vClearcoatRoughnessMapUv;
  6037. #endif
  6038. #ifdef USE_IRIDESCENCEMAP
  6039. varying vec2 vIridescenceMapUv;
  6040. #endif
  6041. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6042. varying vec2 vIridescenceThicknessMapUv;
  6043. #endif
  6044. #ifdef USE_SHEEN_COLORMAP
  6045. varying vec2 vSheenColorMapUv;
  6046. #endif
  6047. #ifdef USE_SHEEN_ROUGHNESSMAP
  6048. varying vec2 vSheenRoughnessMapUv;
  6049. #endif
  6050. #ifdef USE_SPECULARMAP
  6051. varying vec2 vSpecularMapUv;
  6052. #endif
  6053. #ifdef USE_SPECULAR_COLORMAP
  6054. varying vec2 vSpecularColorMapUv;
  6055. #endif
  6056. #ifdef USE_SPECULAR_INTENSITYMAP
  6057. varying vec2 vSpecularIntensityMapUv;
  6058. #endif
  6059. #ifdef USE_TRANSMISSIONMAP
  6060. uniform mat3 transmissionMapTransform;
  6061. varying vec2 vTransmissionMapUv;
  6062. #endif
  6063. #ifdef USE_THICKNESSMAP
  6064. uniform mat3 thicknessMapTransform;
  6065. varying vec2 vThicknessMapUv;
  6066. #endif`,MPe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6067. varying vec2 vUv;
  6068. #endif
  6069. #ifdef USE_MAP
  6070. uniform mat3 mapTransform;
  6071. varying vec2 vMapUv;
  6072. #endif
  6073. #ifdef USE_ALPHAMAP
  6074. uniform mat3 alphaMapTransform;
  6075. varying vec2 vAlphaMapUv;
  6076. #endif
  6077. #ifdef USE_LIGHTMAP
  6078. uniform mat3 lightMapTransform;
  6079. varying vec2 vLightMapUv;
  6080. #endif
  6081. #ifdef USE_AOMAP
  6082. uniform mat3 aoMapTransform;
  6083. varying vec2 vAoMapUv;
  6084. #endif
  6085. #ifdef USE_BUMPMAP
  6086. uniform mat3 bumpMapTransform;
  6087. varying vec2 vBumpMapUv;
  6088. #endif
  6089. #ifdef USE_NORMALMAP
  6090. uniform mat3 normalMapTransform;
  6091. varying vec2 vNormalMapUv;
  6092. #endif
  6093. #ifdef USE_DISPLACEMENTMAP
  6094. uniform mat3 displacementMapTransform;
  6095. varying vec2 vDisplacementMapUv;
  6096. #endif
  6097. #ifdef USE_EMISSIVEMAP
  6098. uniform mat3 emissiveMapTransform;
  6099. varying vec2 vEmissiveMapUv;
  6100. #endif
  6101. #ifdef USE_METALNESSMAP
  6102. uniform mat3 metalnessMapTransform;
  6103. varying vec2 vMetalnessMapUv;
  6104. #endif
  6105. #ifdef USE_ROUGHNESSMAP
  6106. uniform mat3 roughnessMapTransform;
  6107. varying vec2 vRoughnessMapUv;
  6108. #endif
  6109. #ifdef USE_ANISOTROPYMAP
  6110. uniform mat3 anisotropyMapTransform;
  6111. varying vec2 vAnisotropyMapUv;
  6112. #endif
  6113. #ifdef USE_CLEARCOATMAP
  6114. uniform mat3 clearcoatMapTransform;
  6115. varying vec2 vClearcoatMapUv;
  6116. #endif
  6117. #ifdef USE_CLEARCOAT_NORMALMAP
  6118. uniform mat3 clearcoatNormalMapTransform;
  6119. varying vec2 vClearcoatNormalMapUv;
  6120. #endif
  6121. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6122. uniform mat3 clearcoatRoughnessMapTransform;
  6123. varying vec2 vClearcoatRoughnessMapUv;
  6124. #endif
  6125. #ifdef USE_SHEEN_COLORMAP
  6126. uniform mat3 sheenColorMapTransform;
  6127. varying vec2 vSheenColorMapUv;
  6128. #endif
  6129. #ifdef USE_SHEEN_ROUGHNESSMAP
  6130. uniform mat3 sheenRoughnessMapTransform;
  6131. varying vec2 vSheenRoughnessMapUv;
  6132. #endif
  6133. #ifdef USE_IRIDESCENCEMAP
  6134. uniform mat3 iridescenceMapTransform;
  6135. varying vec2 vIridescenceMapUv;
  6136. #endif
  6137. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6138. uniform mat3 iridescenceThicknessMapTransform;
  6139. varying vec2 vIridescenceThicknessMapUv;
  6140. #endif
  6141. #ifdef USE_SPECULARMAP
  6142. uniform mat3 specularMapTransform;
  6143. varying vec2 vSpecularMapUv;
  6144. #endif
  6145. #ifdef USE_SPECULAR_COLORMAP
  6146. uniform mat3 specularColorMapTransform;
  6147. varying vec2 vSpecularColorMapUv;
  6148. #endif
  6149. #ifdef USE_SPECULAR_INTENSITYMAP
  6150. uniform mat3 specularIntensityMapTransform;
  6151. varying vec2 vSpecularIntensityMapUv;
  6152. #endif
  6153. #ifdef USE_TRANSMISSIONMAP
  6154. uniform mat3 transmissionMapTransform;
  6155. varying vec2 vTransmissionMapUv;
  6156. #endif
  6157. #ifdef USE_THICKNESSMAP
  6158. uniform mat3 thicknessMapTransform;
  6159. varying vec2 vThicknessMapUv;
  6160. #endif`,jPe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6161. vUv = vec3( uv, 1 ).xy;
  6162. #endif
  6163. #ifdef USE_MAP
  6164. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  6165. #endif
  6166. #ifdef USE_ALPHAMAP
  6167. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  6168. #endif
  6169. #ifdef USE_LIGHTMAP
  6170. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  6171. #endif
  6172. #ifdef USE_AOMAP
  6173. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  6174. #endif
  6175. #ifdef USE_BUMPMAP
  6176. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  6177. #endif
  6178. #ifdef USE_NORMALMAP
  6179. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  6180. #endif
  6181. #ifdef USE_DISPLACEMENTMAP
  6182. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  6183. #endif
  6184. #ifdef USE_EMISSIVEMAP
  6185. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  6186. #endif
  6187. #ifdef USE_METALNESSMAP
  6188. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  6189. #endif
  6190. #ifdef USE_ROUGHNESSMAP
  6191. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  6192. #endif
  6193. #ifdef USE_ANISOTROPYMAP
  6194. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  6195. #endif
  6196. #ifdef USE_CLEARCOATMAP
  6197. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  6198. #endif
  6199. #ifdef USE_CLEARCOAT_NORMALMAP
  6200. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  6201. #endif
  6202. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6203. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  6204. #endif
  6205. #ifdef USE_IRIDESCENCEMAP
  6206. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  6207. #endif
  6208. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6209. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  6210. #endif
  6211. #ifdef USE_SHEEN_COLORMAP
  6212. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  6213. #endif
  6214. #ifdef USE_SHEEN_ROUGHNESSMAP
  6215. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  6216. #endif
  6217. #ifdef USE_SPECULARMAP
  6218. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  6219. #endif
  6220. #ifdef USE_SPECULAR_COLORMAP
  6221. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  6222. #endif
  6223. #ifdef USE_SPECULAR_INTENSITYMAP
  6224. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  6225. #endif
  6226. #ifdef USE_TRANSMISSIONMAP
  6227. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  6228. #endif
  6229. #ifdef USE_THICKNESSMAP
  6230. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  6231. #endif`,EPe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  6232. vec4 worldPosition = vec4( transformed, 1.0 );
  6233. #ifdef USE_BATCHING
  6234. worldPosition = batchingMatrix * worldPosition;
  6235. #endif
  6236. #ifdef USE_INSTANCING
  6237. worldPosition = instanceMatrix * worldPosition;
  6238. #endif
  6239. worldPosition = modelMatrix * worldPosition;
  6240. #endif`;const DPe=`varying vec2 vUv;
  6241. uniform mat3 uvTransform;
  6242. void main() {
  6243. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  6244. gl_Position = vec4( position.xy, 1.0, 1.0 );
  6245. }`,FPe=`uniform sampler2D t2D;
  6246. uniform float backgroundIntensity;
  6247. varying vec2 vUv;
  6248. void main() {
  6249. vec4 texColor = texture2D( t2D, vUv );
  6250. #ifdef DECODE_VIDEO_TEXTURE
  6251. 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 );
  6252. #endif
  6253. texColor.rgb *= backgroundIntensity;
  6254. gl_FragColor = texColor;
  6255. #include <tonemapping_fragment>
  6256. #include <colorspace_fragment>
  6257. }`,RPe=`varying vec3 vWorldDirection;
  6258. #include <common>
  6259. void main() {
  6260. vWorldDirection = transformDirection( position, modelMatrix );
  6261. #include <begin_vertex>
  6262. #include <project_vertex>
  6263. gl_Position.z = gl_Position.w;
  6264. }`,LPe=`#ifdef ENVMAP_TYPE_CUBE
  6265. uniform samplerCube envMap;
  6266. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6267. uniform sampler2D envMap;
  6268. #endif
  6269. uniform float flipEnvMap;
  6270. uniform float backgroundBlurriness;
  6271. uniform float backgroundIntensity;
  6272. varying vec3 vWorldDirection;
  6273. #include <cube_uv_reflection_fragment>
  6274. void main() {
  6275. #ifdef ENVMAP_TYPE_CUBE
  6276. vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  6277. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6278. vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );
  6279. #else
  6280. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  6281. #endif
  6282. texColor.rgb *= backgroundIntensity;
  6283. gl_FragColor = texColor;
  6284. #include <tonemapping_fragment>
  6285. #include <colorspace_fragment>
  6286. }`,OPe=`varying vec3 vWorldDirection;
  6287. #include <common>
  6288. void main() {
  6289. vWorldDirection = transformDirection( position, modelMatrix );
  6290. #include <begin_vertex>
  6291. #include <project_vertex>
  6292. gl_Position.z = gl_Position.w;
  6293. }`,IPe=`uniform samplerCube tCube;
  6294. uniform float tFlip;
  6295. uniform float opacity;
  6296. varying vec3 vWorldDirection;
  6297. void main() {
  6298. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  6299. gl_FragColor = texColor;
  6300. gl_FragColor.a *= opacity;
  6301. #include <tonemapping_fragment>
  6302. #include <colorspace_fragment>
  6303. }`,zPe=`#include <common>
  6304. #include <batching_pars_vertex>
  6305. #include <uv_pars_vertex>
  6306. #include <displacementmap_pars_vertex>
  6307. #include <morphtarget_pars_vertex>
  6308. #include <skinning_pars_vertex>
  6309. #include <logdepthbuf_pars_vertex>
  6310. #include <clipping_planes_pars_vertex>
  6311. varying vec2 vHighPrecisionZW;
  6312. void main() {
  6313. #include <uv_vertex>
  6314. #include <batching_vertex>
  6315. #include <skinbase_vertex>
  6316. #ifdef USE_DISPLACEMENTMAP
  6317. #include <beginnormal_vertex>
  6318. #include <morphnormal_vertex>
  6319. #include <skinnormal_vertex>
  6320. #endif
  6321. #include <begin_vertex>
  6322. #include <morphtarget_vertex>
  6323. #include <skinning_vertex>
  6324. #include <displacementmap_vertex>
  6325. #include <project_vertex>
  6326. #include <logdepthbuf_vertex>
  6327. #include <clipping_planes_vertex>
  6328. vHighPrecisionZW = gl_Position.zw;
  6329. }`,UPe=`#if DEPTH_PACKING == 3200
  6330. uniform float opacity;
  6331. #endif
  6332. #include <common>
  6333. #include <packing>
  6334. #include <uv_pars_fragment>
  6335. #include <map_pars_fragment>
  6336. #include <alphamap_pars_fragment>
  6337. #include <alphatest_pars_fragment>
  6338. #include <alphahash_pars_fragment>
  6339. #include <logdepthbuf_pars_fragment>
  6340. #include <clipping_planes_pars_fragment>
  6341. varying vec2 vHighPrecisionZW;
  6342. void main() {
  6343. #include <clipping_planes_fragment>
  6344. vec4 diffuseColor = vec4( 1.0 );
  6345. #if DEPTH_PACKING == 3200
  6346. diffuseColor.a = opacity;
  6347. #endif
  6348. #include <map_fragment>
  6349. #include <alphamap_fragment>
  6350. #include <alphatest_fragment>
  6351. #include <alphahash_fragment>
  6352. #include <logdepthbuf_fragment>
  6353. float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
  6354. #if DEPTH_PACKING == 3200
  6355. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  6356. #elif DEPTH_PACKING == 3201
  6357. gl_FragColor = packDepthToRGBA( fragCoordZ );
  6358. #endif
  6359. }`,BPe=`#define DISTANCE
  6360. varying vec3 vWorldPosition;
  6361. #include <common>
  6362. #include <batching_pars_vertex>
  6363. #include <uv_pars_vertex>
  6364. #include <displacementmap_pars_vertex>
  6365. #include <morphtarget_pars_vertex>
  6366. #include <skinning_pars_vertex>
  6367. #include <clipping_planes_pars_vertex>
  6368. void main() {
  6369. #include <uv_vertex>
  6370. #include <batching_vertex>
  6371. #include <skinbase_vertex>
  6372. #ifdef USE_DISPLACEMENTMAP
  6373. #include <beginnormal_vertex>
  6374. #include <morphnormal_vertex>
  6375. #include <skinnormal_vertex>
  6376. #endif
  6377. #include <begin_vertex>
  6378. #include <morphtarget_vertex>
  6379. #include <skinning_vertex>
  6380. #include <displacementmap_vertex>
  6381. #include <project_vertex>
  6382. #include <worldpos_vertex>
  6383. #include <clipping_planes_vertex>
  6384. vWorldPosition = worldPosition.xyz;
  6385. }`,HPe=`#define DISTANCE
  6386. uniform vec3 referencePosition;
  6387. uniform float nearDistance;
  6388. uniform float farDistance;
  6389. varying vec3 vWorldPosition;
  6390. #include <common>
  6391. #include <packing>
  6392. #include <uv_pars_fragment>
  6393. #include <map_pars_fragment>
  6394. #include <alphamap_pars_fragment>
  6395. #include <alphatest_pars_fragment>
  6396. #include <alphahash_pars_fragment>
  6397. #include <clipping_planes_pars_fragment>
  6398. void main () {
  6399. #include <clipping_planes_fragment>
  6400. vec4 diffuseColor = vec4( 1.0 );
  6401. #include <map_fragment>
  6402. #include <alphamap_fragment>
  6403. #include <alphatest_fragment>
  6404. #include <alphahash_fragment>
  6405. float dist = length( vWorldPosition - referencePosition );
  6406. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  6407. dist = saturate( dist );
  6408. gl_FragColor = packDepthToRGBA( dist );
  6409. }`,qPe=`varying vec3 vWorldDirection;
  6410. #include <common>
  6411. void main() {
  6412. vWorldDirection = transformDirection( position, modelMatrix );
  6413. #include <begin_vertex>
  6414. #include <project_vertex>
  6415. }`,$Pe=`uniform sampler2D tEquirect;
  6416. varying vec3 vWorldDirection;
  6417. #include <common>
  6418. void main() {
  6419. vec3 direction = normalize( vWorldDirection );
  6420. vec2 sampleUV = equirectUv( direction );
  6421. gl_FragColor = texture2D( tEquirect, sampleUV );
  6422. #include <tonemapping_fragment>
  6423. #include <colorspace_fragment>
  6424. }`,VPe=`uniform float scale;
  6425. attribute float lineDistance;
  6426. varying float vLineDistance;
  6427. #include <common>
  6428. #include <uv_pars_vertex>
  6429. #include <color_pars_vertex>
  6430. #include <fog_pars_vertex>
  6431. #include <morphtarget_pars_vertex>
  6432. #include <logdepthbuf_pars_vertex>
  6433. #include <clipping_planes_pars_vertex>
  6434. void main() {
  6435. vLineDistance = scale * lineDistance;
  6436. #include <uv_vertex>
  6437. #include <color_vertex>
  6438. #include <morphcolor_vertex>
  6439. #include <begin_vertex>
  6440. #include <morphtarget_vertex>
  6441. #include <project_vertex>
  6442. #include <logdepthbuf_vertex>
  6443. #include <clipping_planes_vertex>
  6444. #include <fog_vertex>
  6445. }`,GPe=`uniform vec3 diffuse;
  6446. uniform float opacity;
  6447. uniform float dashSize;
  6448. uniform float totalSize;
  6449. varying float vLineDistance;
  6450. #include <common>
  6451. #include <color_pars_fragment>
  6452. #include <uv_pars_fragment>
  6453. #include <map_pars_fragment>
  6454. #include <fog_pars_fragment>
  6455. #include <logdepthbuf_pars_fragment>
  6456. #include <clipping_planes_pars_fragment>
  6457. void main() {
  6458. #include <clipping_planes_fragment>
  6459. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  6460. discard;
  6461. }
  6462. vec3 outgoingLight = vec3( 0.0 );
  6463. vec4 diffuseColor = vec4( diffuse, opacity );
  6464. #include <logdepthbuf_fragment>
  6465. #include <map_fragment>
  6466. #include <color_fragment>
  6467. outgoingLight = diffuseColor.rgb;
  6468. #include <opaque_fragment>
  6469. #include <tonemapping_fragment>
  6470. #include <colorspace_fragment>
  6471. #include <fog_fragment>
  6472. #include <premultiplied_alpha_fragment>
  6473. }`,WPe=`#include <common>
  6474. #include <batching_pars_vertex>
  6475. #include <uv_pars_vertex>
  6476. #include <envmap_pars_vertex>
  6477. #include <color_pars_vertex>
  6478. #include <fog_pars_vertex>
  6479. #include <morphtarget_pars_vertex>
  6480. #include <skinning_pars_vertex>
  6481. #include <logdepthbuf_pars_vertex>
  6482. #include <clipping_planes_pars_vertex>
  6483. void main() {
  6484. #include <uv_vertex>
  6485. #include <color_vertex>
  6486. #include <morphcolor_vertex>
  6487. #include <batching_vertex>
  6488. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  6489. #include <beginnormal_vertex>
  6490. #include <morphnormal_vertex>
  6491. #include <skinbase_vertex>
  6492. #include <skinnormal_vertex>
  6493. #include <defaultnormal_vertex>
  6494. #endif
  6495. #include <begin_vertex>
  6496. #include <morphtarget_vertex>
  6497. #include <skinning_vertex>
  6498. #include <project_vertex>
  6499. #include <logdepthbuf_vertex>
  6500. #include <clipping_planes_vertex>
  6501. #include <worldpos_vertex>
  6502. #include <envmap_vertex>
  6503. #include <fog_vertex>
  6504. }`,KPe=`uniform vec3 diffuse;
  6505. uniform float opacity;
  6506. #ifndef FLAT_SHADED
  6507. varying vec3 vNormal;
  6508. #endif
  6509. #include <common>
  6510. #include <dithering_pars_fragment>
  6511. #include <color_pars_fragment>
  6512. #include <uv_pars_fragment>
  6513. #include <map_pars_fragment>
  6514. #include <alphamap_pars_fragment>
  6515. #include <alphatest_pars_fragment>
  6516. #include <alphahash_pars_fragment>
  6517. #include <aomap_pars_fragment>
  6518. #include <lightmap_pars_fragment>
  6519. #include <envmap_common_pars_fragment>
  6520. #include <envmap_pars_fragment>
  6521. #include <fog_pars_fragment>
  6522. #include <specularmap_pars_fragment>
  6523. #include <logdepthbuf_pars_fragment>
  6524. #include <clipping_planes_pars_fragment>
  6525. void main() {
  6526. #include <clipping_planes_fragment>
  6527. vec4 diffuseColor = vec4( diffuse, opacity );
  6528. #include <logdepthbuf_fragment>
  6529. #include <map_fragment>
  6530. #include <color_fragment>
  6531. #include <alphamap_fragment>
  6532. #include <alphatest_fragment>
  6533. #include <alphahash_fragment>
  6534. #include <specularmap_fragment>
  6535. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6536. #ifdef USE_LIGHTMAP
  6537. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  6538. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  6539. #else
  6540. reflectedLight.indirectDiffuse += vec3( 1.0 );
  6541. #endif
  6542. #include <aomap_fragment>
  6543. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  6544. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  6545. #include <envmap_fragment>
  6546. #include <opaque_fragment>
  6547. #include <tonemapping_fragment>
  6548. #include <colorspace_fragment>
  6549. #include <fog_fragment>
  6550. #include <premultiplied_alpha_fragment>
  6551. #include <dithering_fragment>
  6552. }`,YPe=`#define LAMBERT
  6553. varying vec3 vViewPosition;
  6554. #include <common>
  6555. #include <batching_pars_vertex>
  6556. #include <uv_pars_vertex>
  6557. #include <displacementmap_pars_vertex>
  6558. #include <envmap_pars_vertex>
  6559. #include <color_pars_vertex>
  6560. #include <fog_pars_vertex>
  6561. #include <normal_pars_vertex>
  6562. #include <morphtarget_pars_vertex>
  6563. #include <skinning_pars_vertex>
  6564. #include <shadowmap_pars_vertex>
  6565. #include <logdepthbuf_pars_vertex>
  6566. #include <clipping_planes_pars_vertex>
  6567. void main() {
  6568. #include <uv_vertex>
  6569. #include <color_vertex>
  6570. #include <morphcolor_vertex>
  6571. #include <batching_vertex>
  6572. #include <beginnormal_vertex>
  6573. #include <morphnormal_vertex>
  6574. #include <skinbase_vertex>
  6575. #include <skinnormal_vertex>
  6576. #include <defaultnormal_vertex>
  6577. #include <normal_vertex>
  6578. #include <begin_vertex>
  6579. #include <morphtarget_vertex>
  6580. #include <skinning_vertex>
  6581. #include <displacementmap_vertex>
  6582. #include <project_vertex>
  6583. #include <logdepthbuf_vertex>
  6584. #include <clipping_planes_vertex>
  6585. vViewPosition = - mvPosition.xyz;
  6586. #include <worldpos_vertex>
  6587. #include <envmap_vertex>
  6588. #include <shadowmap_vertex>
  6589. #include <fog_vertex>
  6590. }`,XPe=`#define LAMBERT
  6591. uniform vec3 diffuse;
  6592. uniform vec3 emissive;
  6593. uniform float opacity;
  6594. #include <common>
  6595. #include <packing>
  6596. #include <dithering_pars_fragment>
  6597. #include <color_pars_fragment>
  6598. #include <uv_pars_fragment>
  6599. #include <map_pars_fragment>
  6600. #include <alphamap_pars_fragment>
  6601. #include <alphatest_pars_fragment>
  6602. #include <alphahash_pars_fragment>
  6603. #include <aomap_pars_fragment>
  6604. #include <lightmap_pars_fragment>
  6605. #include <emissivemap_pars_fragment>
  6606. #include <envmap_common_pars_fragment>
  6607. #include <envmap_pars_fragment>
  6608. #include <fog_pars_fragment>
  6609. #include <bsdfs>
  6610. #include <lights_pars_begin>
  6611. #include <normal_pars_fragment>
  6612. #include <lights_lambert_pars_fragment>
  6613. #include <shadowmap_pars_fragment>
  6614. #include <bumpmap_pars_fragment>
  6615. #include <normalmap_pars_fragment>
  6616. #include <specularmap_pars_fragment>
  6617. #include <logdepthbuf_pars_fragment>
  6618. #include <clipping_planes_pars_fragment>
  6619. void main() {
  6620. #include <clipping_planes_fragment>
  6621. vec4 diffuseColor = vec4( diffuse, opacity );
  6622. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6623. vec3 totalEmissiveRadiance = emissive;
  6624. #include <logdepthbuf_fragment>
  6625. #include <map_fragment>
  6626. #include <color_fragment>
  6627. #include <alphamap_fragment>
  6628. #include <alphatest_fragment>
  6629. #include <alphahash_fragment>
  6630. #include <specularmap_fragment>
  6631. #include <normal_fragment_begin>
  6632. #include <normal_fragment_maps>
  6633. #include <emissivemap_fragment>
  6634. #include <lights_lambert_fragment>
  6635. #include <lights_fragment_begin>
  6636. #include <lights_fragment_maps>
  6637. #include <lights_fragment_end>
  6638. #include <aomap_fragment>
  6639. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  6640. #include <envmap_fragment>
  6641. #include <opaque_fragment>
  6642. #include <tonemapping_fragment>
  6643. #include <colorspace_fragment>
  6644. #include <fog_fragment>
  6645. #include <premultiplied_alpha_fragment>
  6646. #include <dithering_fragment>
  6647. }`,QPe=`#define MATCAP
  6648. varying vec3 vViewPosition;
  6649. #include <common>
  6650. #include <batching_pars_vertex>
  6651. #include <uv_pars_vertex>
  6652. #include <color_pars_vertex>
  6653. #include <displacementmap_pars_vertex>
  6654. #include <fog_pars_vertex>
  6655. #include <normal_pars_vertex>
  6656. #include <morphtarget_pars_vertex>
  6657. #include <skinning_pars_vertex>
  6658. #include <logdepthbuf_pars_vertex>
  6659. #include <clipping_planes_pars_vertex>
  6660. void main() {
  6661. #include <uv_vertex>
  6662. #include <color_vertex>
  6663. #include <morphcolor_vertex>
  6664. #include <batching_vertex>
  6665. #include <beginnormal_vertex>
  6666. #include <morphnormal_vertex>
  6667. #include <skinbase_vertex>
  6668. #include <skinnormal_vertex>
  6669. #include <defaultnormal_vertex>
  6670. #include <normal_vertex>
  6671. #include <begin_vertex>
  6672. #include <morphtarget_vertex>
  6673. #include <skinning_vertex>
  6674. #include <displacementmap_vertex>
  6675. #include <project_vertex>
  6676. #include <logdepthbuf_vertex>
  6677. #include <clipping_planes_vertex>
  6678. #include <fog_vertex>
  6679. vViewPosition = - mvPosition.xyz;
  6680. }`,ZPe=`#define MATCAP
  6681. uniform vec3 diffuse;
  6682. uniform float opacity;
  6683. uniform sampler2D matcap;
  6684. varying vec3 vViewPosition;
  6685. #include <common>
  6686. #include <dithering_pars_fragment>
  6687. #include <color_pars_fragment>
  6688. #include <uv_pars_fragment>
  6689. #include <map_pars_fragment>
  6690. #include <alphamap_pars_fragment>
  6691. #include <alphatest_pars_fragment>
  6692. #include <alphahash_pars_fragment>
  6693. #include <fog_pars_fragment>
  6694. #include <normal_pars_fragment>
  6695. #include <bumpmap_pars_fragment>
  6696. #include <normalmap_pars_fragment>
  6697. #include <logdepthbuf_pars_fragment>
  6698. #include <clipping_planes_pars_fragment>
  6699. void main() {
  6700. #include <clipping_planes_fragment>
  6701. vec4 diffuseColor = vec4( diffuse, opacity );
  6702. #include <logdepthbuf_fragment>
  6703. #include <map_fragment>
  6704. #include <color_fragment>
  6705. #include <alphamap_fragment>
  6706. #include <alphatest_fragment>
  6707. #include <alphahash_fragment>
  6708. #include <normal_fragment_begin>
  6709. #include <normal_fragment_maps>
  6710. vec3 viewDir = normalize( vViewPosition );
  6711. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  6712. vec3 y = cross( viewDir, x );
  6713. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  6714. #ifdef USE_MATCAP
  6715. vec4 matcapColor = texture2D( matcap, uv );
  6716. #else
  6717. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  6718. #endif
  6719. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  6720. #include <opaque_fragment>
  6721. #include <tonemapping_fragment>
  6722. #include <colorspace_fragment>
  6723. #include <fog_fragment>
  6724. #include <premultiplied_alpha_fragment>
  6725. #include <dithering_fragment>
  6726. }`,JPe=`#define NORMAL
  6727. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6728. varying vec3 vViewPosition;
  6729. #endif
  6730. #include <common>
  6731. #include <batching_pars_vertex>
  6732. #include <uv_pars_vertex>
  6733. #include <displacementmap_pars_vertex>
  6734. #include <normal_pars_vertex>
  6735. #include <morphtarget_pars_vertex>
  6736. #include <skinning_pars_vertex>
  6737. #include <logdepthbuf_pars_vertex>
  6738. #include <clipping_planes_pars_vertex>
  6739. void main() {
  6740. #include <uv_vertex>
  6741. #include <batching_vertex>
  6742. #include <beginnormal_vertex>
  6743. #include <morphnormal_vertex>
  6744. #include <skinbase_vertex>
  6745. #include <skinnormal_vertex>
  6746. #include <defaultnormal_vertex>
  6747. #include <normal_vertex>
  6748. #include <begin_vertex>
  6749. #include <morphtarget_vertex>
  6750. #include <skinning_vertex>
  6751. #include <displacementmap_vertex>
  6752. #include <project_vertex>
  6753. #include <logdepthbuf_vertex>
  6754. #include <clipping_planes_vertex>
  6755. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6756. vViewPosition = - mvPosition.xyz;
  6757. #endif
  6758. }`,eTe=`#define NORMAL
  6759. uniform float opacity;
  6760. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6761. varying vec3 vViewPosition;
  6762. #endif
  6763. #include <packing>
  6764. #include <uv_pars_fragment>
  6765. #include <normal_pars_fragment>
  6766. #include <bumpmap_pars_fragment>
  6767. #include <normalmap_pars_fragment>
  6768. #include <logdepthbuf_pars_fragment>
  6769. #include <clipping_planes_pars_fragment>
  6770. void main() {
  6771. #include <clipping_planes_fragment>
  6772. #include <logdepthbuf_fragment>
  6773. #include <normal_fragment_begin>
  6774. #include <normal_fragment_maps>
  6775. gl_FragColor = vec4( packNormalToRGB( normal ), opacity );
  6776. #ifdef OPAQUE
  6777. gl_FragColor.a = 1.0;
  6778. #endif
  6779. }`,tTe=`#define PHONG
  6780. varying vec3 vViewPosition;
  6781. #include <common>
  6782. #include <batching_pars_vertex>
  6783. #include <uv_pars_vertex>
  6784. #include <displacementmap_pars_vertex>
  6785. #include <envmap_pars_vertex>
  6786. #include <color_pars_vertex>
  6787. #include <fog_pars_vertex>
  6788. #include <normal_pars_vertex>
  6789. #include <morphtarget_pars_vertex>
  6790. #include <skinning_pars_vertex>
  6791. #include <shadowmap_pars_vertex>
  6792. #include <logdepthbuf_pars_vertex>
  6793. #include <clipping_planes_pars_vertex>
  6794. void main() {
  6795. #include <uv_vertex>
  6796. #include <color_vertex>
  6797. #include <morphcolor_vertex>
  6798. #include <batching_vertex>
  6799. #include <beginnormal_vertex>
  6800. #include <morphnormal_vertex>
  6801. #include <skinbase_vertex>
  6802. #include <skinnormal_vertex>
  6803. #include <defaultnormal_vertex>
  6804. #include <normal_vertex>
  6805. #include <begin_vertex>
  6806. #include <morphtarget_vertex>
  6807. #include <skinning_vertex>
  6808. #include <displacementmap_vertex>
  6809. #include <project_vertex>
  6810. #include <logdepthbuf_vertex>
  6811. #include <clipping_planes_vertex>
  6812. vViewPosition = - mvPosition.xyz;
  6813. #include <worldpos_vertex>
  6814. #include <envmap_vertex>
  6815. #include <shadowmap_vertex>
  6816. #include <fog_vertex>
  6817. }`,nTe=`#define PHONG
  6818. uniform vec3 diffuse;
  6819. uniform vec3 emissive;
  6820. uniform vec3 specular;
  6821. uniform float shininess;
  6822. uniform float opacity;
  6823. #include <common>
  6824. #include <packing>
  6825. #include <dithering_pars_fragment>
  6826. #include <color_pars_fragment>
  6827. #include <uv_pars_fragment>
  6828. #include <map_pars_fragment>
  6829. #include <alphamap_pars_fragment>
  6830. #include <alphatest_pars_fragment>
  6831. #include <alphahash_pars_fragment>
  6832. #include <aomap_pars_fragment>
  6833. #include <lightmap_pars_fragment>
  6834. #include <emissivemap_pars_fragment>
  6835. #include <envmap_common_pars_fragment>
  6836. #include <envmap_pars_fragment>
  6837. #include <fog_pars_fragment>
  6838. #include <bsdfs>
  6839. #include <lights_pars_begin>
  6840. #include <normal_pars_fragment>
  6841. #include <lights_phong_pars_fragment>
  6842. #include <shadowmap_pars_fragment>
  6843. #include <bumpmap_pars_fragment>
  6844. #include <normalmap_pars_fragment>
  6845. #include <specularmap_pars_fragment>
  6846. #include <logdepthbuf_pars_fragment>
  6847. #include <clipping_planes_pars_fragment>
  6848. void main() {
  6849. #include <clipping_planes_fragment>
  6850. vec4 diffuseColor = vec4( diffuse, opacity );
  6851. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6852. vec3 totalEmissiveRadiance = emissive;
  6853. #include <logdepthbuf_fragment>
  6854. #include <map_fragment>
  6855. #include <color_fragment>
  6856. #include <alphamap_fragment>
  6857. #include <alphatest_fragment>
  6858. #include <alphahash_fragment>
  6859. #include <specularmap_fragment>
  6860. #include <normal_fragment_begin>
  6861. #include <normal_fragment_maps>
  6862. #include <emissivemap_fragment>
  6863. #include <lights_phong_fragment>
  6864. #include <lights_fragment_begin>
  6865. #include <lights_fragment_maps>
  6866. #include <lights_fragment_end>
  6867. #include <aomap_fragment>
  6868. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  6869. #include <envmap_fragment>
  6870. #include <opaque_fragment>
  6871. #include <tonemapping_fragment>
  6872. #include <colorspace_fragment>
  6873. #include <fog_fragment>
  6874. #include <premultiplied_alpha_fragment>
  6875. #include <dithering_fragment>
  6876. }`,rTe=`#define STANDARD
  6877. varying vec3 vViewPosition;
  6878. #ifdef USE_TRANSMISSION
  6879. varying vec3 vWorldPosition;
  6880. #endif
  6881. #include <common>
  6882. #include <batching_pars_vertex>
  6883. #include <uv_pars_vertex>
  6884. #include <displacementmap_pars_vertex>
  6885. #include <color_pars_vertex>
  6886. #include <fog_pars_vertex>
  6887. #include <normal_pars_vertex>
  6888. #include <morphtarget_pars_vertex>
  6889. #include <skinning_pars_vertex>
  6890. #include <shadowmap_pars_vertex>
  6891. #include <logdepthbuf_pars_vertex>
  6892. #include <clipping_planes_pars_vertex>
  6893. void main() {
  6894. #include <uv_vertex>
  6895. #include <color_vertex>
  6896. #include <morphcolor_vertex>
  6897. #include <batching_vertex>
  6898. #include <beginnormal_vertex>
  6899. #include <morphnormal_vertex>
  6900. #include <skinbase_vertex>
  6901. #include <skinnormal_vertex>
  6902. #include <defaultnormal_vertex>
  6903. #include <normal_vertex>
  6904. #include <begin_vertex>
  6905. #include <morphtarget_vertex>
  6906. #include <skinning_vertex>
  6907. #include <displacementmap_vertex>
  6908. #include <project_vertex>
  6909. #include <logdepthbuf_vertex>
  6910. #include <clipping_planes_vertex>
  6911. vViewPosition = - mvPosition.xyz;
  6912. #include <worldpos_vertex>
  6913. #include <shadowmap_vertex>
  6914. #include <fog_vertex>
  6915. #ifdef USE_TRANSMISSION
  6916. vWorldPosition = worldPosition.xyz;
  6917. #endif
  6918. }`,aTe=`#define STANDARD
  6919. #ifdef PHYSICAL
  6920. #define IOR
  6921. #define USE_SPECULAR
  6922. #endif
  6923. uniform vec3 diffuse;
  6924. uniform vec3 emissive;
  6925. uniform float roughness;
  6926. uniform float metalness;
  6927. uniform float opacity;
  6928. #ifdef IOR
  6929. uniform float ior;
  6930. #endif
  6931. #ifdef USE_SPECULAR
  6932. uniform float specularIntensity;
  6933. uniform vec3 specularColor;
  6934. #ifdef USE_SPECULAR_COLORMAP
  6935. uniform sampler2D specularColorMap;
  6936. #endif
  6937. #ifdef USE_SPECULAR_INTENSITYMAP
  6938. uniform sampler2D specularIntensityMap;
  6939. #endif
  6940. #endif
  6941. #ifdef USE_CLEARCOAT
  6942. uniform float clearcoat;
  6943. uniform float clearcoatRoughness;
  6944. #endif
  6945. #ifdef USE_IRIDESCENCE
  6946. uniform float iridescence;
  6947. uniform float iridescenceIOR;
  6948. uniform float iridescenceThicknessMinimum;
  6949. uniform float iridescenceThicknessMaximum;
  6950. #endif
  6951. #ifdef USE_SHEEN
  6952. uniform vec3 sheenColor;
  6953. uniform float sheenRoughness;
  6954. #ifdef USE_SHEEN_COLORMAP
  6955. uniform sampler2D sheenColorMap;
  6956. #endif
  6957. #ifdef USE_SHEEN_ROUGHNESSMAP
  6958. uniform sampler2D sheenRoughnessMap;
  6959. #endif
  6960. #endif
  6961. #ifdef USE_ANISOTROPY
  6962. uniform vec2 anisotropyVector;
  6963. #ifdef USE_ANISOTROPYMAP
  6964. uniform sampler2D anisotropyMap;
  6965. #endif
  6966. #endif
  6967. varying vec3 vViewPosition;
  6968. #include <common>
  6969. #include <packing>
  6970. #include <dithering_pars_fragment>
  6971. #include <color_pars_fragment>
  6972. #include <uv_pars_fragment>
  6973. #include <map_pars_fragment>
  6974. #include <alphamap_pars_fragment>
  6975. #include <alphatest_pars_fragment>
  6976. #include <alphahash_pars_fragment>
  6977. #include <aomap_pars_fragment>
  6978. #include <lightmap_pars_fragment>
  6979. #include <emissivemap_pars_fragment>
  6980. #include <iridescence_fragment>
  6981. #include <cube_uv_reflection_fragment>
  6982. #include <envmap_common_pars_fragment>
  6983. #include <envmap_physical_pars_fragment>
  6984. #include <fog_pars_fragment>
  6985. #include <lights_pars_begin>
  6986. #include <normal_pars_fragment>
  6987. #include <lights_physical_pars_fragment>
  6988. #include <transmission_pars_fragment>
  6989. #include <shadowmap_pars_fragment>
  6990. #include <bumpmap_pars_fragment>
  6991. #include <normalmap_pars_fragment>
  6992. #include <clearcoat_pars_fragment>
  6993. #include <iridescence_pars_fragment>
  6994. #include <roughnessmap_pars_fragment>
  6995. #include <metalnessmap_pars_fragment>
  6996. #include <logdepthbuf_pars_fragment>
  6997. #include <clipping_planes_pars_fragment>
  6998. void main() {
  6999. #include <clipping_planes_fragment>
  7000. vec4 diffuseColor = vec4( diffuse, opacity );
  7001. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  7002. vec3 totalEmissiveRadiance = emissive;
  7003. #include <logdepthbuf_fragment>
  7004. #include <map_fragment>
  7005. #include <color_fragment>
  7006. #include <alphamap_fragment>
  7007. #include <alphatest_fragment>
  7008. #include <alphahash_fragment>
  7009. #include <roughnessmap_fragment>
  7010. #include <metalnessmap_fragment>
  7011. #include <normal_fragment_begin>
  7012. #include <normal_fragment_maps>
  7013. #include <clearcoat_normal_fragment_begin>
  7014. #include <clearcoat_normal_fragment_maps>
  7015. #include <emissivemap_fragment>
  7016. #include <lights_physical_fragment>
  7017. #include <lights_fragment_begin>
  7018. #include <lights_fragment_maps>
  7019. #include <lights_fragment_end>
  7020. #include <aomap_fragment>
  7021. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  7022. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  7023. #include <transmission_fragment>
  7024. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  7025. #ifdef USE_SHEEN
  7026. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  7027. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  7028. #endif
  7029. #ifdef USE_CLEARCOAT
  7030. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  7031. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  7032. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  7033. #endif
  7034. #include <opaque_fragment>
  7035. #include <tonemapping_fragment>
  7036. #include <colorspace_fragment>
  7037. #include <fog_fragment>
  7038. #include <premultiplied_alpha_fragment>
  7039. #include <dithering_fragment>
  7040. }`,iTe=`#define TOON
  7041. varying vec3 vViewPosition;
  7042. #include <common>
  7043. #include <batching_pars_vertex>
  7044. #include <uv_pars_vertex>
  7045. #include <displacementmap_pars_vertex>
  7046. #include <color_pars_vertex>
  7047. #include <fog_pars_vertex>
  7048. #include <normal_pars_vertex>
  7049. #include <morphtarget_pars_vertex>
  7050. #include <skinning_pars_vertex>
  7051. #include <shadowmap_pars_vertex>
  7052. #include <logdepthbuf_pars_vertex>
  7053. #include <clipping_planes_pars_vertex>
  7054. void main() {
  7055. #include <uv_vertex>
  7056. #include <color_vertex>
  7057. #include <morphcolor_vertex>
  7058. #include <batching_vertex>
  7059. #include <beginnormal_vertex>
  7060. #include <morphnormal_vertex>
  7061. #include <skinbase_vertex>
  7062. #include <skinnormal_vertex>
  7063. #include <defaultnormal_vertex>
  7064. #include <normal_vertex>
  7065. #include <begin_vertex>
  7066. #include <morphtarget_vertex>
  7067. #include <skinning_vertex>
  7068. #include <displacementmap_vertex>
  7069. #include <project_vertex>
  7070. #include <logdepthbuf_vertex>
  7071. #include <clipping_planes_vertex>
  7072. vViewPosition = - mvPosition.xyz;
  7073. #include <worldpos_vertex>
  7074. #include <shadowmap_vertex>
  7075. #include <fog_vertex>
  7076. }`,sTe=`#define TOON
  7077. uniform vec3 diffuse;
  7078. uniform vec3 emissive;
  7079. uniform float opacity;
  7080. #include <common>
  7081. #include <packing>
  7082. #include <dithering_pars_fragment>
  7083. #include <color_pars_fragment>
  7084. #include <uv_pars_fragment>
  7085. #include <map_pars_fragment>
  7086. #include <alphamap_pars_fragment>
  7087. #include <alphatest_pars_fragment>
  7088. #include <alphahash_pars_fragment>
  7089. #include <aomap_pars_fragment>
  7090. #include <lightmap_pars_fragment>
  7091. #include <emissivemap_pars_fragment>
  7092. #include <gradientmap_pars_fragment>
  7093. #include <fog_pars_fragment>
  7094. #include <bsdfs>
  7095. #include <lights_pars_begin>
  7096. #include <normal_pars_fragment>
  7097. #include <lights_toon_pars_fragment>
  7098. #include <shadowmap_pars_fragment>
  7099. #include <bumpmap_pars_fragment>
  7100. #include <normalmap_pars_fragment>
  7101. #include <logdepthbuf_pars_fragment>
  7102. #include <clipping_planes_pars_fragment>
  7103. void main() {
  7104. #include <clipping_planes_fragment>
  7105. vec4 diffuseColor = vec4( diffuse, opacity );
  7106. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  7107. vec3 totalEmissiveRadiance = emissive;
  7108. #include <logdepthbuf_fragment>
  7109. #include <map_fragment>
  7110. #include <color_fragment>
  7111. #include <alphamap_fragment>
  7112. #include <alphatest_fragment>
  7113. #include <alphahash_fragment>
  7114. #include <normal_fragment_begin>
  7115. #include <normal_fragment_maps>
  7116. #include <emissivemap_fragment>
  7117. #include <lights_toon_fragment>
  7118. #include <lights_fragment_begin>
  7119. #include <lights_fragment_maps>
  7120. #include <lights_fragment_end>
  7121. #include <aomap_fragment>
  7122. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  7123. #include <opaque_fragment>
  7124. #include <tonemapping_fragment>
  7125. #include <colorspace_fragment>
  7126. #include <fog_fragment>
  7127. #include <premultiplied_alpha_fragment>
  7128. #include <dithering_fragment>
  7129. }`,oTe=`uniform float size;
  7130. uniform float scale;
  7131. #include <common>
  7132. #include <color_pars_vertex>
  7133. #include <fog_pars_vertex>
  7134. #include <morphtarget_pars_vertex>
  7135. #include <logdepthbuf_pars_vertex>
  7136. #include <clipping_planes_pars_vertex>
  7137. #ifdef USE_POINTS_UV
  7138. varying vec2 vUv;
  7139. uniform mat3 uvTransform;
  7140. #endif
  7141. void main() {
  7142. #ifdef USE_POINTS_UV
  7143. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  7144. #endif
  7145. #include <color_vertex>
  7146. #include <morphcolor_vertex>
  7147. #include <begin_vertex>
  7148. #include <morphtarget_vertex>
  7149. #include <project_vertex>
  7150. gl_PointSize = size;
  7151. #ifdef USE_SIZEATTENUATION
  7152. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7153. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  7154. #endif
  7155. #include <logdepthbuf_vertex>
  7156. #include <clipping_planes_vertex>
  7157. #include <worldpos_vertex>
  7158. #include <fog_vertex>
  7159. }`,lTe=`uniform vec3 diffuse;
  7160. uniform float opacity;
  7161. #include <common>
  7162. #include <color_pars_fragment>
  7163. #include <map_particle_pars_fragment>
  7164. #include <alphatest_pars_fragment>
  7165. #include <alphahash_pars_fragment>
  7166. #include <fog_pars_fragment>
  7167. #include <logdepthbuf_pars_fragment>
  7168. #include <clipping_planes_pars_fragment>
  7169. void main() {
  7170. #include <clipping_planes_fragment>
  7171. vec3 outgoingLight = vec3( 0.0 );
  7172. vec4 diffuseColor = vec4( diffuse, opacity );
  7173. #include <logdepthbuf_fragment>
  7174. #include <map_particle_fragment>
  7175. #include <color_fragment>
  7176. #include <alphatest_fragment>
  7177. #include <alphahash_fragment>
  7178. outgoingLight = diffuseColor.rgb;
  7179. #include <opaque_fragment>
  7180. #include <tonemapping_fragment>
  7181. #include <colorspace_fragment>
  7182. #include <fog_fragment>
  7183. #include <premultiplied_alpha_fragment>
  7184. }`,cTe=`#include <common>
  7185. #include <batching_pars_vertex>
  7186. #include <fog_pars_vertex>
  7187. #include <morphtarget_pars_vertex>
  7188. #include <skinning_pars_vertex>
  7189. #include <logdepthbuf_pars_vertex>
  7190. #include <shadowmap_pars_vertex>
  7191. void main() {
  7192. #include <batching_vertex>
  7193. #include <beginnormal_vertex>
  7194. #include <morphnormal_vertex>
  7195. #include <skinbase_vertex>
  7196. #include <skinnormal_vertex>
  7197. #include <defaultnormal_vertex>
  7198. #include <begin_vertex>
  7199. #include <morphtarget_vertex>
  7200. #include <skinning_vertex>
  7201. #include <project_vertex>
  7202. #include <logdepthbuf_vertex>
  7203. #include <worldpos_vertex>
  7204. #include <shadowmap_vertex>
  7205. #include <fog_vertex>
  7206. }`,dTe=`uniform vec3 color;
  7207. uniform float opacity;
  7208. #include <common>
  7209. #include <packing>
  7210. #include <fog_pars_fragment>
  7211. #include <bsdfs>
  7212. #include <lights_pars_begin>
  7213. #include <logdepthbuf_pars_fragment>
  7214. #include <shadowmap_pars_fragment>
  7215. #include <shadowmask_pars_fragment>
  7216. void main() {
  7217. #include <logdepthbuf_fragment>
  7218. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  7219. #include <tonemapping_fragment>
  7220. #include <colorspace_fragment>
  7221. #include <fog_fragment>
  7222. }`,uTe=`uniform float rotation;
  7223. uniform vec2 center;
  7224. #include <common>
  7225. #include <uv_pars_vertex>
  7226. #include <fog_pars_vertex>
  7227. #include <logdepthbuf_pars_vertex>
  7228. #include <clipping_planes_pars_vertex>
  7229. void main() {
  7230. #include <uv_vertex>
  7231. vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
  7232. vec2 scale;
  7233. scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
  7234. scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
  7235. #ifndef USE_SIZEATTENUATION
  7236. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7237. if ( isPerspective ) scale *= - mvPosition.z;
  7238. #endif
  7239. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  7240. vec2 rotatedPosition;
  7241. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  7242. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  7243. mvPosition.xy += rotatedPosition;
  7244. gl_Position = projectionMatrix * mvPosition;
  7245. #include <logdepthbuf_vertex>
  7246. #include <clipping_planes_vertex>
  7247. #include <fog_vertex>
  7248. }`,mTe=`uniform vec3 diffuse;
  7249. uniform float opacity;
  7250. #include <common>
  7251. #include <uv_pars_fragment>
  7252. #include <map_pars_fragment>
  7253. #include <alphamap_pars_fragment>
  7254. #include <alphatest_pars_fragment>
  7255. #include <alphahash_pars_fragment>
  7256. #include <fog_pars_fragment>
  7257. #include <logdepthbuf_pars_fragment>
  7258. #include <clipping_planes_pars_fragment>
  7259. void main() {
  7260. #include <clipping_planes_fragment>
  7261. vec3 outgoingLight = vec3( 0.0 );
  7262. vec4 diffuseColor = vec4( diffuse, opacity );
  7263. #include <logdepthbuf_fragment>
  7264. #include <map_fragment>
  7265. #include <alphamap_fragment>
  7266. #include <alphatest_fragment>
  7267. #include <alphahash_fragment>
  7268. outgoingLight = diffuseColor.rgb;
  7269. #include <opaque_fragment>
  7270. #include <tonemapping_fragment>
  7271. #include <colorspace_fragment>
  7272. #include <fog_fragment>
  7273. }`,er={alphahash_fragment:FNe,alphahash_pars_fragment:RNe,alphamap_fragment:LNe,alphamap_pars_fragment:ONe,alphatest_fragment:INe,alphatest_pars_fragment:zNe,aomap_fragment:UNe,aomap_pars_fragment:BNe,batching_pars_vertex:HNe,batching_vertex:qNe,begin_vertex:$Ne,beginnormal_vertex:VNe,bsdfs:GNe,iridescence_fragment:WNe,bumpmap_pars_fragment:KNe,clipping_planes_fragment:YNe,clipping_planes_pars_fragment:XNe,clipping_planes_pars_vertex:QNe,clipping_planes_vertex:ZNe,color_fragment:JNe,color_pars_fragment:eCe,color_pars_vertex:tCe,color_vertex:nCe,common:rCe,cube_uv_reflection_fragment:aCe,defaultnormal_vertex:iCe,displacementmap_pars_vertex:sCe,displacementmap_vertex:oCe,emissivemap_fragment:lCe,emissivemap_pars_fragment:cCe,colorspace_fragment:dCe,colorspace_pars_fragment:uCe,envmap_fragment:mCe,envmap_common_pars_fragment:hCe,envmap_pars_fragment:pCe,envmap_pars_vertex:fCe,envmap_physical_pars_fragment:PCe,envmap_vertex:gCe,fog_vertex:bCe,fog_pars_vertex:xCe,fog_fragment:yCe,fog_pars_fragment:vCe,gradientmap_pars_fragment:wCe,lightmap_fragment:SCe,lightmap_pars_fragment:_Ce,lights_lambert_fragment:kCe,lights_lambert_pars_fragment:NCe,lights_pars_begin:CCe,lights_toon_fragment:TCe,lights_toon_pars_fragment:ACe,lights_phong_fragment:MCe,lights_phong_pars_fragment:jCe,lights_physical_fragment:ECe,lights_physical_pars_fragment:DCe,lights_fragment_begin:FCe,lights_fragment_maps:RCe,lights_fragment_end:LCe,logdepthbuf_fragment:OCe,logdepthbuf_pars_fragment:ICe,logdepthbuf_pars_vertex:zCe,logdepthbuf_vertex:UCe,map_fragment:BCe,map_pars_fragment:HCe,map_particle_fragment:qCe,map_particle_pars_fragment:$Ce,metalnessmap_fragment:VCe,metalnessmap_pars_fragment:GCe,morphcolor_vertex:WCe,morphnormal_vertex:KCe,morphtarget_pars_vertex:YCe,morphtarget_vertex:XCe,normal_fragment_begin:QCe,normal_fragment_maps:ZCe,normal_pars_fragment:JCe,normal_pars_vertex:ePe,normal_vertex:tPe,normalmap_pars_fragment:nPe,clearcoat_normal_fragment_begin:rPe,clearcoat_normal_fragment_maps:aPe,clearcoat_pars_fragment:iPe,iridescence_pars_fragment:sPe,opaque_fragment:oPe,packing:lPe,premultiplied_alpha_fragment:cPe,project_vertex:dPe,dithering_fragment:uPe,dithering_pars_fragment:mPe,roughnessmap_fragment:hPe,roughnessmap_pars_fragment:pPe,shadowmap_pars_fragment:fPe,shadowmap_pars_vertex:gPe,shadowmap_vertex:bPe,shadowmask_pars_fragment:xPe,skinbase_vertex:yPe,skinning_pars_vertex:vPe,skinning_vertex:wPe,skinnormal_vertex:SPe,specularmap_fragment:_Pe,specularmap_pars_fragment:kPe,tonemapping_fragment:NPe,tonemapping_pars_fragment:CPe,transmission_fragment:PPe,transmission_pars_fragment:TPe,uv_pars_fragment:APe,uv_pars_vertex:MPe,uv_vertex:jPe,worldpos_vertex:EPe,background_vert:DPe,background_frag:FPe,backgroundCube_vert:RPe,backgroundCube_frag:LPe,cube_vert:OPe,cube_frag:IPe,depth_vert:zPe,depth_frag:UPe,distanceRGBA_vert:BPe,distanceRGBA_frag:HPe,equirect_vert:qPe,equirect_frag:$Pe,linedashed_vert:VPe,linedashed_frag:GPe,meshbasic_vert:WPe,meshbasic_frag:KPe,meshlambert_vert:YPe,meshlambert_frag:XPe,meshmatcap_vert:QPe,meshmatcap_frag:ZPe,meshnormal_vert:JPe,meshnormal_frag:eTe,meshphong_vert:tTe,meshphong_frag:nTe,meshphysical_vert:rTe,meshphysical_frag:aTe,meshtoon_vert:iTe,meshtoon_frag:sTe,points_vert:oTe,points_frag:lTe,shadow_vert:cTe,shadow_frag:dTe,sprite_vert:uTe,sprite_frag:mTe},Yt={common:{diffuse:{value:new An(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},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},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 Hn(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 An(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 An(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 An(16777215)},opacity:{value:1},center:{value:new Hn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new lr},alphaMap:{value:null},alphaMapTransform:{value:new lr},alphaTest:{value:0}}},wo={basic:{uniforms:Gs([Yt.common,Yt.specularmap,Yt.envmap,Yt.aomap,Yt.lightmap,Yt.fog]),vertexShader:er.meshbasic_vert,fragmentShader:er.meshbasic_frag},lambert:{uniforms:Gs([Yt.common,Yt.specularmap,Yt.envmap,Yt.aomap,Yt.lightmap,Yt.emissivemap,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,Yt.fog,Yt.lights,{emissive:{value:new An(0)}}]),vertexShader:er.meshlambert_vert,fragmentShader:er.meshlambert_frag},phong:{uniforms:Gs([Yt.common,Yt.specularmap,Yt.envmap,Yt.aomap,Yt.lightmap,Yt.emissivemap,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,Yt.fog,Yt.lights,{emissive:{value:new An(0)},specular:{value:new An(1118481)},shininess:{value:30}}]),vertexShader:er.meshphong_vert,fragmentShader:er.meshphong_frag},standard:{uniforms:Gs([Yt.common,Yt.envmap,Yt.aomap,Yt.lightmap,Yt.emissivemap,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,Yt.roughnessmap,Yt.metalnessmap,Yt.fog,Yt.lights,{emissive:{value:new An(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:er.meshphysical_vert,fragmentShader:er.meshphysical_frag},toon:{uniforms:Gs([Yt.common,Yt.aomap,Yt.lightmap,Yt.emissivemap,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,Yt.gradientmap,Yt.fog,Yt.lights,{emissive:{value:new An(0)}}]),vertexShader:er.meshtoon_vert,fragmentShader:er.meshtoon_frag},matcap:{uniforms:Gs([Yt.common,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,Yt.fog,{matcap:{value:null}}]),vertexShader:er.meshmatcap_vert,fragmentShader:er.meshmatcap_frag},points:{uniforms:Gs([Yt.points,Yt.fog]),vertexShader:er.points_vert,fragmentShader:er.points_frag},dashed:{uniforms:Gs([Yt.common,Yt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:er.linedashed_vert,fragmentShader:er.linedashed_frag},depth:{uniforms:Gs([Yt.common,Yt.displacementmap]),vertexShader:er.depth_vert,fragmentShader:er.depth_frag},normal:{uniforms:Gs([Yt.common,Yt.bumpmap,Yt.normalmap,Yt.displacementmap,{opacity:{value:1}}]),vertexShader:er.meshnormal_vert,fragmentShader:er.meshnormal_frag},sprite:{uniforms:Gs([Yt.sprite,Yt.fog]),vertexShader:er.sprite_vert,fragmentShader:er.sprite_frag},background:{uniforms:{uvTransform:{value:new lr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:er.background_vert,fragmentShader:er.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:er.backgroundCube_vert,fragmentShader:er.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:er.cube_vert,fragmentShader:er.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:er.equirect_vert,fragmentShader:er.equirect_frag},distanceRGBA:{uniforms:Gs([Yt.common,Yt.displacementmap,{referencePosition:{value:new ot},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:er.distanceRGBA_vert,fragmentShader:er.distanceRGBA_frag},shadow:{uniforms:Gs([Yt.lights,Yt.fog,{color:{value:new An(0)},opacity:{value:1}}]),vertexShader:er.shadow_vert,fragmentShader:er.shadow_frag}};wo.physical={uniforms:Gs([wo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new lr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new lr},clearcoatNormalScale:{value:new Hn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new lr},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 An(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 Hn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new lr},attenuationDistance:{value:0},attenuationColor:{value:new An(0)},specularColor:{value:new An(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new lr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new lr},anisotropyVector:{value:new Hn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new lr}}]),vertexShader:er.meshphysical_vert,fragmentShader:er.meshphysical_frag};const v1={r:0,b:0,g:0};function hTe(t,e,n,r,i,s,o){const l=new An(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function y(b,g){let _=!1,k=g.isScene===!0?g.background:null;k&&k.isTexture&&(k=(g.backgroundBlurriness>0?n:e).get(k)),k===null?v(l,c):k&&k.isColor&&(v(k,1),_=!0);const P=t.xr.getEnvironmentBlendMode();P==="additive"?r.buffers.color.setClear(0,0,0,1,o):P==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),k&&(k.isCubeTexture||k.mapping===FP)?(u===void 0&&(u=new Ac(new Uw(1,1,1),new Wh({name:"BackgroundCubeMaterial",uniforms:jx(wo.backgroundCube.uniforms),vertexShader:wo.backgroundCube.vertexShader,fragmentShader:wo.backgroundCube.fragmentShader,side:Po,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(N,M,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=g.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,u.material.toneMapped=$r.getTransfer(k.colorSpace)!==ua,(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 Ac(new $O(2,2),new Wh({name:"BackgroundMaterial",uniforms:jx(wo.background.uniforms),vertexShader:wo.background.vertexShader,fragmentShader:wo.background.fragmentShader,side:Gh,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=g.backgroundIntensity,d.material.toneMapped=$r.getTransfer(k.colorSpace)!==ua,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 v(b,g){b.getRGB(v1,$Z(t)),r.buffers.color.setClear(v1.r,v1.g,v1.b,g,o)}return{getClearColor:function(){return l},setClearColor:function(b,g=1){l.set(b),c=g,v(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(b){c=b,v(l,c)},render:y}}function pTe(t,e,n,r){const i=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=r.isWebGL2?null:e.get("OES_vertex_array_object"),o=r.isWebGL2||s!==null,l={},c=b(null);let d=c,u=!1;function m(L,te,ae,ee,me){let le=!1;if(o){const ue=v(ee,ae,te);d!==ue&&(d=ue,f(d.object)),le=g(L,ee,ae,me),le&&_(L,ee,ae,me)}else{const ue=te.wireframe===!0;(d.geometry!==ee.id||d.program!==ae.id||d.wireframe!==ue)&&(d.geometry=ee.id,d.program=ae.id,d.wireframe=ue,le=!0)}me!==null&&n.update(me,t.ELEMENT_ARRAY_BUFFER),(le||u)&&(u=!1,T(L,te,ae,ee),me!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(me).buffer))}function p(){return r.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function f(L){return r.isWebGL2?t.bindVertexArray(L):s.bindVertexArrayOES(L)}function y(L){return r.isWebGL2?t.deleteVertexArray(L):s.deleteVertexArrayOES(L)}function v(L,te,ae){const ee=ae.wireframe===!0;let me=l[L.id];me===void 0&&(me={},l[L.id]=me);let le=me[te.id];le===void 0&&(le={},me[te.id]=le);let ue=le[ee];return ue===void 0&&(ue=b(p()),le[ee]=ue),ue}function b(L){const te=[],ae=[],ee=[];for(let me=0;me<i;me++)te[me]=0,ae[me]=0,ee[me]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:te,enabledAttributes:ae,attributeDivisors:ee,object:L,attributes:{},index:null}}function g(L,te,ae,ee){const me=d.attributes,le=te.attributes;let ue=0;const K=ae.getAttributes();for(const ne in K)if(K[ne].location>=0){const be=me[ne];let _e=le[ne];if(_e===void 0&&(ne==="instanceMatrix"&&L.instanceMatrix&&(_e=L.instanceMatrix),ne==="instanceColor"&&L.instanceColor&&(_e=L.instanceColor)),be===void 0||be.attribute!==_e||_e&&be.data!==_e.data)return!0;ue++}return d.attributesNum!==ue||d.index!==ee}function _(L,te,ae,ee){const me={},le=te.attributes;let ue=0;const K=ae.getAttributes();for(const ne in K)if(K[ne].location>=0){let be=le[ne];be===void 0&&(ne==="instanceMatrix"&&L.instanceMatrix&&(be=L.instanceMatrix),ne==="instanceColor"&&L.instanceColor&&(be=L.instanceColor));const _e={};_e.attribute=be,be&&be.data&&(_e.data=be.data),me[ne]=_e,ue++}d.attributes=me,d.attributesNum=ue,d.index=ee}function k(){const L=d.newAttributes;for(let te=0,ae=L.length;te<ae;te++)L[te]=0}function P(L){N(L,0)}function N(L,te){const ae=d.newAttributes,ee=d.enabledAttributes,me=d.attributeDivisors;ae[L]=1,ee[L]===0&&(t.enableVertexAttribArray(L),ee[L]=1),me[L]!==te&&((r.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[r.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](L,te),me[L]=te)}function M(){const L=d.newAttributes,te=d.enabledAttributes;for(let ae=0,ee=te.length;ae<ee;ae++)te[ae]!==L[ae]&&(t.disableVertexAttribArray(ae),te[ae]=0)}function A(L,te,ae,ee,me,le,ue){ue===!0?t.vertexAttribIPointer(L,te,ae,me,le):t.vertexAttribPointer(L,te,ae,ee,me,le)}function T(L,te,ae,ee){if(r.isWebGL2===!1&&(L.isInstancedMesh||ee.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;k();const me=ee.attributes,le=ae.getAttributes(),ue=te.defaultAttributeValues;for(const K in le){const ne=le[K];if(ne.location>=0){let oe=me[K];if(oe===void 0&&(K==="instanceMatrix"&&L.instanceMatrix&&(oe=L.instanceMatrix),K==="instanceColor"&&L.instanceColor&&(oe=L.instanceColor)),oe!==void 0){const be=oe.normalized,_e=oe.itemSize,B=n.get(oe);if(B===void 0)continue;const Y=B.buffer,D=B.type,j=B.bytesPerElement,z=r.isWebGL2===!0&&(D===t.INT||D===t.UNSIGNED_INT||oe.gpuType===kZ);if(oe.isInterleavedBufferAttribute){const W=oe.data,q=W.stride,de=oe.offset;if(W.isInstancedInterleavedBuffer){for(let O=0;O<ne.locationSize;O++)N(ne.location+O,W.meshPerAttribute);L.isInstancedMesh!==!0&&ee._maxInstanceCount===void 0&&(ee._maxInstanceCount=W.meshPerAttribute*W.count)}else for(let O=0;O<ne.locationSize;O++)P(ne.location+O);t.bindBuffer(t.ARRAY_BUFFER,Y);for(let O=0;O<ne.locationSize;O++)A(ne.location+O,_e/ne.locationSize,D,be,q*j,(de+_e/ne.locationSize*O)*j,z)}else{if(oe.isInstancedBufferAttribute){for(let W=0;W<ne.locationSize;W++)N(ne.location+W,oe.meshPerAttribute);L.isInstancedMesh!==!0&&ee._maxInstanceCount===void 0&&(ee._maxInstanceCount=oe.meshPerAttribute*oe.count)}else for(let W=0;W<ne.locationSize;W++)P(ne.location+W);t.bindBuffer(t.ARRAY_BUFFER,Y);for(let W=0;W<ne.locationSize;W++)A(ne.location+W,_e/ne.locationSize,D,be,_e*j,_e/ne.locationSize*W*j,z)}}else if(ue!==void 0){const be=ue[K];if(be!==void 0)switch(be.length){case 2:t.vertexAttrib2fv(ne.location,be);break;case 3:t.vertexAttrib3fv(ne.location,be);break;case 4:t.vertexAttrib4fv(ne.location,be);break;default:t.vertexAttrib1fv(ne.location,be)}}}}M()}function C(){I();for(const L in l){const te=l[L];for(const ae in te){const ee=te[ae];for(const me in ee)y(ee[me].object),delete ee[me];delete te[ae]}delete l[L]}}function F(L){if(l[L.id]===void 0)return;const te=l[L.id];for(const ae in te){const ee=te[ae];for(const me in ee)y(ee[me].object),delete ee[me];delete te[ae]}delete l[L.id]}function $(L){for(const te in l){const ae=l[te];if(ae[L.id]===void 0)continue;const ee=ae[L.id];for(const me in ee)y(ee[me].object),delete ee[me];delete ae[L.id]}}function I(){X(),u=!0,d!==c&&(d=c,f(d.object))}function X(){c.geometry=null,c.program=null,c.wireframe=!1}return{setup:m,reset:I,resetDefaultState:X,dispose:C,releaseStatesOfGeometry:F,releaseStatesOfProgram:$,initAttributes:k,enableAttribute:P,disableUnusedAttributes:M}}function fTe(t,e,n,r){const i=r.isWebGL2;let s;function o(u){s=u}function l(u,m){t.drawArrays(s,u,m),n.update(m,s,1)}function c(u,m,p){if(p===0)return;let f,y;if(i)f=t,y="drawArraysInstanced";else if(f=e.get("ANGLE_instanced_arrays"),y="drawArraysInstancedANGLE",f===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}f[y](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 y=0;y<p;y++)this.render(u[y],m[y]);else{f.multiDrawArraysWEBGL(s,u,0,m,0,p);let y=0;for(let v=0;v<p;v++)y+=m[v];n.update(y,s,1)}}this.setMode=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=d}function gTe(t,e,n){let r;function i(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}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),y=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),v=t.getParameter(t.MAX_VERTEX_ATTRIBS),b=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),g=t.getParameter(t.MAX_VARYING_VECTORS),_=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),k=p>0,P=o||e.has("OES_texture_float"),N=k&&P,M=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:y,maxAttributes:v,maxVertexUniforms:b,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:k,floatFragmentTextures:P,floatVertexTextures:N,maxSamples:M}}function bTe(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new ah,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||r!==0||i;return i=p,r=m.length,f},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=u(m,p,0)},this.setState=function(m,p,f){const y=m.clippingPlanes,v=m.clipIntersection,b=m.clipShadows,g=t.get(m);if(!i||y===null||y.length===0||s&&!b)s?u(null):d();else{const _=s?0:r,k=_*4;let P=g.clippingState||null;c.value=P,P=u(y,p,k,f);for(let N=0;N!==k;++N)P[N]=n[N];g.clippingState=P,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(m,p,f,y){const v=m!==null?m.length:0;let b=null;if(v!==0){if(b=c.value,y!==!0||b===null){const g=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(b===null||b.length<g)&&(b=new Float32Array(g));for(let k=0,P=f;k!==v;++k,P+=4)o.copy(m[k]).applyMatrix4(_,l),o.normal.toArray(b,P),b[P+3]=o.constant}c.value=b,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,b}}function xTe(t){let e=new WeakMap;function n(o,l){return l===BF?o.mapping=Tx:l===HF&&(o.mapping=Ax),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===BF||l===HF)if(e.has(o)){const c=e.get(o).texture;return n(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const d=new MNe(c.height/2);return d.fromEquirectangularTexture(t,o),e.set(o,d),o.addEventListener("dispose",i),n(d.texture,o.mapping)}else return null}}return o}function i(o){const l=o.target;l.removeEventListener("dispose",i);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class yTe extends VZ{constructor(e=-1,n=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=i+n,c=i-n;if(this.view!==null&&this.view.enabled){const d=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=d*this.view.offsetX,o=s+d*this.view.width,l-=u*this.view.offsetY,c=l-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const Xb=4,Mq=[.125,.215,.35,.446,.526,.582],tf=20,gE=new yTe,jq=new An;let bE=null,xE=0,yE=0;const Wp=(1+Math.sqrt(5))/2,Tb=1/Wp,Eq=[new ot(1,1,1),new ot(-1,1,1),new ot(1,1,-1),new ot(-1,1,-1),new ot(0,Wp,Tb),new ot(0,Wp,-Tb),new ot(Tb,0,Wp),new ot(-Tb,0,Wp),new ot(Wp,Tb,0),new ot(-Wp,Tb,0)];class Dq{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,i=100){bE=this._renderer.getRenderTarget(),xE=this._renderer.getActiveCubeFace(),yE=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Lq(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Rq(),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(bE,xE,yE),e.scissorTest=!1,w1(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===Tx||e.mapping===Ax?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),bE=this._renderer.getRenderTarget(),xE=this._renderer.getActiveCubeFace(),yE=this._renderer.getActiveMipmapLevel();const r=n||this._allocateTargets();return this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,r={magFilter:Ll,minFilter:Ll,generateMipmaps:!1,type:$0,format:Ol,colorSpace:Qu,depthBuffer:!1},i=Fq(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Fq(e,n,r);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=vTe(s)),this._blurMaterial=wTe(s,e,n)}return i}_compileMaterial(e){const n=new Ac(this._lodPlanes[0],e);this._renderer.compile(n,gE)}_sceneToCubeUV(e,n,r,i){const l=new Zo(90,1,n,r),c=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,m=u.autoClear,p=u.toneMapping;u.getClearColor(jq),u.toneMapping=Lh,u.autoClear=!1;const f=new BZ({name:"PMREM.Background",side:Po,depthWrite:!1,depthTest:!1}),y=new Ac(new Uw,f);let v=!1;const b=e.background;b?b.isColor&&(f.color.copy(b),e.background=null,v=!0):(f.color.copy(jq),v=!0);for(let g=0;g<6;g++){const _=g%3;_===0?(l.up.set(0,c[g],0),l.lookAt(d[g],0,0)):_===1?(l.up.set(0,0,c[g]),l.lookAt(0,d[g],0)):(l.up.set(0,c[g],0),l.lookAt(0,0,d[g]));const k=this._cubeSize;w1(i,_*k,g>2?k:0,k,k),u.setRenderTarget(i),v&&u.render(y,l),u.render(e,l)}y.geometry.dispose(),y.material.dispose(),u.toneMapping=p,u.autoClear=m,e.background=b}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===Tx||e.mapping===Ax;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=Lq()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Rq());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Ac(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;w1(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,gE)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;for(let i=1;i<this._lodPlanes.length;i++){const s=Math.sqrt(this._sigmas[i]*this._sigmas[i]-this._sigmas[i-1]*this._sigmas[i-1]),o=Eq[(i-1)%Eq.length];this._blur(e,i-1,i,s,o)}n.autoClear=r}_blur(e,n,r,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,i,"latitudinal",s),this._halfBlur(o,e,r,r,i,"longitudinal",s)}_halfBlur(e,n,r,i,s,o,l){const c=this._renderer,d=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const u=3,m=new Ac(this._lodPlanes[i],d),p=d.uniforms,f=this._sizeLods[r]-1,y=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*tf-1),v=s/y,b=isFinite(s)?1+Math.floor(u*v):tf;b>tf&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${tf}`);const g=[];let _=0;for(let A=0;A<tf;++A){const T=A/v,C=Math.exp(-T*T/2);g.push(C),A===0?_+=C:A<b&&(_+=2*C)}for(let A=0;A<g.length;A++)g[A]=g[A]/_;p.envMap.value=e.texture,p.samples.value=b,p.weights.value=g,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:k}=this;p.dTheta.value=y,p.mipInt.value=k-r;const P=this._sizeLods[i],N=3*P*(i>k-Xb?i-k+Xb:0),M=4*(this._cubeSize-P);w1(n,N,M,3*P,2*P),c.setRenderTarget(n),c.render(m,gE)}}function vTe(t){const e=[],n=[],r=[];let i=t;const s=t-Xb+1+Mq.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);n.push(l);let c=1/l;o>t-Xb?c=Mq[o-t+Xb-1]:o===0&&(c=0),r.push(c);const d=1/(l-2),u=-d,m=1+d,p=[u,u,m,u,m,m,u,u,m,m,u,m],f=6,y=6,v=3,b=2,g=1,_=new Float32Array(v*y*f),k=new Float32Array(b*y*f),P=new Float32Array(g*y*f);for(let M=0;M<f;M++){const A=M%3*2/3-1,T=M>2?0:-1,C=[A,T,0,A+2/3,T,0,A+2/3,T+1,0,A,T,0,A+2/3,T+1,0,A,T+1,0];_.set(C,v*y*M),k.set(p,b*y*M);const F=[M,M,M,M,M,M];P.set(F,g*y*M)}const N=new Rs;N.setAttribute("position",new al(_,v)),N.setAttribute("uv",new al(k,b)),N.setAttribute("faceIndex",new al(P,g)),e.push(N),i>Xb&&i--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function Fq(t,e,n){const r=new Vf(t,e,n);return r.texture.mapping=FP,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function w1(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function wTe(t,e,n){const r=new Float32Array(tf),i=new ot(0,1,0);return new Wh({name:"SphericalGaussianBlur",defines:{n:tf,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:VO(),fragmentShader:`
  7274. precision mediump float;
  7275. precision mediump int;
  7276. varying vec3 vOutputDirection;
  7277. uniform sampler2D envMap;
  7278. uniform int samples;
  7279. uniform float weights[ n ];
  7280. uniform bool latitudinal;
  7281. uniform float dTheta;
  7282. uniform float mipInt;
  7283. uniform vec3 poleAxis;
  7284. #define ENVMAP_TYPE_CUBE_UV
  7285. #include <cube_uv_reflection_fragment>
  7286. vec3 getSample( float theta, vec3 axis ) {
  7287. float cosTheta = cos( theta );
  7288. // Rodrigues' axis-angle rotation
  7289. vec3 sampleDirection = vOutputDirection * cosTheta
  7290. + cross( axis, vOutputDirection ) * sin( theta )
  7291. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  7292. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  7293. }
  7294. void main() {
  7295. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  7296. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  7297. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  7298. }
  7299. axis = normalize( axis );
  7300. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  7301. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  7302. for ( int i = 1; i < n; i++ ) {
  7303. if ( i >= samples ) {
  7304. break;
  7305. }
  7306. float theta = dTheta * float( i );
  7307. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  7308. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  7309. }
  7310. }
  7311. `,blending:Rh,depthTest:!1,depthWrite:!1})}function Rq(){return new Wh({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:VO(),fragmentShader:`
  7312. precision mediump float;
  7313. precision mediump int;
  7314. varying vec3 vOutputDirection;
  7315. uniform sampler2D envMap;
  7316. #include <common>
  7317. void main() {
  7318. vec3 outputDirection = normalize( vOutputDirection );
  7319. vec2 uv = equirectUv( outputDirection );
  7320. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  7321. }
  7322. `,blending:Rh,depthTest:!1,depthWrite:!1})}function Lq(){return new Wh({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:VO(),fragmentShader:`
  7323. precision mediump float;
  7324. precision mediump int;
  7325. uniform float flipEnvMap;
  7326. varying vec3 vOutputDirection;
  7327. uniform samplerCube envMap;
  7328. void main() {
  7329. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  7330. }
  7331. `,blending:Rh,depthTest:!1,depthWrite:!1})}function VO(){return`
  7332. precision mediump float;
  7333. precision mediump int;
  7334. attribute float faceIndex;
  7335. varying vec3 vOutputDirection;
  7336. // RH coordinate system; PMREM face-indexing convention
  7337. vec3 getDirection( vec2 uv, float face ) {
  7338. uv = 2.0 * uv - 1.0;
  7339. vec3 direction = vec3( uv, 1.0 );
  7340. if ( face == 0.0 ) {
  7341. direction = direction.zyx; // ( 1, v, u ) pos x
  7342. } else if ( face == 1.0 ) {
  7343. direction = direction.xzy;
  7344. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  7345. } else if ( face == 2.0 ) {
  7346. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  7347. } else if ( face == 3.0 ) {
  7348. direction = direction.zyx;
  7349. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  7350. } else if ( face == 4.0 ) {
  7351. direction = direction.xzy;
  7352. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  7353. } else if ( face == 5.0 ) {
  7354. direction.z *= -1.0; // ( u, v, -1 ) neg z
  7355. }
  7356. return direction;
  7357. }
  7358. void main() {
  7359. vOutputDirection = getDirection( uv, faceIndex );
  7360. gl_Position = vec4( position, 1.0 );
  7361. }
  7362. `}function STe(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,d=c===BF||c===HF,u=c===Tx||c===Ax;if(d||u)if(l.isRenderTargetTexture&&l.needsPMREMUpdate===!0){l.needsPMREMUpdate=!1;let m=e.get(l);return n===null&&(n=new Dq(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 Dq(t));const p=d?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,p),l.addEventListener("dispose",s),p.texture}else return null}}}return l}function i(l){let c=0;const d=6;for(let u=0;u<d;u++)l[u]!==void 0&&c++;return c===d}function s(l){const c=l.target;c.removeEventListener("dispose",s);const d=e.get(c);d!==void 0&&(e.delete(c),d.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function _Te(t){const e={};function n(r){if(e[r]!==void 0)return e[r];let i;switch(r){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(r)}return e[r]=i,i}return{has:function(r){return n(r)!==null},init:function(r){r.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(r){const i=n(r);return i===null&&console.warn("THREE.WebGLRenderer: "+r+" extension not supported."),i}}}function kTe(t,e,n,r){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const y in p.attributes)e.remove(p.attributes[y]);for(const y in p.morphAttributes){const v=p.morphAttributes[y];for(let b=0,g=v.length;b<g;b++)e.remove(v[b])}p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),r.releaseStatesOfGeometry(p),p.isInstancedBufferGeometry===!0&&delete p._maxInstanceCount,n.memory.geometries--}function l(m,p){return i[p.id]===!0||(p.addEventListener("dispose",o),i[p.id]=!0,n.memory.geometries++),p}function c(m){const p=m.attributes;for(const y in p)e.update(p[y],t.ARRAY_BUFFER);const f=m.morphAttributes;for(const y in f){const v=f[y];for(let b=0,g=v.length;b<g;b++)e.update(v[b],t.ARRAY_BUFFER)}}function d(m){const p=[],f=m.index,y=m.attributes.position;let v=0;if(f!==null){const _=f.array;v=f.version;for(let k=0,P=_.length;k<P;k+=3){const N=_[k+0],M=_[k+1],A=_[k+2];p.push(N,M,M,A,A,N)}}else if(y!==void 0){const _=y.array;v=y.version;for(let k=0,P=_.length/3-1;k<P;k+=3){const N=k+0,M=k+1,A=k+2;p.push(N,M,M,A,A,N)}}else return;const b=new(RZ(p)?qZ:HZ)(p,1);b.version=v;const g=s.get(m);g&&e.remove(g),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 NTe(t,e,n,r){const i=r.isWebGL2;let s;function o(f){s=f}let l,c;function d(f){l=f.type,c=f.bytesPerElement}function u(f,y){t.drawElements(s,y,l,f*c),n.update(y,s,1)}function m(f,y,v){if(v===0)return;let b,g;if(i)b=t,g="drawElementsInstanced";else if(b=e.get("ANGLE_instanced_arrays"),g="drawElementsInstancedANGLE",b===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}b[g](s,y,l,f*c,v),n.update(y,s,v)}function p(f,y,v){if(v===0)return;const b=e.get("WEBGL_multi_draw");if(b===null)for(let g=0;g<v;g++)this.render(f[g]/c,y[g]);else{b.multiDrawElementsWEBGL(s,y,0,l,f,0,v);let g=0;for(let _=0;_<v;_++)g+=y[_];n.update(g,s,1)}}this.setMode=o,this.setIndex=d,this.render=u,this.renderInstances=m,this.renderMultiDraw=p}function CTe(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(s,o,l){switch(n.calls++,o){case t.TRIANGLES:n.triangles+=l*(s/3);break;case t.LINES:n.lines+=l*(s/2);break;case t.LINE_STRIP:n.lines+=l*(s-1);break;case t.LINE_LOOP:n.lines+=l*s;break;case t.POINTS:n.points+=l*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",o);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:i,update:r}}function PTe(t,e){return t[0]-e[0]}function TTe(t,e){return Math.abs(e[1])-Math.abs(t[1])}function ATe(t,e,n){const r={},i=new Float32Array(8),s=new WeakMap,o=new Gr,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 y=u.morphAttributes.position||u.morphAttributes.normal||u.morphAttributes.color,v=y!==void 0?y.length:0;let b=s.get(u);if(b===void 0||b.count!==v){let te=function(){X.dispose(),s.delete(u),u.removeEventListener("dispose",te)};var f=te;b!==void 0&&b.texture.dispose();const k=u.morphAttributes.position!==void 0,P=u.morphAttributes.normal!==void 0,N=u.morphAttributes.color!==void 0,M=u.morphAttributes.position||[],A=u.morphAttributes.normal||[],T=u.morphAttributes.color||[];let C=0;k===!0&&(C=1),P===!0&&(C=2),N===!0&&(C=3);let F=u.attributes.position.count*C,$=1;F>e.maxTextureSize&&($=Math.ceil(F/e.maxTextureSize),F=e.maxTextureSize);const I=new Float32Array(F*$*4*v),X=new IZ(I,F,$,v);X.type=ju,X.needsUpdate=!0;const L=C*4;for(let ae=0;ae<v;ae++){const ee=M[ae],me=A[ae],le=T[ae],ue=F*$*4*ae;for(let K=0;K<ee.count;K++){const ne=K*L;k===!0&&(o.fromBufferAttribute(ee,K),I[ue+ne+0]=o.x,I[ue+ne+1]=o.y,I[ue+ne+2]=o.z,I[ue+ne+3]=0),P===!0&&(o.fromBufferAttribute(me,K),I[ue+ne+4]=o.x,I[ue+ne+5]=o.y,I[ue+ne+6]=o.z,I[ue+ne+7]=0),N===!0&&(o.fromBufferAttribute(le,K),I[ue+ne+8]=o.x,I[ue+ne+9]=o.y,I[ue+ne+10]=o.z,I[ue+ne+11]=le.itemSize===4?o.w:1)}}b={count:v,texture:X,size:new Hn(F,$)},s.set(u,b),u.addEventListener("dispose",te)}let g=0;for(let k=0;k<p.length;k++)g+=p[k];const _=u.morphTargetsRelative?1:1-g;m.getUniforms().setValue(t,"morphTargetBaseInfluence",_),m.getUniforms().setValue(t,"morphTargetInfluences",p),m.getUniforms().setValue(t,"morphTargetsTexture",b.texture,n),m.getUniforms().setValue(t,"morphTargetsTextureSize",b.size)}else{const y=p===void 0?0:p.length;let v=r[u.id];if(v===void 0||v.length!==y){v=[];for(let P=0;P<y;P++)v[P]=[P,0];r[u.id]=v}for(let P=0;P<y;P++){const N=v[P];N[0]=P,N[1]=p[P]}v.sort(TTe);for(let P=0;P<8;P++)P<y&&v[P][1]?(l[P][0]=v[P][0],l[P][1]=v[P][1]):(l[P][0]=Number.MAX_SAFE_INTEGER,l[P][1]=0);l.sort(PTe);const b=u.morphAttributes.position,g=u.morphAttributes.normal;let _=0;for(let P=0;P<8;P++){const N=l[P],M=N[0],A=N[1];M!==Number.MAX_SAFE_INTEGER&&A?(b&&u.getAttribute("morphTarget"+P)!==b[M]&&u.setAttribute("morphTarget"+P,b[M]),g&&u.getAttribute("morphNormal"+P)!==g[M]&&u.setAttribute("morphNormal"+P,g[M]),i[P]=A,_+=A):(b&&u.hasAttribute("morphTarget"+P)===!0&&u.deleteAttribute("morphTarget"+P),g&&u.hasAttribute("morphNormal"+P)===!0&&u.deleteAttribute("morphNormal"+P),i[P]=0)}const k=u.morphTargetsRelative?1:1-_;m.getUniforms().setValue(t,"morphTargetBaseInfluence",k),m.getUniforms().setValue(t,"morphTargetInfluences",i)}}return{update:c}}function MTe(t,e,n,r){let i=new WeakMap;function s(c){const d=r.render.frame,u=c.geometry,m=e.get(c,u);if(i.get(m)!==d&&(e.update(m),i.set(m,d)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),i.get(c)!==d&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),i.set(c,d))),c.isSkinnedMesh){const p=c.skeleton;i.get(p)!==d&&(p.update(),i.set(p,d))}return m}function o(){i=new WeakMap}function l(c){const d=c.target;d.removeEventListener("dispose",l),n.remove(d.instanceMatrix),d.instanceColor!==null&&n.remove(d.instanceColor)}return{update:s,dispose:o}}class KZ extends To{constructor(e,n,r,i,s,o,l,c,d,u){if(u=u!==void 0?u:Sf,u!==Sf&&u!==Mx)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&u===Sf&&(r=vh),r===void 0&&u===Mx&&(r=wf),super(null,i,s,o,l,c,u,r,d),this.isDepthTexture=!0,this.image={width:e,height:n},this.magFilter=l!==void 0?l:ns,this.minFilter=c!==void 0?c:ns,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 YZ=new To,XZ=new KZ(1,1);XZ.compareFunction=DZ;const QZ=new IZ,ZZ=new pNe,JZ=new GZ,Oq=[],Iq=[],zq=new Float32Array(16),Uq=new Float32Array(9),Bq=new Float32Array(4);function oy(t,e,n){const r=t[0];if(r<=0||r>0)return t;const i=e*n;let s=Oq[i];if(s===void 0&&(s=new Float32Array(i),Oq[i]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function yi(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n<r;n++)if(t[n]!==e[n])return!1;return!0}function vi(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function OP(t,e){let n=Iq[e];n===void 0&&(n=new Int32Array(e),Iq[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function jTe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function ETe(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(yi(n,e))return;t.uniform2fv(this.addr,e),vi(n,e)}}function DTe(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(yi(n,e))return;t.uniform3fv(this.addr,e),vi(n,e)}}function FTe(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(yi(n,e))return;t.uniform4fv(this.addr,e),vi(n,e)}}function RTe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(yi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),vi(n,e)}else{if(yi(n,r))return;Bq.set(r),t.uniformMatrix2fv(this.addr,!1,Bq),vi(n,r)}}function LTe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(yi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),vi(n,e)}else{if(yi(n,r))return;Uq.set(r),t.uniformMatrix3fv(this.addr,!1,Uq),vi(n,r)}}function OTe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(yi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),vi(n,e)}else{if(yi(n,r))return;zq.set(r),t.uniformMatrix4fv(this.addr,!1,zq),vi(n,r)}}function ITe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function zTe(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(yi(n,e))return;t.uniform2iv(this.addr,e),vi(n,e)}}function UTe(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(yi(n,e))return;t.uniform3iv(this.addr,e),vi(n,e)}}function BTe(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(yi(n,e))return;t.uniform4iv(this.addr,e),vi(n,e)}}function HTe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function qTe(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(yi(n,e))return;t.uniform2uiv(this.addr,e),vi(n,e)}}function $Te(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(yi(n,e))return;t.uniform3uiv(this.addr,e),vi(n,e)}}function VTe(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(yi(n,e))return;t.uniform4uiv(this.addr,e),vi(n,e)}}function GTe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i);const s=this.type===t.SAMPLER_2D_SHADOW?XZ:YZ;n.setTexture2D(e||s,i)}function WTe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(e||ZZ,i)}function KTe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(e||JZ,i)}function YTe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(e||QZ,i)}function XTe(t){switch(t){case 5126:return jTe;case 35664:return ETe;case 35665:return DTe;case 35666:return FTe;case 35674:return RTe;case 35675:return LTe;case 35676:return OTe;case 5124:case 35670:return ITe;case 35667:case 35671:return zTe;case 35668:case 35672:return UTe;case 35669:case 35673:return BTe;case 5125:return HTe;case 36294:return qTe;case 36295:return $Te;case 36296:return VTe;case 35678:case 36198:case 36298:case 36306:case 35682:return GTe;case 35679:case 36299:case 36307:return WTe;case 35680:case 36300:case 36308:case 36293:return KTe;case 36289:case 36303:case 36311:case 36292:return YTe}}function QTe(t,e){t.uniform1fv(this.addr,e)}function ZTe(t,e){const n=oy(e,this.size,2);t.uniform2fv(this.addr,n)}function JTe(t,e){const n=oy(e,this.size,3);t.uniform3fv(this.addr,n)}function eAe(t,e){const n=oy(e,this.size,4);t.uniform4fv(this.addr,n)}function tAe(t,e){const n=oy(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function nAe(t,e){const n=oy(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function rAe(t,e){const n=oy(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function aAe(t,e){t.uniform1iv(this.addr,e)}function iAe(t,e){t.uniform2iv(this.addr,e)}function sAe(t,e){t.uniform3iv(this.addr,e)}function oAe(t,e){t.uniform4iv(this.addr,e)}function lAe(t,e){t.uniform1uiv(this.addr,e)}function cAe(t,e){t.uniform2uiv(this.addr,e)}function dAe(t,e){t.uniform3uiv(this.addr,e)}function uAe(t,e){t.uniform4uiv(this.addr,e)}function mAe(t,e,n){const r=this.cache,i=e.length,s=OP(n,i);yi(r,s)||(t.uniform1iv(this.addr,s),vi(r,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||YZ,s[o])}function hAe(t,e,n){const r=this.cache,i=e.length,s=OP(n,i);yi(r,s)||(t.uniform1iv(this.addr,s),vi(r,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||ZZ,s[o])}function pAe(t,e,n){const r=this.cache,i=e.length,s=OP(n,i);yi(r,s)||(t.uniform1iv(this.addr,s),vi(r,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||JZ,s[o])}function fAe(t,e,n){const r=this.cache,i=e.length,s=OP(n,i);yi(r,s)||(t.uniform1iv(this.addr,s),vi(r,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||QZ,s[o])}function gAe(t){switch(t){case 5126:return QTe;case 35664:return ZTe;case 35665:return JTe;case 35666:return eAe;case 35674:return tAe;case 35675:return nAe;case 35676:return rAe;case 5124:case 35670:return aAe;case 35667:case 35671:return iAe;case 35668:case 35672:return sAe;case 35669:case 35673:return oAe;case 5125:return lAe;case 36294:return cAe;case 36295:return dAe;case 36296:return uAe;case 35678:case 36198:case 36298:case 36306:case 35682:return mAe;case 35679:case 36299:case 36307:return hAe;case 35680:case 36300:case 36308:case 36293:return pAe;case 36289:case 36303:case 36311:case 36292:return fAe}}class bAe{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=XTe(n.type)}}class xAe{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=gAe(n.type)}}class yAe{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],r)}}}const vE=/(\w+)(\])?(\[|\.)?/g;function Hq(t,e){t.seq.push(e),t.map[e.id]=e}function vAe(t,e,n){const r=t.name,i=r.length;for(vE.lastIndex=0;;){const s=vE.exec(r),o=vE.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){Hq(n,d===void 0?new bAe(l,t,e):new xAe(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new yAe(l),Hq(n,m)),n=m}}}class Tk{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<r;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);vAe(s,o,this)}}setValue(e,n,r,i){const s=this.map[n];s!==void 0&&s.setValue(e,r,i)}setOptional(e,n,r){const i=n[r];i!==void 0&&this.setValue(e,r,i)}static upload(e,n,r,i){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=r[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,i)}}static seqWithValue(e,n){const r=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&r.push(o)}return r}}function qq(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const wAe=37297;let SAe=0;function _Ae(t,e){const n=t.split(`
  7363. `),r=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
  7364. `)}function kAe(t){const e=$r.getPrimaries($r.workingColorSpace),n=$r.getPrimaries(t);let r;switch(e===n?r="":e===gN&&n===fN?r="LinearDisplayP3ToLinearSRGB":e===fN&&n===gN&&(r="LinearSRGBToLinearDisplayP3"),t){case Qu:case RP:return[r,"LinearTransferOETF"];case rs:case UO:return[r,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[r,"LinearTransferOETF"]}}function $q(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),i=t.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return n.toUpperCase()+`
  7365. `+i+`
  7366. `+_Ae(t.getShaderSource(e),o)}else return i}function NAe(t,e){const n=kAe(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function CAe(t,e){let n;switch(e){case Nke:n="Linear";break;case Cke:n="Reinhard";break;case Pke:n="OptimizedCineon";break;case Tke:n="ACESFilmic";break;case Ake:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function PAe(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(Vv).join(`
  7367. `)}function TAe(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
  7368. `)}function AAe(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){const s=t.getActiveAttrib(e,i),o=s.name;let l=1;s.type===t.FLOAT_MAT2&&(l=2),s.type===t.FLOAT_MAT3&&(l=3),s.type===t.FLOAT_MAT4&&(l=4),n[o]={type:s.type,location:t.getAttribLocation(e,o),locationSize:l}}return n}function Vv(t){return t!==""}function Vq(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 Gq(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const MAe=/^[ \t]*#include +<([\w\d./]+)>/gm;function KF(t){return t.replace(MAe,EAe)}const jAe=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function EAe(t,e){let n=er[e];if(n===void 0){const r=jAe.get(e);if(r!==void 0)n=er[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return KF(n)}const DAe=/#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 Wq(t){return t.replace(DAe,FAe)}function FAe(t,e,n,r){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function Kq(t){let e="precision "+t.precision+` float;
  7369. precision `+t.precision+" int;";return t.precision==="highp"?e+=`
  7370. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  7371. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  7372. #define LOW_PRECISION`),e}function RAe(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===SZ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===J1e?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===xu&&(e="SHADOWMAP_TYPE_VSM"),e}function LAe(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case Tx:case Ax:e="ENVMAP_TYPE_CUBE";break;case FP:e="ENVMAP_TYPE_CUBE_UV";break}return e}function OAe(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===Ax&&(e="ENVMAP_MODE_REFRACTION"),e}function IAe(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case IO:e="ENVMAP_BLENDING_MULTIPLY";break;case _ke:e="ENVMAP_BLENDING_MIX";break;case kke:e="ENVMAP_BLENDING_ADD";break}return e}function zAe(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:r,maxMip:n}}function UAe(t,e,n,r){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=RAe(n),d=LAe(n),u=OAe(n),m=IAe(n),p=zAe(n),f=n.isWebGL2?"":PAe(n),y=TAe(s),v=i.createProgram();let b,g,_=n.glslVersion?"#version "+n.glslVersion+`
  7373. `:"";n.isRawShaderMaterial?(b=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y].filter(Vv).join(`
  7374. `),b.length>0&&(b+=`
  7375. `),g=[f,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y].filter(Vv).join(`
  7376. `),g.length>0&&(g+=`
  7377. `)):(b=[Kq(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y,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",`
  7378. `].filter(Vv).join(`
  7379. `),g=[f,Kq(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,y,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!==Lh?"#define TONE_MAPPING":"",n.toneMapping!==Lh?er.tonemapping_pars_fragment:"",n.toneMapping!==Lh?CAe("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",er.colorspace_pars_fragment,NAe("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  7380. `].filter(Vv).join(`
  7381. `)),o=KF(o),o=Vq(o,n),o=Gq(o,n),l=KF(l),l=Vq(l,n),l=Gq(l,n),o=Wq(o),l=Wq(l),n.isWebGL2&&n.isRawShaderMaterial!==!0&&(_=`#version 300 es
  7382. `,b=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(`
  7383. `)+`
  7384. `+b,g=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===mq?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===mq?"":"#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(`
  7385. `)+`
  7386. `+g);const k=_+b+o,P=_+g+l,N=qq(i,i.VERTEX_SHADER,k),M=qq(i,i.FRAGMENT_SHADER,P);i.attachShader(v,N),i.attachShader(v,M),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function A($){if(t.debug.checkShaderErrors){const I=i.getProgramInfoLog(v).trim(),X=i.getShaderInfoLog(N).trim(),L=i.getShaderInfoLog(M).trim();let te=!0,ae=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(te=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,M);else{const ee=$q(i,N,"vertex"),me=$q(i,M,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+`
  7387. Program Info Log: `+I+`
  7388. `+ee+`
  7389. `+me)}else I!==""?console.warn("THREE.WebGLProgram: Program Info Log:",I):(X===""||L==="")&&(ae=!1);ae&&($.diagnostics={runnable:te,programLog:I,vertexShader:{log:X,prefix:b},fragmentShader:{log:L,prefix:g}})}i.deleteShader(N),i.deleteShader(M),T=new Tk(i,v),C=AAe(i,v)}let T;this.getUniforms=function(){return T===void 0&&A(this),T};let C;this.getAttributes=function(){return C===void 0&&A(this),C};let F=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return F===!1&&(F=i.getProgramParameter(v,wAe)),F},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=SAe++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=M,this}let BAe=0;class HAe{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new qAe(e),n.set(e,r)),r}}class qAe{constructor(e){this.id=BAe++,this.code=e,this.usedTimes=0}}function $Ae(t,e,n,r,i,s,o){const l=new zZ,c=new HAe,d=[],u=i.isWebGL2,m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.precision;const y={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(C){return C===0?"uv":`uv${C}`}function b(C,F,$,I,X){const L=I.fog,te=X.geometry,ae=C.isMeshStandardMaterial?I.environment:null,ee=(C.isMeshStandardMaterial?n:e).get(C.envMap||ae),me=ee&&ee.mapping===FP?ee.image.height:null,le=y[C.type];C.precision!==null&&(f=i.getMaxPrecision(C.precision),f!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",f,"instead."));const ue=te.morphAttributes.position||te.morphAttributes.normal||te.morphAttributes.color,K=ue!==void 0?ue.length:0;let ne=0;te.morphAttributes.position!==void 0&&(ne=1),te.morphAttributes.normal!==void 0&&(ne=2),te.morphAttributes.color!==void 0&&(ne=3);let oe,be,_e,B;if(le){const xt=wo[le];oe=xt.vertexShader,be=xt.fragmentShader}else oe=C.vertexShader,be=C.fragmentShader,c.update(C),_e=c.getVertexShaderID(C),B=c.getFragmentShaderID(C);const Y=t.getRenderTarget(),D=X.isInstancedMesh===!0,j=X.isBatchedMesh===!0,z=!!C.map,W=!!C.matcap,q=!!ee,de=!!C.aoMap,O=!!C.lightMap,G=!!C.bumpMap,Q=!!C.normalMap,V=!!C.displacementMap,J=!!C.emissiveMap,ie=!!C.metalnessMap,he=!!C.roughnessMap,fe=C.anisotropy>0,se=C.clearcoat>0,U=C.iridescence>0,R=C.sheen>0,re=C.transmission>0,xe=fe&&!!C.anisotropyMap,we=se&&!!C.clearcoatMap,ye=se&&!!C.clearcoatNormalMap,Ae=se&&!!C.clearcoatRoughnessMap,ve=U&&!!C.iridescenceMap,Te=U&&!!C.iridescenceThicknessMap,Fe=R&&!!C.sheenColorMap,Ee=R&&!!C.sheenRoughnessMap,Se=!!C.specularMap,je=!!C.specularColorMap,qe=!!C.specularIntensityMap,Re=re&&!!C.transmissionMap,Ye=re&&!!C.thicknessMap,ce=!!C.gradientMap,ze=!!C.alphaMap,Ne=C.alphaTest>0,Ge=!!C.alphaHash,$e=!!C.extensions,Pe=!!te.attributes.uv1,Me=!!te.attributes.uv2,Ve=!!te.attributes.uv3;let tt=Lh;return C.toneMapped&&(Y===null||Y.isXRRenderTarget===!0)&&(tt=t.toneMapping),{isWebGL2:u,shaderID:le,shaderType:C.type,shaderName:C.name,vertexShader:oe,fragmentShader:be,defines:C.defines,customVertexShaderID:_e,customFragmentShaderID:B,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:f,batching:j,instancing:D,instancingColor:D&&X.instanceColor!==null,supportsVertexTextures:p,outputColorSpace:Y===null?t.outputColorSpace:Y.isXRRenderTarget===!0?Y.texture.colorSpace:Qu,map:z,matcap:W,envMap:q,envMapMode:q&&ee.mapping,envMapCubeUVHeight:me,aoMap:de,lightMap:O,bumpMap:G,normalMap:Q,displacementMap:p&&V,emissiveMap:J,normalMapObjectSpace:Q&&C.normalMapType===Bke,normalMapTangentSpace:Q&&C.normalMapType===EZ,metalnessMap:ie,roughnessMap:he,anisotropy:fe,anisotropyMap:xe,clearcoat:se,clearcoatMap:we,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ae,iridescence:U,iridescenceMap:ve,iridescenceThicknessMap:Te,sheen:R,sheenColorMap:Fe,sheenRoughnessMap:Ee,specularMap:Se,specularColorMap:je,specularIntensityMap:qe,transmission:re,transmissionMap:Re,thicknessMap:Ye,gradientMap:ce,opaque:C.transparent===!1&&C.blending===sx,alphaMap:ze,alphaTest:Ne,alphaHash:Ge,combine:C.combine,mapUv:z&&v(C.map.channel),aoMapUv:de&&v(C.aoMap.channel),lightMapUv:O&&v(C.lightMap.channel),bumpMapUv:G&&v(C.bumpMap.channel),normalMapUv:Q&&v(C.normalMap.channel),displacementMapUv:V&&v(C.displacementMap.channel),emissiveMapUv:J&&v(C.emissiveMap.channel),metalnessMapUv:ie&&v(C.metalnessMap.channel),roughnessMapUv:he&&v(C.roughnessMap.channel),anisotropyMapUv:xe&&v(C.anisotropyMap.channel),clearcoatMapUv:we&&v(C.clearcoatMap.channel),clearcoatNormalMapUv:ye&&v(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(C.clearcoatRoughnessMap.channel),iridescenceMapUv:ve&&v(C.iridescenceMap.channel),iridescenceThicknessMapUv:Te&&v(C.iridescenceThicknessMap.channel),sheenColorMapUv:Fe&&v(C.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&v(C.sheenRoughnessMap.channel),specularMapUv:Se&&v(C.specularMap.channel),specularColorMapUv:je&&v(C.specularColorMap.channel),specularIntensityMapUv:qe&&v(C.specularIntensityMap.channel),transmissionMapUv:Re&&v(C.transmissionMap.channel),thicknessMapUv:Ye&&v(C.thicknessMap.channel),alphaMapUv:ze&&v(C.alphaMap.channel),vertexTangents:!!te.attributes.tangent&&(Q||fe),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!te.attributes.color&&te.attributes.color.itemSize===4,vertexUv1s:Pe,vertexUv2s:Me,vertexUv3s:Ve,pointsUvs:X.isPoints===!0&&!!te.attributes.uv&&(z||ze),fog:!!L,useFog:C.fog===!0,fogExp2:L&&L.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:m,skinning:X.isSkinnedMesh===!0,morphTargets:te.morphAttributes.position!==void 0,morphNormals:te.morphAttributes.normal!==void 0,morphColors:te.morphAttributes.color!==void 0,morphTargetsCount:K,morphTextureStride:ne,numDirLights:F.directional.length,numPointLights:F.point.length,numSpotLights:F.spot.length,numSpotLightMaps:F.spotLightMap.length,numRectAreaLights:F.rectArea.length,numHemiLights:F.hemi.length,numDirLightShadows:F.directionalShadowMap.length,numPointLightShadows:F.pointShadowMap.length,numSpotLightShadows:F.spotShadowMap.length,numSpotLightShadowsWithMaps:F.numSpotLightShadowsWithMaps,numLightProbes:F.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:C.dithering,shadowMapEnabled:t.shadowMap.enabled&&$.length>0,shadowMapType:t.shadowMap.type,toneMapping:tt,useLegacyLights:t._useLegacyLights,decodeVideoTexture:z&&C.map.isVideoTexture===!0&&$r.getTransfer(C.map.colorSpace)===ua,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===ku,flipSided:C.side===Po,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionDerivatives:$e&&C.extensions.derivatives===!0,extensionFragDepth:$e&&C.extensions.fragDepth===!0,extensionDrawBuffers:$e&&C.extensions.drawBuffers===!0,extensionShaderTextureLOD:$e&&C.extensions.shaderTextureLOD===!0,rendererExtensionFragDepth:u||r.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||r.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||r.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()}}function g(C){const F=[];if(C.shaderID?F.push(C.shaderID):(F.push(C.customVertexShaderID),F.push(C.customFragmentShaderID)),C.defines!==void 0)for(const $ in C.defines)F.push($),F.push(C.defines[$]);return C.isRawShaderMaterial===!1&&(_(F,C),k(F,C),F.push(t.outputColorSpace)),F.push(C.customProgramCacheKey),F.join()}function _(C,F){C.push(F.precision),C.push(F.outputColorSpace),C.push(F.envMapMode),C.push(F.envMapCubeUVHeight),C.push(F.mapUv),C.push(F.alphaMapUv),C.push(F.lightMapUv),C.push(F.aoMapUv),C.push(F.bumpMapUv),C.push(F.normalMapUv),C.push(F.displacementMapUv),C.push(F.emissiveMapUv),C.push(F.metalnessMapUv),C.push(F.roughnessMapUv),C.push(F.anisotropyMapUv),C.push(F.clearcoatMapUv),C.push(F.clearcoatNormalMapUv),C.push(F.clearcoatRoughnessMapUv),C.push(F.iridescenceMapUv),C.push(F.iridescenceThicknessMapUv),C.push(F.sheenColorMapUv),C.push(F.sheenRoughnessMapUv),C.push(F.specularMapUv),C.push(F.specularColorMapUv),C.push(F.specularIntensityMapUv),C.push(F.transmissionMapUv),C.push(F.thicknessMapUv),C.push(F.combine),C.push(F.fogExp2),C.push(F.sizeAttenuation),C.push(F.morphTargetsCount),C.push(F.morphAttributeCount),C.push(F.numDirLights),C.push(F.numPointLights),C.push(F.numSpotLights),C.push(F.numSpotLightMaps),C.push(F.numHemiLights),C.push(F.numRectAreaLights),C.push(F.numDirLightShadows),C.push(F.numPointLightShadows),C.push(F.numSpotLightShadows),C.push(F.numSpotLightShadowsWithMaps),C.push(F.numLightProbes),C.push(F.shadowMapType),C.push(F.toneMapping),C.push(F.numClippingPlanes),C.push(F.numClipIntersection),C.push(F.depthPacking)}function k(C,F){l.disableAll(),F.isWebGL2&&l.enable(0),F.supportsVertexTextures&&l.enable(1),F.instancing&&l.enable(2),F.instancingColor&&l.enable(3),F.matcap&&l.enable(4),F.envMap&&l.enable(5),F.normalMapObjectSpace&&l.enable(6),F.normalMapTangentSpace&&l.enable(7),F.clearcoat&&l.enable(8),F.iridescence&&l.enable(9),F.alphaTest&&l.enable(10),F.vertexColors&&l.enable(11),F.vertexAlphas&&l.enable(12),F.vertexUv1s&&l.enable(13),F.vertexUv2s&&l.enable(14),F.vertexUv3s&&l.enable(15),F.vertexTangents&&l.enable(16),F.anisotropy&&l.enable(17),F.alphaHash&&l.enable(18),F.batching&&l.enable(19),C.push(l.mask),l.disableAll(),F.fog&&l.enable(0),F.useFog&&l.enable(1),F.flatShading&&l.enable(2),F.logarithmicDepthBuffer&&l.enable(3),F.skinning&&l.enable(4),F.morphTargets&&l.enable(5),F.morphNormals&&l.enable(6),F.morphColors&&l.enable(7),F.premultipliedAlpha&&l.enable(8),F.shadowMapEnabled&&l.enable(9),F.useLegacyLights&&l.enable(10),F.doubleSided&&l.enable(11),F.flipSided&&l.enable(12),F.useDepthPacking&&l.enable(13),F.dithering&&l.enable(14),F.transmission&&l.enable(15),F.sheen&&l.enable(16),F.opaque&&l.enable(17),F.pointsUvs&&l.enable(18),F.decodeVideoTexture&&l.enable(19),C.push(l.mask)}function P(C){const F=y[C.type];let $;if(F){const I=wo[F];$=qO.clone(I.uniforms)}else $=C.uniforms;return $}function N(C,F){let $;for(let I=0,X=d.length;I<X;I++){const L=d[I];if(L.cacheKey===F){$=L,++$.usedTimes;break}}return $===void 0&&($=new UAe(t,F,C,s),d.push($)),$}function M(C){if(--C.usedTimes===0){const F=d.indexOf(C);d[F]=d[d.length-1],d.pop(),C.destroy()}}function A(C){c.remove(C)}function T(){c.dispose()}return{getParameters:b,getProgramCacheKey:g,getUniforms:P,acquireProgram:N,releaseProgram:M,releaseShaderCache:A,programs:d,dispose:T}}function VAe(){let t=new WeakMap;function e(s){let o=t.get(s);return o===void 0&&(o={},t.set(s,o)),o}function n(s){t.delete(s)}function r(s,o,l){t.get(s)[o]=l}function i(){t=new WeakMap}return{get:e,remove:n,update:r,dispose:i}}function GAe(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 Yq(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 Xq(){const t=[];let e=0;const n=[],r=[],i=[];function s(){e=0,n.length=0,r.length=0,i.length=0}function o(m,p,f,y,v,b){let g=t[e];return g===void 0?(g={id:m.id,object:m,geometry:p,material:f,groupOrder:y,renderOrder:m.renderOrder,z:v,group:b},t[e]=g):(g.id=m.id,g.object=m,g.geometry=p,g.material=f,g.groupOrder=y,g.renderOrder=m.renderOrder,g.z=v,g.group=b),e++,g}function l(m,p,f,y,v,b){const g=o(m,p,f,y,v,b);f.transmission>0?r.push(g):f.transparent===!0?i.push(g):n.push(g)}function c(m,p,f,y,v,b){const g=o(m,p,f,y,v,b);f.transmission>0?r.unshift(g):f.transparent===!0?i.unshift(g):n.unshift(g)}function d(m,p){n.length>1&&n.sort(m||GAe),r.length>1&&r.sort(p||Yq),i.length>1&&i.sort(p||Yq)}function u(){for(let m=e,p=t.length;m<p;m++){const f=t[m];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:r,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function WAe(){let t=new WeakMap;function e(r,i){const s=t.get(r);let o;return s===void 0?(o=new Xq,t.set(r,[o])):i>=s.length?(o=new Xq,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function KAe(){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 ot,color:new An};break;case"SpotLight":n={position:new ot,direction:new ot,color:new An,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new ot,color:new An,distance:0,decay:0};break;case"HemisphereLight":n={direction:new ot,skyColor:new An,groundColor:new An};break;case"RectAreaLight":n={color:new An,position:new ot,halfWidth:new ot,halfHeight:new ot};break}return t[e.id]=n,n}}}function YAe(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Hn};break;case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Hn};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Hn,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let XAe=0;function QAe(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function ZAe(t,e){const n=new KAe,r=YAe(),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 ot);const s=new ot,o=new oa,l=new oa;function c(u,m){let p=0,f=0,y=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let v=0,b=0,g=0,_=0,k=0,P=0,N=0,M=0,A=0,T=0,C=0;u.sort(QAe);const F=m===!0?Math.PI:1;for(let I=0,X=u.length;I<X;I++){const L=u[I],te=L.color,ae=L.intensity,ee=L.distance,me=L.shadow&&L.shadow.map?L.shadow.map.texture:null;if(L.isAmbientLight)p+=te.r*ae*F,f+=te.g*ae*F,y+=te.b*ae*F;else if(L.isLightProbe){for(let le=0;le<9;le++)i.probe[le].addScaledVector(L.sh.coefficients[le],ae);C++}else if(L.isDirectionalLight){const le=n.get(L);if(le.color.copy(L.color).multiplyScalar(L.intensity*F),L.castShadow){const ue=L.shadow,K=r.get(L);K.shadowBias=ue.bias,K.shadowNormalBias=ue.normalBias,K.shadowRadius=ue.radius,K.shadowMapSize=ue.mapSize,i.directionalShadow[v]=K,i.directionalShadowMap[v]=me,i.directionalShadowMatrix[v]=L.shadow.matrix,P++}i.directional[v]=le,v++}else if(L.isSpotLight){const le=n.get(L);le.position.setFromMatrixPosition(L.matrixWorld),le.color.copy(te).multiplyScalar(ae*F),le.distance=ee,le.coneCos=Math.cos(L.angle),le.penumbraCos=Math.cos(L.angle*(1-L.penumbra)),le.decay=L.decay,i.spot[g]=le;const ue=L.shadow;if(L.map&&(i.spotLightMap[A]=L.map,A++,ue.updateMatrices(L),L.castShadow&&T++),i.spotLightMatrix[g]=ue.matrix,L.castShadow){const K=r.get(L);K.shadowBias=ue.bias,K.shadowNormalBias=ue.normalBias,K.shadowRadius=ue.radius,K.shadowMapSize=ue.mapSize,i.spotShadow[g]=K,i.spotShadowMap[g]=me,M++}g++}else if(L.isRectAreaLight){const le=n.get(L);le.color.copy(te).multiplyScalar(ae),le.halfWidth.set(L.width*.5,0,0),le.halfHeight.set(0,L.height*.5,0),i.rectArea[_]=le,_++}else if(L.isPointLight){const le=n.get(L);if(le.color.copy(L.color).multiplyScalar(L.intensity*F),le.distance=L.distance,le.decay=L.decay,L.castShadow){const ue=L.shadow,K=r.get(L);K.shadowBias=ue.bias,K.shadowNormalBias=ue.normalBias,K.shadowRadius=ue.radius,K.shadowMapSize=ue.mapSize,K.shadowCameraNear=ue.camera.near,K.shadowCameraFar=ue.camera.far,i.pointShadow[b]=K,i.pointShadowMap[b]=me,i.pointShadowMatrix[b]=L.shadow.matrix,N++}i.point[b]=le,b++}else if(L.isHemisphereLight){const le=n.get(L);le.skyColor.copy(L.color).multiplyScalar(ae*F),le.groundColor.copy(L.groundColor).multiplyScalar(ae*F),i.hemi[k]=le,k++}}_>0&&(e.isWebGL2||t.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Yt.LTC_FLOAT_1,i.rectAreaLTC2=Yt.LTC_FLOAT_2):t.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=Yt.LTC_HALF_1,i.rectAreaLTC2=Yt.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]=y;const $=i.hash;($.directionalLength!==v||$.pointLength!==b||$.spotLength!==g||$.rectAreaLength!==_||$.hemiLength!==k||$.numDirectionalShadows!==P||$.numPointShadows!==N||$.numSpotShadows!==M||$.numSpotMaps!==A||$.numLightProbes!==C)&&(i.directional.length=v,i.spot.length=g,i.rectArea.length=_,i.point.length=b,i.hemi.length=k,i.directionalShadow.length=P,i.directionalShadowMap.length=P,i.pointShadow.length=N,i.pointShadowMap.length=N,i.spotShadow.length=M,i.spotShadowMap.length=M,i.directionalShadowMatrix.length=P,i.pointShadowMatrix.length=N,i.spotLightMatrix.length=M+A-T,i.spotLightMap.length=A,i.numSpotLightShadowsWithMaps=T,i.numLightProbes=C,$.directionalLength=v,$.pointLength=b,$.spotLength=g,$.rectAreaLength=_,$.hemiLength=k,$.numDirectionalShadows=P,$.numPointShadows=N,$.numSpotShadows=M,$.numSpotMaps=A,$.numLightProbes=C,i.version=XAe++)}function d(u,m){let p=0,f=0,y=0,v=0,b=0;const g=m.matrixWorldInverse;for(let _=0,k=u.length;_<k;_++){const P=u[_];if(P.isDirectionalLight){const N=i.directional[p];N.direction.setFromMatrixPosition(P.matrixWorld),s.setFromMatrixPosition(P.target.matrixWorld),N.direction.sub(s),N.direction.transformDirection(g),p++}else if(P.isSpotLight){const N=i.spot[y];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(g),N.direction.setFromMatrixPosition(P.matrixWorld),s.setFromMatrixPosition(P.target.matrixWorld),N.direction.sub(s),N.direction.transformDirection(g),y++}else if(P.isRectAreaLight){const N=i.rectArea[v];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(g),l.identity(),o.copy(P.matrixWorld),o.premultiply(g),l.extractRotation(o),N.halfWidth.set(P.width*.5,0,0),N.halfHeight.set(0,P.height*.5,0),N.halfWidth.applyMatrix4(l),N.halfHeight.applyMatrix4(l),v++}else if(P.isPointLight){const N=i.point[f];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(g),f++}else if(P.isHemisphereLight){const N=i.hemi[b];N.direction.setFromMatrixPosition(P.matrixWorld),N.direction.transformDirection(g),b++}}}return{setup:c,setupView:d,state:i}}function Qq(t,e){const n=new ZAe(t,e),r=[],i=[];function s(){r.length=0,i.length=0}function o(m){r.push(m)}function l(m){i.push(m)}function c(m){n.setup(r,m)}function d(m){n.setupView(r,m)}return{init:s,state:{lightsArray:r,shadowsArray:i,lights:n},setupLights:c,setupLightsView:d,pushLight:o,pushShadow:l}}function JAe(t,e){let n=new WeakMap;function r(s,o=0){const l=n.get(s);let c;return l===void 0?(c=new Qq(t,e),n.set(s,[c])):o>=l.length?(c=new Qq(t,e),l.push(c)):c=l[o],c}function i(){n=new WeakMap}return{get:r,dispose:i}}class eMe extends sy{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=zke,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 tMe extends sy{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 nMe=`void main() {
  7390. gl_Position = vec4( position, 1.0 );
  7391. }`,rMe=`uniform sampler2D shadow_pass;
  7392. uniform vec2 resolution;
  7393. uniform float radius;
  7394. #include <packing>
  7395. void main() {
  7396. const float samples = float( VSM_SAMPLES );
  7397. float mean = 0.0;
  7398. float squared_mean = 0.0;
  7399. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  7400. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  7401. for ( float i = 0.0; i < samples; i ++ ) {
  7402. float uvOffset = uvStart + i * uvStride;
  7403. #ifdef HORIZONTAL_PASS
  7404. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  7405. mean += distribution.x;
  7406. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  7407. #else
  7408. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  7409. mean += depth;
  7410. squared_mean += depth * depth;
  7411. #endif
  7412. }
  7413. mean = mean / samples;
  7414. squared_mean = squared_mean / samples;
  7415. float std_dev = sqrt( squared_mean - mean * mean );
  7416. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  7417. }`;function aMe(t,e,n){let r=new LP;const i=new Hn,s=new Hn,o=new Gr,l=new eMe({depthPacking:Uke}),c=new tMe,d={},u=n.maxTextureSize,m={[Gh]:Po,[Po]:Gh,[ku]:ku},p=new Wh({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Hn},radius:{value:4}},vertexShader:nMe,fragmentShader:rMe}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const y=new Rs;y.setAttribute("position",new al(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Ac(y,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=SZ;let g=this.type;this.render=function(N,M,A){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||N.length===0)return;const T=t.getRenderTarget(),C=t.getActiveCubeFace(),F=t.getActiveMipmapLevel(),$=t.state;$.setBlending(Rh),$.buffers.color.setClear(1,1,1,1),$.buffers.depth.setTest(!0),$.setScissorTest(!1);const I=g!==xu&&this.type===xu,X=g===xu&&this.type!==xu;for(let L=0,te=N.length;L<te;L++){const ae=N[L],ee=ae.shadow;if(ee===void 0){console.warn("THREE.WebGLShadowMap:",ae,"has no shadow.");continue}if(ee.autoUpdate===!1&&ee.needsUpdate===!1)continue;i.copy(ee.mapSize);const me=ee.getFrameExtents();if(i.multiply(me),s.copy(ee.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/me.x),i.x=s.x*me.x,ee.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/me.y),i.y=s.y*me.y,ee.mapSize.y=s.y)),ee.map===null||I===!0||X===!0){const ue=this.type!==xu?{minFilter:ns,magFilter:ns}:{};ee.map!==null&&ee.map.dispose(),ee.map=new Vf(i.x,i.y,ue),ee.map.texture.name=ae.name+".shadowMap",ee.camera.updateProjectionMatrix()}t.setRenderTarget(ee.map),t.clear();const le=ee.getViewportCount();for(let ue=0;ue<le;ue++){const K=ee.getViewport(ue);o.set(s.x*K.x,s.y*K.y,s.x*K.z,s.y*K.w),$.viewport(o),ee.updateMatrices(ae,ue),r=ee.getFrustum(),P(M,A,ee.camera,ae,this.type)}ee.isPointLightShadow!==!0&&this.type===xu&&_(ee,A),ee.needsUpdate=!1}g=this.type,b.needsUpdate=!1,t.setRenderTarget(T,C,F)};function _(N,M){const A=e.update(v);p.defines.VSM_SAMPLES!==N.blurSamples&&(p.defines.VSM_SAMPLES=N.blurSamples,f.defines.VSM_SAMPLES=N.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),N.mapPass===null&&(N.mapPass=new Vf(i.x,i.y)),p.uniforms.shadow_pass.value=N.map.texture,p.uniforms.resolution.value=N.mapSize,p.uniforms.radius.value=N.radius,t.setRenderTarget(N.mapPass),t.clear(),t.renderBufferDirect(M,null,A,p,v,null),f.uniforms.shadow_pass.value=N.mapPass.texture,f.uniforms.resolution.value=N.mapSize,f.uniforms.radius.value=N.radius,t.setRenderTarget(N.map),t.clear(),t.renderBufferDirect(M,null,A,f,v,null)}function k(N,M,A,T){let C=null;const F=A.isPointLight===!0?N.customDistanceMaterial:N.customDepthMaterial;if(F!==void 0)C=F;else if(C=A.isPointLight===!0?c:l,t.localClippingEnabled&&M.clipShadows===!0&&Array.isArray(M.clippingPlanes)&&M.clippingPlanes.length!==0||M.displacementMap&&M.displacementScale!==0||M.alphaMap&&M.alphaTest>0||M.map&&M.alphaTest>0){const $=C.uuid,I=M.uuid;let X=d[$];X===void 0&&(X={},d[$]=X);let L=X[I];L===void 0&&(L=C.clone(),X[I]=L),C=L}if(C.visible=M.visible,C.wireframe=M.wireframe,T===xu?C.side=M.shadowSide!==null?M.shadowSide:M.side:C.side=M.shadowSide!==null?M.shadowSide:m[M.side],C.alphaMap=M.alphaMap,C.alphaTest=M.alphaTest,C.map=M.map,C.clipShadows=M.clipShadows,C.clippingPlanes=M.clippingPlanes,C.clipIntersection=M.clipIntersection,C.displacementMap=M.displacementMap,C.displacementScale=M.displacementScale,C.displacementBias=M.displacementBias,C.wireframeLinewidth=M.wireframeLinewidth,C.linewidth=M.linewidth,A.isPointLight===!0&&C.isMeshDistanceMaterial===!0){const $=t.properties.get(C);$.light=A}return C}function P(N,M,A,T,C){if(N.visible===!1)return;if(N.layers.test(M.layers)&&(N.isMesh||N.isLine||N.isPoints)&&(N.castShadow||N.receiveShadow&&C===xu)&&(!N.frustumCulled||r.intersectsObject(N))){N.modelViewMatrix.multiplyMatrices(A.matrixWorldInverse,N.matrixWorld);const I=e.update(N),X=N.material;if(Array.isArray(X)){const L=I.groups;for(let te=0,ae=L.length;te<ae;te++){const ee=L[te],me=X[ee.materialIndex];if(me&&me.visible){const le=k(N,me,T,C);N.onBeforeShadow(t,N,M,A,I,le,ee),t.renderBufferDirect(A,null,I,le,N,ee),N.onAfterShadow(t,N,M,A,I,le,ee)}}}else if(X.visible){const L=k(N,X,T,C);N.onBeforeShadow(t,N,M,A,I,L,null),t.renderBufferDirect(A,null,I,L,N,null),N.onAfterShadow(t,N,M,A,I,L,null)}}const $=N.children;for(let I=0,X=$.length;I<X;I++)P($[I],M,A,T,C)}}function iMe(t,e,n){const r=n.isWebGL2;function i(){let Ne=!1;const Ge=new Gr;let $e=null;const Pe=new Gr(0,0,0,0);return{setMask:function(Me){$e!==Me&&!Ne&&(t.colorMask(Me,Me,Me,Me),$e=Me)},setLocked:function(Me){Ne=Me},setClear:function(Me,Ve,tt,ut,xt){xt===!0&&(Me*=ut,Ve*=ut,tt*=ut),Ge.set(Me,Ve,tt,ut),Pe.equals(Ge)===!1&&(t.clearColor(Me,Ve,tt,ut),Pe.copy(Ge))},reset:function(){Ne=!1,$e=null,Pe.set(-1,0,0,0)}}}function s(){let Ne=!1,Ge=null,$e=null,Pe=null;return{setTest:function(Me){Me?j(t.DEPTH_TEST):z(t.DEPTH_TEST)},setMask:function(Me){Ge!==Me&&!Ne&&(t.depthMask(Me),Ge=Me)},setFunc:function(Me){if($e!==Me){switch(Me){case gke:t.depthFunc(t.NEVER);break;case bke:t.depthFunc(t.ALWAYS);break;case xke:t.depthFunc(t.LESS);break;case hN:t.depthFunc(t.LEQUAL);break;case yke:t.depthFunc(t.EQUAL);break;case vke:t.depthFunc(t.GEQUAL);break;case wke:t.depthFunc(t.GREATER);break;case Ske:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}$e=Me}},setLocked:function(Me){Ne=Me},setClear:function(Me){Pe!==Me&&(t.clearDepth(Me),Pe=Me)},reset:function(){Ne=!1,Ge=null,$e=null,Pe=null}}}function o(){let Ne=!1,Ge=null,$e=null,Pe=null,Me=null,Ve=null,tt=null,ut=null,xt=null;return{setTest:function(wt){Ne||(wt?j(t.STENCIL_TEST):z(t.STENCIL_TEST))},setMask:function(wt){Ge!==wt&&!Ne&&(t.stencilMask(wt),Ge=wt)},setFunc:function(wt,Ht,Xt){($e!==wt||Pe!==Ht||Me!==Xt)&&(t.stencilFunc(wt,Ht,Xt),$e=wt,Pe=Ht,Me=Xt)},setOp:function(wt,Ht,Xt){(Ve!==wt||tt!==Ht||ut!==Xt)&&(t.stencilOp(wt,Ht,Xt),Ve=wt,tt=Ht,ut=Xt)},setLocked:function(wt){Ne=wt},setClear:function(wt){xt!==wt&&(t.clearStencil(wt),xt=wt)},reset:function(){Ne=!1,Ge=null,$e=null,Pe=null,Me=null,Ve=null,tt=null,ut=null,xt=null}}}const l=new i,c=new s,d=new o,u=new WeakMap,m=new WeakMap;let p={},f={},y=new WeakMap,v=[],b=null,g=!1,_=null,k=null,P=null,N=null,M=null,A=null,T=null,C=new An(0,0,0),F=0,$=!1,I=null,X=null,L=null,te=null,ae=null;const ee=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let me=!1,le=0;const ue=t.getParameter(t.VERSION);ue.indexOf("WebGL")!==-1?(le=parseFloat(/^WebGL (\d)/.exec(ue)[1]),me=le>=1):ue.indexOf("OpenGL ES")!==-1&&(le=parseFloat(/^OpenGL ES (\d)/.exec(ue)[1]),me=le>=2);let K=null,ne={};const oe=t.getParameter(t.SCISSOR_BOX),be=t.getParameter(t.VIEWPORT),_e=new Gr().fromArray(oe),B=new Gr().fromArray(be);function Y(Ne,Ge,$e,Pe){const Me=new Uint8Array(4),Ve=t.createTexture();t.bindTexture(Ne,Ve),t.texParameteri(Ne,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Ne,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let tt=0;tt<$e;tt++)r&&(Ne===t.TEXTURE_3D||Ne===t.TEXTURE_2D_ARRAY)?t.texImage3D(Ge,0,t.RGBA,1,1,Pe,0,t.RGBA,t.UNSIGNED_BYTE,Me):t.texImage2D(Ge+tt,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Me);return Ve}const D={};D[t.TEXTURE_2D]=Y(t.TEXTURE_2D,t.TEXTURE_2D,1),D[t.TEXTURE_CUBE_MAP]=Y(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),r&&(D[t.TEXTURE_2D_ARRAY]=Y(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),D[t.TEXTURE_3D]=Y(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),l.setClear(0,0,0,1),c.setClear(1),d.setClear(0),j(t.DEPTH_TEST),c.setFunc(hN),J(!1),ie(DH),j(t.CULL_FACE),Q(Rh);function j(Ne){p[Ne]!==!0&&(t.enable(Ne),p[Ne]=!0)}function z(Ne){p[Ne]!==!1&&(t.disable(Ne),p[Ne]=!1)}function W(Ne,Ge){return f[Ne]!==Ge?(t.bindFramebuffer(Ne,Ge),f[Ne]=Ge,r&&(Ne===t.DRAW_FRAMEBUFFER&&(f[t.FRAMEBUFFER]=Ge),Ne===t.FRAMEBUFFER&&(f[t.DRAW_FRAMEBUFFER]=Ge)),!0):!1}function q(Ne,Ge){let $e=v,Pe=!1;if(Ne)if($e=y.get(Ge),$e===void 0&&($e=[],y.set(Ge,$e)),Ne.isWebGLMultipleRenderTargets){const Me=Ne.texture;if($e.length!==Me.length||$e[0]!==t.COLOR_ATTACHMENT0){for(let Ve=0,tt=Me.length;Ve<tt;Ve++)$e[Ve]=t.COLOR_ATTACHMENT0+Ve;$e.length=Me.length,Pe=!0}}else $e[0]!==t.COLOR_ATTACHMENT0&&($e[0]=t.COLOR_ATTACHMENT0,Pe=!0);else $e[0]!==t.BACK&&($e[0]=t.BACK,Pe=!0);Pe&&(n.isWebGL2?t.drawBuffers($e):e.get("WEBGL_draw_buffers").drawBuffersWEBGL($e))}function de(Ne){return b!==Ne?(t.useProgram(Ne),b=Ne,!0):!1}const O={[ef]:t.FUNC_ADD,[tke]:t.FUNC_SUBTRACT,[nke]:t.FUNC_REVERSE_SUBTRACT};if(r)O[OH]=t.MIN,O[IH]=t.MAX;else{const Ne=e.get("EXT_blend_minmax");Ne!==null&&(O[OH]=Ne.MIN_EXT,O[IH]=Ne.MAX_EXT)}const G={[rke]:t.ZERO,[ake]:t.ONE,[ike]:t.SRC_COLOR,[zF]:t.SRC_ALPHA,[uke]:t.SRC_ALPHA_SATURATE,[cke]:t.DST_COLOR,[oke]:t.DST_ALPHA,[ske]:t.ONE_MINUS_SRC_COLOR,[UF]:t.ONE_MINUS_SRC_ALPHA,[dke]:t.ONE_MINUS_DST_COLOR,[lke]:t.ONE_MINUS_DST_ALPHA,[mke]:t.CONSTANT_COLOR,[hke]:t.ONE_MINUS_CONSTANT_COLOR,[pke]:t.CONSTANT_ALPHA,[fke]:t.ONE_MINUS_CONSTANT_ALPHA};function Q(Ne,Ge,$e,Pe,Me,Ve,tt,ut,xt,wt){if(Ne===Rh){g===!0&&(z(t.BLEND),g=!1);return}if(g===!1&&(j(t.BLEND),g=!0),Ne!==eke){if(Ne!==_||wt!==$){if((k!==ef||M!==ef)&&(t.blendEquation(t.FUNC_ADD),k=ef,M=ef),wt)switch(Ne){case sx:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FH:t.blendFunc(t.ONE,t.ONE);break;case RH:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case LH:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",Ne);break}else switch(Ne){case sx:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FH:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case RH:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case LH:t.blendFunc(t.ZERO,t.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",Ne);break}P=null,N=null,A=null,T=null,C.set(0,0,0),F=0,_=Ne,$=wt}return}Me=Me||Ge,Ve=Ve||$e,tt=tt||Pe,(Ge!==k||Me!==M)&&(t.blendEquationSeparate(O[Ge],O[Me]),k=Ge,M=Me),($e!==P||Pe!==N||Ve!==A||tt!==T)&&(t.blendFuncSeparate(G[$e],G[Pe],G[Ve],G[tt]),P=$e,N=Pe,A=Ve,T=tt),(ut.equals(C)===!1||xt!==F)&&(t.blendColor(ut.r,ut.g,ut.b,xt),C.copy(ut),F=xt),_=Ne,$=!1}function V(Ne,Ge){Ne.side===ku?z(t.CULL_FACE):j(t.CULL_FACE);let $e=Ne.side===Po;Ge&&($e=!$e),J($e),Ne.blending===sx&&Ne.transparent===!1?Q(Rh):Q(Ne.blending,Ne.blendEquation,Ne.blendSrc,Ne.blendDst,Ne.blendEquationAlpha,Ne.blendSrcAlpha,Ne.blendDstAlpha,Ne.blendColor,Ne.blendAlpha,Ne.premultipliedAlpha),c.setFunc(Ne.depthFunc),c.setTest(Ne.depthTest),c.setMask(Ne.depthWrite),l.setMask(Ne.colorWrite);const Pe=Ne.stencilWrite;d.setTest(Pe),Pe&&(d.setMask(Ne.stencilWriteMask),d.setFunc(Ne.stencilFunc,Ne.stencilRef,Ne.stencilFuncMask),d.setOp(Ne.stencilFail,Ne.stencilZFail,Ne.stencilZPass)),fe(Ne.polygonOffset,Ne.polygonOffsetFactor,Ne.polygonOffsetUnits),Ne.alphaToCoverage===!0?j(t.SAMPLE_ALPHA_TO_COVERAGE):z(t.SAMPLE_ALPHA_TO_COVERAGE)}function J(Ne){I!==Ne&&(Ne?t.frontFace(t.CW):t.frontFace(t.CCW),I=Ne)}function ie(Ne){Ne!==Q1e?(j(t.CULL_FACE),Ne!==X&&(Ne===DH?t.cullFace(t.BACK):Ne===Z1e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):z(t.CULL_FACE),X=Ne}function he(Ne){Ne!==L&&(me&&t.lineWidth(Ne),L=Ne)}function fe(Ne,Ge,$e){Ne?(j(t.POLYGON_OFFSET_FILL),(te!==Ge||ae!==$e)&&(t.polygonOffset(Ge,$e),te=Ge,ae=$e)):z(t.POLYGON_OFFSET_FILL)}function se(Ne){Ne?j(t.SCISSOR_TEST):z(t.SCISSOR_TEST)}function U(Ne){Ne===void 0&&(Ne=t.TEXTURE0+ee-1),K!==Ne&&(t.activeTexture(Ne),K=Ne)}function R(Ne,Ge,$e){$e===void 0&&(K===null?$e=t.TEXTURE0+ee-1:$e=K);let Pe=ne[$e];Pe===void 0&&(Pe={type:void 0,texture:void 0},ne[$e]=Pe),(Pe.type!==Ne||Pe.texture!==Ge)&&(K!==$e&&(t.activeTexture($e),K=$e),t.bindTexture(Ne,Ge||D[Ne]),Pe.type=Ne,Pe.texture=Ge)}function re(){const Ne=ne[K];Ne!==void 0&&Ne.type!==void 0&&(t.bindTexture(Ne.type,null),Ne.type=void 0,Ne.texture=void 0)}function xe(){try{t.compressedTexImage2D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function we(){try{t.compressedTexImage3D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function ye(){try{t.texSubImage2D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function Ae(){try{t.texSubImage3D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function ve(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function Te(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function Fe(){try{t.texStorage2D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function Ee(){try{t.texStorage3D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function Se(){try{t.texImage2D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function je(){try{t.texImage3D.apply(t,arguments)}catch(Ne){console.error("THREE.WebGLState:",Ne)}}function qe(Ne){_e.equals(Ne)===!1&&(t.scissor(Ne.x,Ne.y,Ne.z,Ne.w),_e.copy(Ne))}function Re(Ne){B.equals(Ne)===!1&&(t.viewport(Ne.x,Ne.y,Ne.z,Ne.w),B.copy(Ne))}function Ye(Ne,Ge){let $e=m.get(Ge);$e===void 0&&($e=new WeakMap,m.set(Ge,$e));let Pe=$e.get(Ne);Pe===void 0&&(Pe=t.getUniformBlockIndex(Ge,Ne.name),$e.set(Ne,Pe))}function ce(Ne,Ge){const Pe=m.get(Ge).get(Ne);u.get(Ge)!==Pe&&(t.uniformBlockBinding(Ge,Pe,Ne.__bindingPointIndex),u.set(Ge,Pe))}function ze(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),r===!0&&(t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),p={},K=null,ne={},f={},y=new WeakMap,v=[],b=null,g=!1,_=null,k=null,P=null,N=null,M=null,A=null,T=null,C=new An(0,0,0),F=0,$=!1,I=null,X=null,L=null,te=null,ae=null,_e.set(0,0,t.canvas.width,t.canvas.height),B.set(0,0,t.canvas.width,t.canvas.height),l.reset(),c.reset(),d.reset()}return{buffers:{color:l,depth:c,stencil:d},enable:j,disable:z,bindFramebuffer:W,drawBuffers:q,useProgram:de,setBlending:Q,setMaterial:V,setFlipSided:J,setCullFace:ie,setLineWidth:he,setPolygonOffset:fe,setScissorTest:se,activeTexture:U,bindTexture:R,unbindTexture:re,compressedTexImage2D:xe,compressedTexImage3D:we,texImage2D:Se,texImage3D:je,updateUBOMapping:Ye,uniformBlockBinding:ce,texStorage2D:Fe,texStorage3D:Ee,texSubImage2D:ye,texSubImage3D:Ae,compressedTexSubImage2D:ve,compressedTexSubImage3D:Te,scissor:qe,viewport:Re,reset:ze}}function sMe(t,e,n,r,i,s,o){const l=i.isWebGL2,c=i.maxTextures,d=i.maxCubemapSize,u=i.maxTextureSize,m=i.maxSamples,p=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,f=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),y=new WeakMap;let v;const b=new WeakMap;let g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(U,R){return g?new OffscreenCanvas(U,R):xN("canvas")}function k(U,R,re,xe){let we=1;if((U.width>xe||U.height>xe)&&(we=xe/Math.max(U.width,U.height)),we<1||R===!0)if(typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&U instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&U instanceof ImageBitmap){const ye=R?bN:Math.floor,Ae=ye(we*U.width),ve=ye(we*U.height);v===void 0&&(v=_(Ae,ve));const Te=re?_(Ae,ve):v;return Te.width=Ae,Te.height=ve,Te.getContext("2d").drawImage(U,0,0,Ae,ve),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+U.width+"x"+U.height+") to ("+Ae+"x"+ve+")."),Te}else return"data"in U&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+U.width+"x"+U.height+")."),U;return U}function P(U){return WF(U.width)&&WF(U.height)}function N(U){return l?!1:U.wrapS!==wc||U.wrapT!==wc||U.minFilter!==ns&&U.minFilter!==Ll}function M(U,R){return U.generateMipmaps&&R&&U.minFilter!==ns&&U.minFilter!==Ll}function A(U){t.generateMipmap(U)}function T(U,R,re,xe,we=!1){if(l===!1)return R;if(U!==null){if(t[U]!==void 0)return t[U];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+U+"'")}let ye=R;if(R===t.RED&&(re===t.FLOAT&&(ye=t.R32F),re===t.HALF_FLOAT&&(ye=t.R16F),re===t.UNSIGNED_BYTE&&(ye=t.R8)),R===t.RED_INTEGER&&(re===t.UNSIGNED_BYTE&&(ye=t.R8UI),re===t.UNSIGNED_SHORT&&(ye=t.R16UI),re===t.UNSIGNED_INT&&(ye=t.R32UI),re===t.BYTE&&(ye=t.R8I),re===t.SHORT&&(ye=t.R16I),re===t.INT&&(ye=t.R32I)),R===t.RG&&(re===t.FLOAT&&(ye=t.RG32F),re===t.HALF_FLOAT&&(ye=t.RG16F),re===t.UNSIGNED_BYTE&&(ye=t.RG8)),R===t.RGBA){const Ae=we?pN:$r.getTransfer(xe);re===t.FLOAT&&(ye=t.RGBA32F),re===t.HALF_FLOAT&&(ye=t.RGBA16F),re===t.UNSIGNED_BYTE&&(ye=Ae===ua?t.SRGB8_ALPHA8:t.RGBA8),re===t.UNSIGNED_SHORT_4_4_4_4&&(ye=t.RGBA4),re===t.UNSIGNED_SHORT_5_5_5_1&&(ye=t.RGB5_A1)}return(ye===t.R16F||ye===t.R32F||ye===t.RG16F||ye===t.RG32F||ye===t.RGBA16F||ye===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function C(U,R,re){return M(U,re)===!0||U.isFramebufferTexture&&U.minFilter!==ns&&U.minFilter!==Ll?Math.log2(Math.max(R.width,R.height))+1:U.mipmaps!==void 0&&U.mipmaps.length>0?U.mipmaps.length:U.isCompressedTexture&&Array.isArray(U.image)?R.mipmaps.length:1}function F(U){return U===ns||U===zH||U===Wj?t.NEAREST:t.LINEAR}function $(U){const R=U.target;R.removeEventListener("dispose",$),X(R),R.isVideoTexture&&y.delete(R)}function I(U){const R=U.target;R.removeEventListener("dispose",I),te(R)}function X(U){const R=r.get(U);if(R.__webglInit===void 0)return;const re=U.source,xe=b.get(re);if(xe){const we=xe[R.__cacheKey];we.usedTimes--,we.usedTimes===0&&L(U),Object.keys(xe).length===0&&b.delete(re)}r.remove(U)}function L(U){const R=r.get(U);t.deleteTexture(R.__webglTexture);const re=U.source,xe=b.get(re);delete xe[R.__cacheKey],o.memory.textures--}function te(U){const R=U.texture,re=r.get(U),xe=r.get(R);if(xe.__webglTexture!==void 0&&(t.deleteTexture(xe.__webglTexture),o.memory.textures--),U.depthTexture&&U.depthTexture.dispose(),U.isWebGLCubeRenderTarget)for(let we=0;we<6;we++){if(Array.isArray(re.__webglFramebuffer[we]))for(let ye=0;ye<re.__webglFramebuffer[we].length;ye++)t.deleteFramebuffer(re.__webglFramebuffer[we][ye]);else t.deleteFramebuffer(re.__webglFramebuffer[we]);re.__webglDepthbuffer&&t.deleteRenderbuffer(re.__webglDepthbuffer[we])}else{if(Array.isArray(re.__webglFramebuffer))for(let we=0;we<re.__webglFramebuffer.length;we++)t.deleteFramebuffer(re.__webglFramebuffer[we]);else t.deleteFramebuffer(re.__webglFramebuffer);if(re.__webglDepthbuffer&&t.deleteRenderbuffer(re.__webglDepthbuffer),re.__webglMultisampledFramebuffer&&t.deleteFramebuffer(re.__webglMultisampledFramebuffer),re.__webglColorRenderbuffer)for(let we=0;we<re.__webglColorRenderbuffer.length;we++)re.__webglColorRenderbuffer[we]&&t.deleteRenderbuffer(re.__webglColorRenderbuffer[we]);re.__webglDepthRenderbuffer&&t.deleteRenderbuffer(re.__webglDepthRenderbuffer)}if(U.isWebGLMultipleRenderTargets)for(let we=0,ye=R.length;we<ye;we++){const Ae=r.get(R[we]);Ae.__webglTexture&&(t.deleteTexture(Ae.__webglTexture),o.memory.textures--),r.remove(R[we])}r.remove(R),r.remove(U)}let ae=0;function ee(){ae=0}function me(){const U=ae;return U>=c&&console.warn("THREE.WebGLTextures: Trying to use "+U+" texture units while this GPU supports only "+c),ae+=1,U}function le(U){const R=[];return R.push(U.wrapS),R.push(U.wrapT),R.push(U.wrapR||0),R.push(U.magFilter),R.push(U.minFilter),R.push(U.anisotropy),R.push(U.internalFormat),R.push(U.format),R.push(U.type),R.push(U.generateMipmaps),R.push(U.premultiplyAlpha),R.push(U.flipY),R.push(U.unpackAlignment),R.push(U.colorSpace),R.join()}function ue(U,R){const re=r.get(U);if(U.isVideoTexture&&fe(U),U.isRenderTargetTexture===!1&&U.version>0&&re.__version!==U.version){const xe=U.image;if(xe===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(xe.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{j(re,U,R);return}}n.bindTexture(t.TEXTURE_2D,re.__webglTexture,t.TEXTURE0+R)}function K(U,R){const re=r.get(U);if(U.version>0&&re.__version!==U.version){j(re,U,R);return}n.bindTexture(t.TEXTURE_2D_ARRAY,re.__webglTexture,t.TEXTURE0+R)}function ne(U,R){const re=r.get(U);if(U.version>0&&re.__version!==U.version){j(re,U,R);return}n.bindTexture(t.TEXTURE_3D,re.__webglTexture,t.TEXTURE0+R)}function oe(U,R){const re=r.get(U);if(U.version>0&&re.__version!==U.version){z(re,U,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,re.__webglTexture,t.TEXTURE0+R)}const be={[qF]:t.REPEAT,[wc]:t.CLAMP_TO_EDGE,[$F]:t.MIRRORED_REPEAT},_e={[ns]:t.NEAREST,[zH]:t.NEAREST_MIPMAP_NEAREST,[Wj]:t.NEAREST_MIPMAP_LINEAR,[Ll]:t.LINEAR,[Mke]:t.LINEAR_MIPMAP_NEAREST,[q0]:t.LINEAR_MIPMAP_LINEAR},B={[Hke]:t.NEVER,[Kke]:t.ALWAYS,[qke]:t.LESS,[DZ]:t.LEQUAL,[$ke]:t.EQUAL,[Wke]:t.GEQUAL,[Vke]:t.GREATER,[Gke]:t.NOTEQUAL};function Y(U,R,re){if(re?(t.texParameteri(U,t.TEXTURE_WRAP_S,be[R.wrapS]),t.texParameteri(U,t.TEXTURE_WRAP_T,be[R.wrapT]),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,be[R.wrapR]),t.texParameteri(U,t.TEXTURE_MAG_FILTER,_e[R.magFilter]),t.texParameteri(U,t.TEXTURE_MIN_FILTER,_e[R.minFilter])):(t.texParameteri(U,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(U,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(R.wrapS!==wc||R.wrapT!==wc)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(U,t.TEXTURE_MAG_FILTER,F(R.magFilter)),t.texParameteri(U,t.TEXTURE_MIN_FILTER,F(R.minFilter)),R.minFilter!==ns&&R.minFilter!==Ll&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),R.compareFunction&&(t.texParameteri(U,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(U,t.TEXTURE_COMPARE_FUNC,B[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const xe=e.get("EXT_texture_filter_anisotropic");if(R.magFilter===ns||R.minFilter!==Wj&&R.minFilter!==q0||R.type===ju&&e.has("OES_texture_float_linear")===!1||l===!1&&R.type===$0&&e.has("OES_texture_half_float_linear")===!1)return;(R.anisotropy>1||r.get(R).__currentAnisotropy)&&(t.texParameterf(U,xe.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy)}}function D(U,R){let re=!1;U.__webglInit===void 0&&(U.__webglInit=!0,R.addEventListener("dispose",$));const xe=R.source;let we=b.get(xe);we===void 0&&(we={},b.set(xe,we));const ye=le(R);if(ye!==U.__cacheKey){we[ye]===void 0&&(we[ye]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,re=!0),we[ye].usedTimes++;const Ae=we[U.__cacheKey];Ae!==void 0&&(we[U.__cacheKey].usedTimes--,Ae.usedTimes===0&&L(R)),U.__cacheKey=ye,U.__webglTexture=we[ye].texture}return re}function j(U,R,re){let xe=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(xe=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(xe=t.TEXTURE_3D);const we=D(U,R),ye=R.source;n.bindTexture(xe,U.__webglTexture,t.TEXTURE0+re);const Ae=r.get(ye);if(ye.version!==Ae.__version||we===!0){n.activeTexture(t.TEXTURE0+re);const ve=$r.getPrimaries($r.workingColorSpace),Te=R.colorSpace===Il?null:$r.getPrimaries(R.colorSpace),Fe=R.colorSpace===Il||ve===Te?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,Fe);const Ee=N(R)&&P(R.image)===!1;let Se=k(R.image,Ee,!1,u);Se=se(R,Se);const je=P(Se)||l,qe=s.convert(R.format,R.colorSpace);let Re=s.convert(R.type),Ye=T(R.internalFormat,qe,Re,R.colorSpace,R.isVideoTexture);Y(xe,R,je);let ce;const ze=R.mipmaps,Ne=l&&R.isVideoTexture!==!0&&Ye!==MZ,Ge=Ae.__version===void 0||we===!0,$e=C(R,Se,je);if(R.isDepthTexture)Ye=t.DEPTH_COMPONENT,l?R.type===ju?Ye=t.DEPTH_COMPONENT32F:R.type===vh?Ye=t.DEPTH_COMPONENT24:R.type===wf?Ye=t.DEPTH24_STENCIL8:Ye=t.DEPTH_COMPONENT16:R.type===ju&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),R.format===Sf&&Ye===t.DEPTH_COMPONENT&&R.type!==zO&&R.type!==vh&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),R.type=vh,Re=s.convert(R.type)),R.format===Mx&&Ye===t.DEPTH_COMPONENT&&(Ye=t.DEPTH_STENCIL,R.type!==wf&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),R.type=wf,Re=s.convert(R.type))),Ge&&(Ne?n.texStorage2D(t.TEXTURE_2D,1,Ye,Se.width,Se.height):n.texImage2D(t.TEXTURE_2D,0,Ye,Se.width,Se.height,0,qe,Re,null));else if(R.isDataTexture)if(ze.length>0&&je){Ne&&Ge&&n.texStorage2D(t.TEXTURE_2D,$e,Ye,ze[0].width,ze[0].height);for(let Pe=0,Me=ze.length;Pe<Me;Pe++)ce=ze[Pe],Ne?n.texSubImage2D(t.TEXTURE_2D,Pe,0,0,ce.width,ce.height,qe,Re,ce.data):n.texImage2D(t.TEXTURE_2D,Pe,Ye,ce.width,ce.height,0,qe,Re,ce.data);R.generateMipmaps=!1}else Ne?(Ge&&n.texStorage2D(t.TEXTURE_2D,$e,Ye,Se.width,Se.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,Se.width,Se.height,qe,Re,Se.data)):n.texImage2D(t.TEXTURE_2D,0,Ye,Se.width,Se.height,0,qe,Re,Se.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){Ne&&Ge&&n.texStorage3D(t.TEXTURE_2D_ARRAY,$e,Ye,ze[0].width,ze[0].height,Se.depth);for(let Pe=0,Me=ze.length;Pe<Me;Pe++)ce=ze[Pe],R.format!==Ol?qe!==null?Ne?n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Pe,0,0,0,ce.width,ce.height,Se.depth,qe,ce.data,0,0):n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Pe,Ye,ce.width,ce.height,Se.depth,0,ce.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ne?n.texSubImage3D(t.TEXTURE_2D_ARRAY,Pe,0,0,0,ce.width,ce.height,Se.depth,qe,Re,ce.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Pe,Ye,ce.width,ce.height,Se.depth,0,qe,Re,ce.data)}else{Ne&&Ge&&n.texStorage2D(t.TEXTURE_2D,$e,Ye,ze[0].width,ze[0].height);for(let Pe=0,Me=ze.length;Pe<Me;Pe++)ce=ze[Pe],R.format!==Ol?qe!==null?Ne?n.compressedTexSubImage2D(t.TEXTURE_2D,Pe,0,0,ce.width,ce.height,qe,ce.data):n.compressedTexImage2D(t.TEXTURE_2D,Pe,Ye,ce.width,ce.height,0,ce.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ne?n.texSubImage2D(t.TEXTURE_2D,Pe,0,0,ce.width,ce.height,qe,Re,ce.data):n.texImage2D(t.TEXTURE_2D,Pe,Ye,ce.width,ce.height,0,qe,Re,ce.data)}else if(R.isDataArrayTexture)Ne?(Ge&&n.texStorage3D(t.TEXTURE_2D_ARRAY,$e,Ye,Se.width,Se.height,Se.depth),n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Se.width,Se.height,Se.depth,qe,Re,Se.data)):n.texImage3D(t.TEXTURE_2D_ARRAY,0,Ye,Se.width,Se.height,Se.depth,0,qe,Re,Se.data);else if(R.isData3DTexture)Ne?(Ge&&n.texStorage3D(t.TEXTURE_3D,$e,Ye,Se.width,Se.height,Se.depth),n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Se.width,Se.height,Se.depth,qe,Re,Se.data)):n.texImage3D(t.TEXTURE_3D,0,Ye,Se.width,Se.height,Se.depth,0,qe,Re,Se.data);else if(R.isFramebufferTexture){if(Ge)if(Ne)n.texStorage2D(t.TEXTURE_2D,$e,Ye,Se.width,Se.height);else{let Pe=Se.width,Me=Se.height;for(let Ve=0;Ve<$e;Ve++)n.texImage2D(t.TEXTURE_2D,Ve,Ye,Pe,Me,0,qe,Re,null),Pe>>=1,Me>>=1}}else if(ze.length>0&&je){Ne&&Ge&&n.texStorage2D(t.TEXTURE_2D,$e,Ye,ze[0].width,ze[0].height);for(let Pe=0,Me=ze.length;Pe<Me;Pe++)ce=ze[Pe],Ne?n.texSubImage2D(t.TEXTURE_2D,Pe,0,0,qe,Re,ce):n.texImage2D(t.TEXTURE_2D,Pe,Ye,qe,Re,ce);R.generateMipmaps=!1}else Ne?(Ge&&n.texStorage2D(t.TEXTURE_2D,$e,Ye,Se.width,Se.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,qe,Re,Se)):n.texImage2D(t.TEXTURE_2D,0,Ye,qe,Re,Se);M(R,je)&&A(xe),Ae.__version=ye.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function z(U,R,re){if(R.image.length!==6)return;const xe=D(U,R),we=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,U.__webglTexture,t.TEXTURE0+re);const ye=r.get(we);if(we.version!==ye.__version||xe===!0){n.activeTexture(t.TEXTURE0+re);const Ae=$r.getPrimaries($r.workingColorSpace),ve=R.colorSpace===Il?null:$r.getPrimaries(R.colorSpace),Te=R.colorSpace===Il||Ae===ve?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Te);const Fe=R.isCompressedTexture||R.image[0].isCompressedTexture,Ee=R.image[0]&&R.image[0].isDataTexture,Se=[];for(let Pe=0;Pe<6;Pe++)!Fe&&!Ee?Se[Pe]=k(R.image[Pe],!1,!0,d):Se[Pe]=Ee?R.image[Pe].image:R.image[Pe],Se[Pe]=se(R,Se[Pe]);const je=Se[0],qe=P(je)||l,Re=s.convert(R.format,R.colorSpace),Ye=s.convert(R.type),ce=T(R.internalFormat,Re,Ye,R.colorSpace),ze=l&&R.isVideoTexture!==!0,Ne=ye.__version===void 0||xe===!0;let Ge=C(R,je,qe);Y(t.TEXTURE_CUBE_MAP,R,qe);let $e;if(Fe){ze&&Ne&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Ge,ce,je.width,je.height);for(let Pe=0;Pe<6;Pe++){$e=Se[Pe].mipmaps;for(let Me=0;Me<$e.length;Me++){const Ve=$e[Me];R.format!==Ol?Re!==null?ze?n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,0,0,Ve.width,Ve.height,Re,Ve.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,ce,Ve.width,Ve.height,0,Ve.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):ze?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,0,0,Ve.width,Ve.height,Re,Ye,Ve.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me,ce,Ve.width,Ve.height,0,Re,Ye,Ve.data)}}}else{$e=R.mipmaps,ze&&Ne&&($e.length>0&&Ge++,n.texStorage2D(t.TEXTURE_CUBE_MAP,Ge,ce,Se[0].width,Se[0].height));for(let Pe=0;Pe<6;Pe++)if(Ee){ze?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,0,0,Se[Pe].width,Se[Pe].height,Re,Ye,Se[Pe].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,ce,Se[Pe].width,Se[Pe].height,0,Re,Ye,Se[Pe].data);for(let Me=0;Me<$e.length;Me++){const tt=$e[Me].image[Pe].image;ze?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,0,0,tt.width,tt.height,Re,Ye,tt.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,ce,tt.width,tt.height,0,Re,Ye,tt.data)}}else{ze?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,0,0,Re,Ye,Se[Pe]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,0,ce,Re,Ye,Se[Pe]);for(let Me=0;Me<$e.length;Me++){const Ve=$e[Me];ze?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,0,0,Re,Ye,Ve.image[Pe]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Pe,Me+1,ce,Re,Ye,Ve.image[Pe])}}}M(R,qe)&&A(t.TEXTURE_CUBE_MAP),ye.__version=we.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function W(U,R,re,xe,we,ye){const Ae=s.convert(re.format,re.colorSpace),ve=s.convert(re.type),Te=T(re.internalFormat,Ae,ve,re.colorSpace);if(!r.get(R).__hasExternalTextures){const Ee=Math.max(1,R.width>>ye),Se=Math.max(1,R.height>>ye);we===t.TEXTURE_3D||we===t.TEXTURE_2D_ARRAY?n.texImage3D(we,ye,Te,Ee,Se,R.depth,0,Ae,ve,null):n.texImage2D(we,ye,Te,Ee,Se,0,Ae,ve,null)}n.bindFramebuffer(t.FRAMEBUFFER,U),he(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,xe,we,r.get(re).__webglTexture,0,ie(R)):(we===t.TEXTURE_2D||we>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&we<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,xe,we,r.get(re).__webglTexture,ye),n.bindFramebuffer(t.FRAMEBUFFER,null)}function q(U,R,re){if(t.bindRenderbuffer(t.RENDERBUFFER,U),R.depthBuffer&&!R.stencilBuffer){let xe=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(re||he(R)){const we=R.depthTexture;we&&we.isDepthTexture&&(we.type===ju?xe=t.DEPTH_COMPONENT32F:we.type===vh&&(xe=t.DEPTH_COMPONENT24));const ye=ie(R);he(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ye,xe,R.width,R.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,ye,xe,R.width,R.height)}else t.renderbufferStorage(t.RENDERBUFFER,xe,R.width,R.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,U)}else if(R.depthBuffer&&R.stencilBuffer){const xe=ie(R);re&&he(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,xe,t.DEPTH24_STENCIL8,R.width,R.height):he(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,xe,t.DEPTH24_STENCIL8,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,U)}else{const xe=R.isWebGLMultipleRenderTargets===!0?R.texture:[R.texture];for(let we=0;we<xe.length;we++){const ye=xe[we],Ae=s.convert(ye.format,ye.colorSpace),ve=s.convert(ye.type),Te=T(ye.internalFormat,Ae,ve,ye.colorSpace),Fe=ie(R);re&&he(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Fe,Te,R.width,R.height):he(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Fe,Te,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Te,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function de(U,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,U),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!r.get(R.depthTexture).__webglTexture||R.depthTexture.image.width!==R.width||R.depthTexture.image.height!==R.height)&&(R.depthTexture.image.width=R.width,R.depthTexture.image.height=R.height,R.depthTexture.needsUpdate=!0),ue(R.depthTexture,0);const xe=r.get(R.depthTexture).__webglTexture,we=ie(R);if(R.depthTexture.format===Sf)he(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,xe,0,we):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,xe,0);else if(R.depthTexture.format===Mx)he(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,xe,0,we):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,xe,0);else throw new Error("Unknown depthTexture format")}function O(U){const R=r.get(U),re=U.isWebGLCubeRenderTarget===!0;if(U.depthTexture&&!R.__autoAllocateDepthBuffer){if(re)throw new Error("target.depthTexture not supported in Cube render targets");de(R.__webglFramebuffer,U)}else if(re){R.__webglDepthbuffer=[];for(let xe=0;xe<6;xe++)n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[xe]),R.__webglDepthbuffer[xe]=t.createRenderbuffer(),q(R.__webglDepthbuffer[xe],U,!1)}else n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer=t.createRenderbuffer(),q(R.__webglDepthbuffer,U,!1);n.bindFramebuffer(t.FRAMEBUFFER,null)}function G(U,R,re){const xe=r.get(U);R!==void 0&&W(xe.__webglFramebuffer,U,U.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),re!==void 0&&O(U)}function Q(U){const R=U.texture,re=r.get(U),xe=r.get(R);U.addEventListener("dispose",I),U.isWebGLMultipleRenderTargets!==!0&&(xe.__webglTexture===void 0&&(xe.__webglTexture=t.createTexture()),xe.__version=R.version,o.memory.textures++);const we=U.isWebGLCubeRenderTarget===!0,ye=U.isWebGLMultipleRenderTargets===!0,Ae=P(U)||l;if(we){re.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(l&&R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer[ve]=[];for(let Te=0;Te<R.mipmaps.length;Te++)re.__webglFramebuffer[ve][Te]=t.createFramebuffer()}else re.__webglFramebuffer[ve]=t.createFramebuffer()}else{if(l&&R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer=[];for(let ve=0;ve<R.mipmaps.length;ve++)re.__webglFramebuffer[ve]=t.createFramebuffer()}else re.__webglFramebuffer=t.createFramebuffer();if(ye)if(i.drawBuffers){const ve=U.texture;for(let Te=0,Fe=ve.length;Te<Fe;Te++){const Ee=r.get(ve[Te]);Ee.__webglTexture===void 0&&(Ee.__webglTexture=t.createTexture(),o.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");if(l&&U.samples>0&&he(U)===!1){const ve=ye?R:[R];re.__webglMultisampledFramebuffer=t.createFramebuffer(),re.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,re.__webglMultisampledFramebuffer);for(let Te=0;Te<ve.length;Te++){const Fe=ve[Te];re.__webglColorRenderbuffer[Te]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,re.__webglColorRenderbuffer[Te]);const Ee=s.convert(Fe.format,Fe.colorSpace),Se=s.convert(Fe.type),je=T(Fe.internalFormat,Ee,Se,Fe.colorSpace,U.isXRRenderTarget===!0),qe=ie(U);t.renderbufferStorageMultisample(t.RENDERBUFFER,qe,je,U.width,U.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Te,t.RENDERBUFFER,re.__webglColorRenderbuffer[Te])}t.bindRenderbuffer(t.RENDERBUFFER,null),U.depthBuffer&&(re.__webglDepthRenderbuffer=t.createRenderbuffer(),q(re.__webglDepthRenderbuffer,U,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(we){n.bindTexture(t.TEXTURE_CUBE_MAP,xe.__webglTexture),Y(t.TEXTURE_CUBE_MAP,R,Ae);for(let ve=0;ve<6;ve++)if(l&&R.mipmaps&&R.mipmaps.length>0)for(let Te=0;Te<R.mipmaps.length;Te++)W(re.__webglFramebuffer[ve][Te],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,Te);else W(re.__webglFramebuffer[ve],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);M(R,Ae)&&A(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(ye){const ve=U.texture;for(let Te=0,Fe=ve.length;Te<Fe;Te++){const Ee=ve[Te],Se=r.get(Ee);n.bindTexture(t.TEXTURE_2D,Se.__webglTexture),Y(t.TEXTURE_2D,Ee,Ae),W(re.__webglFramebuffer,U,Ee,t.COLOR_ATTACHMENT0+Te,t.TEXTURE_2D,0),M(Ee,Ae)&&A(t.TEXTURE_2D)}n.unbindTexture()}else{let ve=t.TEXTURE_2D;if((U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(l?ve=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),n.bindTexture(ve,xe.__webglTexture),Y(ve,R,Ae),l&&R.mipmaps&&R.mipmaps.length>0)for(let Te=0;Te<R.mipmaps.length;Te++)W(re.__webglFramebuffer[Te],U,R,t.COLOR_ATTACHMENT0,ve,Te);else W(re.__webglFramebuffer,U,R,t.COLOR_ATTACHMENT0,ve,0);M(R,Ae)&&A(ve),n.unbindTexture()}U.depthBuffer&&O(U)}function V(U){const R=P(U)||l,re=U.isWebGLMultipleRenderTargets===!0?U.texture:[U.texture];for(let xe=0,we=re.length;xe<we;xe++){const ye=re[xe];if(M(ye,R)){const Ae=U.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,ve=r.get(ye).__webglTexture;n.bindTexture(Ae,ve),A(Ae),n.unbindTexture()}}}function J(U){if(l&&U.samples>0&&he(U)===!1){const R=U.isWebGLMultipleRenderTargets?U.texture:[U.texture],re=U.width,xe=U.height;let we=t.COLOR_BUFFER_BIT;const ye=[],Ae=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ve=r.get(U),Te=U.isWebGLMultipleRenderTargets===!0;if(Te)for(let Fe=0;Fe<R.length;Fe++)n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,ve.__webglMultisampledFramebuffer),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ve.__webglFramebuffer);for(let Fe=0;Fe<R.length;Fe++){ye.push(t.COLOR_ATTACHMENT0+Fe),U.depthBuffer&&ye.push(Ae);const Ee=ve.__ignoreDepthValues!==void 0?ve.__ignoreDepthValues:!1;if(Ee===!1&&(U.depthBuffer&&(we|=t.DEPTH_BUFFER_BIT),U.stencilBuffer&&(we|=t.STENCIL_BUFFER_BIT)),Te&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,ve.__webglColorRenderbuffer[Fe]),Ee===!0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[Ae]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[Ae])),Te){const Se=r.get(R[Fe]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Se,0)}t.blitFramebuffer(0,0,re,xe,0,0,re,xe,we,t.NEAREST),f&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,ye)}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),Te)for(let Fe=0;Fe<R.length;Fe++){n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.RENDERBUFFER,ve.__webglColorRenderbuffer[Fe]);const Ee=r.get(R[Fe]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Fe,t.TEXTURE_2D,Ee,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ve.__webglMultisampledFramebuffer)}}function ie(U){return Math.min(m,U.samples)}function he(U){const R=r.get(U);return l&&U.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function fe(U){const R=o.render.frame;y.get(U)!==R&&(y.set(U,R),U.update())}function se(U,R){const re=U.colorSpace,xe=U.format,we=U.type;return U.isCompressedTexture===!0||U.isVideoTexture===!0||U.format===GF||re!==Qu&&re!==Il&&($r.getTransfer(re)===ua?l===!1?e.has("EXT_sRGB")===!0&&xe===Ol?(U.format=GF,U.minFilter=Ll,U.generateMipmaps=!1):R=LZ.sRGBToLinear(R):(xe!==Ol||we!==Oh)&&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=me,this.resetTextureUnits=ee,this.setTexture2D=ue,this.setTexture2DArray=K,this.setTexture3D=ne,this.setTextureCube=oe,this.rebindTextures=G,this.setupRenderTarget=Q,this.updateRenderTargetMipmap=V,this.updateMultisampleRenderTarget=J,this.setupDepthRenderbuffer=O,this.setupFrameBufferTexture=W,this.useMultisampledRTT=he}function oMe(t,e,n){const r=n.isWebGL2;function i(s,o=Il){let l;const c=$r.getTransfer(o);if(s===Oh)return t.UNSIGNED_BYTE;if(s===NZ)return t.UNSIGNED_SHORT_4_4_4_4;if(s===CZ)return t.UNSIGNED_SHORT_5_5_5_1;if(s===jke)return t.BYTE;if(s===Eke)return t.SHORT;if(s===zO)return t.UNSIGNED_SHORT;if(s===kZ)return t.INT;if(s===vh)return t.UNSIGNED_INT;if(s===ju)return t.FLOAT;if(s===$0)return r?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===Dke)return t.ALPHA;if(s===Ol)return t.RGBA;if(s===Fke)return t.LUMINANCE;if(s===Rke)return t.LUMINANCE_ALPHA;if(s===Sf)return t.DEPTH_COMPONENT;if(s===Mx)return t.DEPTH_STENCIL;if(s===GF)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===Lke)return t.RED;if(s===PZ)return t.RED_INTEGER;if(s===Oke)return t.RG;if(s===TZ)return t.RG_INTEGER;if(s===AZ)return t.RGBA_INTEGER;if(s===Kj||s===Yj||s===Xj||s===Qj)if(c===ua)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===Kj)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===Yj)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===Xj)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===Qj)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===Kj)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===Yj)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===Xj)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===Qj)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===UH||s===BH||s===HH||s===qH)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===UH)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===BH)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===HH)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===qH)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===MZ)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===$H||s===VH)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===$H)return c===ua?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===VH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===GH||s===WH||s===KH||s===YH||s===XH||s===QH||s===ZH||s===JH||s===eq||s===tq||s===nq||s===rq||s===aq||s===iq)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===GH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===WH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===KH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===YH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===XH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===QH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===ZH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===JH)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===eq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===tq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===nq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===rq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===aq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===iq)return c===ua?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===Zj||s===sq||s===oq)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===Zj)return c===ua?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===sq)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===oq)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===Ike||s===lq||s===cq||s===dq)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===Zj)return l.COMPRESSED_RED_RGTC1_EXT;if(s===lq)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===cq)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===dq)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===wf?r?t.UNSIGNED_INT_24_8:(l=e.get("WEBGL_depth_texture"),l!==null?l.UNSIGNED_INT_24_8_WEBGL:null):t[s]!==void 0?t[s]:null}return{convert:i}}class lMe extends Zo{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Gv extends Js{constructor(){super(),this.isGroup=!0,this.type="Group"}}const cMe={type:"move"};class wE{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Gv,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 Gv,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ot,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ot),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Gv,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ot,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ot),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let i=null,s=null,o=null;const l=this._targetRay,c=this._grip,d=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(d&&e.hand){o=!0;for(const v of e.hand.values()){const b=n.getJointPose(v,r),g=this._getHandJoint(d,v);b!==null&&(g.matrix.fromArray(b.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=b.radius),g.visible=b!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,y=.005;d.inputState.pinching&&p>f+y?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-y&&(d.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(l.matrix.fromArray(i.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,i.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(i.linearVelocity)):l.hasLinearVelocity=!1,i.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(i.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(cMe)))}return l!==null&&(l.visible=i!==null),c!==null&&(c.visible=s!==null),d!==null&&(d.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Gv;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}class dMe extends ug{constructor(e,n){super();const r=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,y=null;const v=n.getContextAttributes();let b=null,g=null;const _=[],k=[],P=new Hn;let N=null;const M=new Zo;M.layers.enable(1),M.viewport=new Gr;const A=new Zo;A.layers.enable(2),A.viewport=new Gr;const T=[M,A],C=new lMe;C.layers.enable(1),C.layers.enable(2);let F=null,$=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(oe){let be=_[oe];return be===void 0&&(be=new wE,_[oe]=be),be.getTargetRaySpace()},this.getControllerGrip=function(oe){let be=_[oe];return be===void 0&&(be=new wE,_[oe]=be),be.getGripSpace()},this.getHand=function(oe){let be=_[oe];return be===void 0&&(be=new wE,_[oe]=be),be.getHandSpace()};function I(oe){const be=k.indexOf(oe.inputSource);if(be===-1)return;const _e=_[be];_e!==void 0&&(_e.update(oe.inputSource,oe.frame,d||o),_e.dispatchEvent({type:oe.type,data:oe.inputSource}))}function X(){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",X),i.removeEventListener("inputsourceschange",L);for(let oe=0;oe<_.length;oe++){const be=k[oe];be!==null&&(k[oe]=null,_[oe].disconnect(be))}F=null,$=null,e.setRenderTarget(b),f=null,p=null,m=null,i=null,g=null,ne.stop(),r.isPresenting=!1,e.setPixelRatio(N),e.setSize(P.width,P.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(oe){s=oe,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(oe){l=oe,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||o},this.setReferenceSpace=function(oe){d=oe},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m},this.getFrame=function(){return y},this.getSession=function(){return i},this.setSession=async function(oe){if(i=oe,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",X),i.addEventListener("inputsourceschange",L),v.xrCompatible!==!0&&await n.makeXRCompatible(),N=e.getPixelRatio(),e.getSize(P),i.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const be={antialias:i.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,be),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),g=new Vf(f.framebufferWidth,f.framebufferHeight,{format:Ol,type:Oh,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let be=null,_e=null,B=null;v.depth&&(B=v.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,be=v.stencil?Mx:Sf,_e=v.stencil?wf:vh);const Y={colorFormat:n.RGBA8,depthFormat:B,scaleFactor:s};m=new XRWebGLBinding(i,n),p=m.createProjectionLayer(Y),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),g=new Vf(p.textureWidth,p.textureHeight,{format:Ol,type:Oh,depthTexture:new KZ(p.textureWidth,p.textureHeight,_e,void 0,void 0,void 0,void 0,void 0,void 0,be),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const D=e.properties.get(g);D.__ignoreDepthValues=p.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),ne.setContext(i),ne.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode};function L(oe){for(let be=0;be<oe.removed.length;be++){const _e=oe.removed[be],B=k.indexOf(_e);B>=0&&(k[B]=null,_[B].disconnect(_e))}for(let be=0;be<oe.added.length;be++){const _e=oe.added[be];let B=k.indexOf(_e);if(B===-1){for(let D=0;D<_.length;D++)if(D>=k.length){k.push(_e),B=D;break}else if(k[D]===null){k[D]=_e,B=D;break}if(B===-1)break}const Y=_[B];Y&&Y.connect(_e)}}const te=new ot,ae=new ot;function ee(oe,be,_e){te.setFromMatrixPosition(be.matrixWorld),ae.setFromMatrixPosition(_e.matrixWorld);const B=te.distanceTo(ae),Y=be.projectionMatrix.elements,D=_e.projectionMatrix.elements,j=Y[14]/(Y[10]-1),z=Y[14]/(Y[10]+1),W=(Y[9]+1)/Y[5],q=(Y[9]-1)/Y[5],de=(Y[8]-1)/Y[0],O=(D[8]+1)/D[0],G=j*de,Q=j*O,V=B/(-de+O),J=V*-de;be.matrixWorld.decompose(oe.position,oe.quaternion,oe.scale),oe.translateX(J),oe.translateZ(V),oe.matrixWorld.compose(oe.position,oe.quaternion,oe.scale),oe.matrixWorldInverse.copy(oe.matrixWorld).invert();const ie=j+V,he=z+V,fe=G-J,se=Q+(B-J),U=W*z/he*ie,R=q*z/he*ie;oe.projectionMatrix.makePerspective(fe,se,U,R,ie,he),oe.projectionMatrixInverse.copy(oe.projectionMatrix).invert()}function me(oe,be){be===null?oe.matrixWorld.copy(oe.matrix):oe.matrixWorld.multiplyMatrices(be.matrixWorld,oe.matrix),oe.matrixWorldInverse.copy(oe.matrixWorld).invert()}this.updateCamera=function(oe){if(i===null)return;C.near=A.near=M.near=oe.near,C.far=A.far=M.far=oe.far,(F!==C.near||$!==C.far)&&(i.updateRenderState({depthNear:C.near,depthFar:C.far}),F=C.near,$=C.far);const be=oe.parent,_e=C.cameras;me(C,be);for(let B=0;B<_e.length;B++)me(_e[B],be);_e.length===2?ee(C,M,A):C.projectionMatrix.copy(M.projectionMatrix),le(oe,C,be)};function le(oe,be,_e){_e===null?oe.matrix.copy(be.matrixWorld):(oe.matrix.copy(_e.matrixWorld),oe.matrix.invert(),oe.matrix.multiply(be.matrixWorld)),oe.matrix.decompose(oe.position,oe.quaternion,oe.scale),oe.updateMatrixWorld(!0),oe.projectionMatrix.copy(be.projectionMatrix),oe.projectionMatrixInverse.copy(be.projectionMatrixInverse),oe.isPerspectiveCamera&&(oe.fov=G0*2*Math.atan(1/oe.projectionMatrix.elements[5]),oe.zoom=1)}this.getCamera=function(){return C},this.getFoveation=function(){if(!(p===null&&f===null))return c},this.setFoveation=function(oe){c=oe,p!==null&&(p.fixedFoveation=oe),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=oe)};let ue=null;function K(oe,be){if(u=be.getViewerPose(d||o),y=be,u!==null){const _e=u.views;f!==null&&(e.setRenderTargetFramebuffer(g,f.framebuffer),e.setRenderTarget(g));let B=!1;_e.length!==C.cameras.length&&(C.cameras.length=0,B=!0);for(let Y=0;Y<_e.length;Y++){const D=_e[Y];let j=null;if(f!==null)j=f.getViewport(D);else{const W=m.getViewSubImage(p,D);j=W.viewport,Y===0&&(e.setRenderTargetTextures(g,W.colorTexture,p.ignoreDepthValues?void 0:W.depthStencilTexture),e.setRenderTarget(g))}let z=T[Y];z===void 0&&(z=new Zo,z.layers.enable(Y),z.viewport=new Gr,T[Y]=z),z.matrix.fromArray(D.transform.matrix),z.matrix.decompose(z.position,z.quaternion,z.scale),z.projectionMatrix.fromArray(D.projectionMatrix),z.projectionMatrixInverse.copy(z.projectionMatrix).invert(),z.viewport.set(j.x,j.y,j.width,j.height),Y===0&&(C.matrix.copy(z.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale)),B===!0&&C.cameras.push(z)}}for(let _e=0;_e<_.length;_e++){const B=k[_e],Y=_[_e];B!==null&&Y!==void 0&&Y.update(B,be,d||o)}ue&&ue(oe,be),be.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:be}),y=null}const ne=new WZ;ne.setAnimationLoop(K),this.setAnimationLoop=function(oe){ue=oe},this.dispose=function(){}}}function uMe(t,e){function n(b,g){b.matrixAutoUpdate===!0&&b.updateMatrix(),g.value.copy(b.matrix)}function r(b,g){g.color.getRGB(b.fogColor.value,$Z(t)),g.isFog?(b.fogNear.value=g.near,b.fogFar.value=g.far):g.isFogExp2&&(b.fogDensity.value=g.density)}function i(b,g,_,k,P){g.isMeshBasicMaterial||g.isMeshLambertMaterial?s(b,g):g.isMeshToonMaterial?(s(b,g),m(b,g)):g.isMeshPhongMaterial?(s(b,g),u(b,g)):g.isMeshStandardMaterial?(s(b,g),p(b,g),g.isMeshPhysicalMaterial&&f(b,g,P)):g.isMeshMatcapMaterial?(s(b,g),y(b,g)):g.isMeshDepthMaterial?s(b,g):g.isMeshDistanceMaterial?(s(b,g),v(b,g)):g.isMeshNormalMaterial?s(b,g):g.isLineBasicMaterial?(o(b,g),g.isLineDashedMaterial&&l(b,g)):g.isPointsMaterial?c(b,g,_,k):g.isSpriteMaterial?d(b,g):g.isShadowMaterial?(b.color.value.copy(g.color),b.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function s(b,g){b.opacity.value=g.opacity,g.color&&b.diffuse.value.copy(g.color),g.emissive&&b.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.bumpMap&&(b.bumpMap.value=g.bumpMap,n(g.bumpMap,b.bumpMapTransform),b.bumpScale.value=g.bumpScale,g.side===Po&&(b.bumpScale.value*=-1)),g.normalMap&&(b.normalMap.value=g.normalMap,n(g.normalMap,b.normalMapTransform),b.normalScale.value.copy(g.normalScale),g.side===Po&&b.normalScale.value.negate()),g.displacementMap&&(b.displacementMap.value=g.displacementMap,n(g.displacementMap,b.displacementMapTransform),b.displacementScale.value=g.displacementScale,b.displacementBias.value=g.displacementBias),g.emissiveMap&&(b.emissiveMap.value=g.emissiveMap,n(g.emissiveMap,b.emissiveMapTransform)),g.specularMap&&(b.specularMap.value=g.specularMap,n(g.specularMap,b.specularMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest);const _=e.get(g).envMap;if(_&&(b.envMap.value=_,b.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=g.reflectivity,b.ior.value=g.ior,b.refractionRatio.value=g.refractionRatio),g.lightMap){b.lightMap.value=g.lightMap;const k=t._useLegacyLights===!0?Math.PI:1;b.lightMapIntensity.value=g.lightMapIntensity*k,n(g.lightMap,b.lightMapTransform)}g.aoMap&&(b.aoMap.value=g.aoMap,b.aoMapIntensity.value=g.aoMapIntensity,n(g.aoMap,b.aoMapTransform))}function o(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform))}function l(b,g){b.dashSize.value=g.dashSize,b.totalSize.value=g.dashSize+g.gapSize,b.scale.value=g.scale}function c(b,g,_,k){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.size.value=g.size*_,b.scale.value=k*.5,g.map&&(b.map.value=g.map,n(g.map,b.uvTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function d(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.rotation.value=g.rotation,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function u(b,g){b.specular.value.copy(g.specular),b.shininess.value=Math.max(g.shininess,1e-4)}function m(b,g){g.gradientMap&&(b.gradientMap.value=g.gradientMap)}function p(b,g){b.metalness.value=g.metalness,g.metalnessMap&&(b.metalnessMap.value=g.metalnessMap,n(g.metalnessMap,b.metalnessMapTransform)),b.roughness.value=g.roughness,g.roughnessMap&&(b.roughnessMap.value=g.roughnessMap,n(g.roughnessMap,b.roughnessMapTransform)),e.get(g).envMap&&(b.envMapIntensity.value=g.envMapIntensity)}function f(b,g,_){b.ior.value=g.ior,g.sheen>0&&(b.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),b.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(b.sheenColorMap.value=g.sheenColorMap,n(g.sheenColorMap,b.sheenColorMapTransform)),g.sheenRoughnessMap&&(b.sheenRoughnessMap.value=g.sheenRoughnessMap,n(g.sheenRoughnessMap,b.sheenRoughnessMapTransform))),g.clearcoat>0&&(b.clearcoat.value=g.clearcoat,b.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(b.clearcoatMap.value=g.clearcoatMap,n(g.clearcoatMap,b.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,n(g.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(b.clearcoatNormalMap.value=g.clearcoatNormalMap,n(g.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===Po&&b.clearcoatNormalScale.value.negate())),g.iridescence>0&&(b.iridescence.value=g.iridescence,b.iridescenceIOR.value=g.iridescenceIOR,b.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(b.iridescenceMap.value=g.iridescenceMap,n(g.iridescenceMap,b.iridescenceMapTransform)),g.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=g.iridescenceThicknessMap,n(g.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),g.transmission>0&&(b.transmission.value=g.transmission,b.transmissionSamplerMap.value=_.texture,b.transmissionSamplerSize.value.set(_.width,_.height),g.transmissionMap&&(b.transmissionMap.value=g.transmissionMap,n(g.transmissionMap,b.transmissionMapTransform)),b.thickness.value=g.thickness,g.thicknessMap&&(b.thicknessMap.value=g.thicknessMap,n(g.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=g.attenuationDistance,b.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(b.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(b.anisotropyMap.value=g.anisotropyMap,n(g.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=g.specularIntensity,b.specularColor.value.copy(g.specularColor),g.specularColorMap&&(b.specularColorMap.value=g.specularColorMap,n(g.specularColorMap,b.specularColorMapTransform)),g.specularIntensityMap&&(b.specularIntensityMap.value=g.specularIntensityMap,n(g.specularIntensityMap,b.specularIntensityMapTransform))}function y(b,g){g.matcap&&(b.matcap.value=g.matcap)}function v(b,g){const _=e.get(g).light;b.referencePosition.value.setFromMatrixPosition(_.matrixWorld),b.nearDistance.value=_.shadow.camera.near,b.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function mMe(t,e,n,r){let i={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(_,k){const P=k.program;r.uniformBlockBinding(_,P)}function d(_,k){let P=i[_.id];P===void 0&&(y(_),P=u(_),i[_.id]=P,_.addEventListener("dispose",b));const N=k.program;r.updateUBOMapping(_,N);const M=e.render.frame;s[_.id]!==M&&(p(_),s[_.id]=M)}function u(_){const k=m();_.__bindingPointIndex=k;const P=t.createBuffer(),N=_.__size,M=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,P),t.bufferData(t.UNIFORM_BUFFER,N,M),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,k,P),P}function m(){for(let _=0;_<l;_++)if(o.indexOf(_)===-1)return o.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function p(_){const k=i[_.id],P=_.uniforms,N=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,k);for(let M=0,A=P.length;M<A;M++){const T=P[M];if(f(T,M,N)===!0){const C=T.__offset,F=Array.isArray(T.value)?T.value:[T.value];let $=0;for(let I=0;I<F.length;I++){const X=F[I],L=v(X);typeof X=="number"?(T.__data[0]=X,t.bufferSubData(t.UNIFORM_BUFFER,C+$,T.__data)):X.isMatrix3?(T.__data[0]=X.elements[0],T.__data[1]=X.elements[1],T.__data[2]=X.elements[2],T.__data[3]=X.elements[0],T.__data[4]=X.elements[3],T.__data[5]=X.elements[4],T.__data[6]=X.elements[5],T.__data[7]=X.elements[0],T.__data[8]=X.elements[6],T.__data[9]=X.elements[7],T.__data[10]=X.elements[8],T.__data[11]=X.elements[0]):(X.toArray(T.__data,$),$+=L.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,C,T.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(_,k,P){const N=_.value;if(P[k]===void 0){if(typeof N=="number")P[k]=N;else{const M=Array.isArray(N)?N:[N],A=[];for(let T=0;T<M.length;T++)A.push(M[T].clone());P[k]=A}return!0}else if(typeof N=="number"){if(P[k]!==N)return P[k]=N,!0}else{const M=Array.isArray(P[k])?P[k]:[P[k]],A=Array.isArray(N)?N:[N];for(let T=0;T<M.length;T++){const C=M[T];if(C.equals(A[T])===!1)return C.copy(A[T]),!0}}return!1}function y(_){const k=_.uniforms;let P=0;const N=16;let M=0;for(let A=0,T=k.length;A<T;A++){const C=k[A],F={boundary:0,storage:0},$=Array.isArray(C.value)?C.value:[C.value];for(let I=0,X=$.length;I<X;I++){const L=$[I],te=v(L);F.boundary+=te.boundary,F.storage+=te.storage}if(C.__data=new Float32Array(F.storage/Float32Array.BYTES_PER_ELEMENT),C.__offset=P,A>0){M=P%N;const I=N-M;M!==0&&I-F.boundary<0&&(P+=N-M,C.__offset=P)}P+=F.storage}return M=P%N,M>0&&(P+=N-M),_.__size=P,_.__cache={},this}function v(_){const k={boundary:0,storage:0};return typeof _=="number"?(k.boundary=4,k.storage=4):_.isVector2?(k.boundary=8,k.storage=8):_.isVector3||_.isColor?(k.boundary=16,k.storage=12):_.isVector4?(k.boundary=16,k.storage=16):_.isMatrix3?(k.boundary=48,k.storage=48):_.isMatrix4?(k.boundary=64,k.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),k}function b(_){const k=_.target;k.removeEventListener("dispose",b);const P=o.indexOf(k.__bindingPointIndex);o.splice(P,1),t.deleteBuffer(i[k.id]),delete i[k.id],delete s[k.id]}function g(){for(const _ in i)t.deleteBuffer(i[_]);o=[],i={},s={}}return{bind:c,update:d,dispose:g}}class YF{constructor(e={}){const{canvas:n=cNe(),context:r=null,depth:i=!0,stencil:s=!0,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:d=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:m=!1}=e;this.isWebGLRenderer=!0;let p;r!==null?p=r.getContextAttributes().alpha:p=o;const f=new Uint32Array(4),y=new Int32Array(4);let v=null,b=null;const g=[],_=[];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=rs,this._useLegacyLights=!1,this.toneMapping=Lh,this.toneMappingExposure=1;const k=this;let P=!1,N=0,M=0,A=null,T=-1,C=null;const F=new Gr,$=new Gr;let I=null;const X=new An(0);let L=0,te=n.width,ae=n.height,ee=1,me=null,le=null;const ue=new Gr(0,0,te,ae),K=new Gr(0,0,te,ae);let ne=!1;const oe=new LP;let be=!1,_e=!1,B=null;const Y=new oa,D=new Hn,j=new ot,z={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function W(){return A===null?ee:1}let q=r;function de(Ue,dt){for(let pt=0;pt<Ue.length;pt++){const De=Ue[pt],Le=n.getContext(De,dt);if(Le!==null)return Le}return null}try{const Ue={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${DP}`),n.addEventListener("webglcontextlost",ze,!1),n.addEventListener("webglcontextrestored",Ne,!1),n.addEventListener("webglcontextcreationerror",Ge,!1),q===null){const dt=["webgl2","webgl","experimental-webgl"];if(k.isWebGL1Renderer===!0&&dt.shift(),q=de(dt,Ue),q===null)throw de(dt)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&q instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),q.getShaderPrecisionFormat===void 0&&(q.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(Ue){throw console.error("THREE.WebGLRenderer: "+Ue.message),Ue}let O,G,Q,V,J,ie,he,fe,se,U,R,re,xe,we,ye,Ae,ve,Te,Fe,Ee,Se,je,qe,Re;function Ye(){O=new _Te(q),G=new gTe(q,O,e),O.init(G),je=new oMe(q,O,G),Q=new iMe(q,O,G),V=new CTe(q),J=new VAe,ie=new sMe(q,O,Q,J,G,je,V),he=new xTe(k),fe=new STe(k),se=new DNe(q,G),qe=new pTe(q,O,se,G),U=new kTe(q,se,V,qe),R=new MTe(q,U,se,V),Fe=new ATe(q,G,ie),Ae=new bTe(J),re=new $Ae(k,he,fe,O,G,qe,Ae),xe=new uMe(k,J),we=new WAe,ye=new JAe(O,G),Te=new hTe(k,he,fe,Q,R,p,c),ve=new aMe(k,R,G),Re=new mMe(q,V,G,Q),Ee=new fTe(q,O,V,G),Se=new NTe(q,O,V,G),V.programs=re.programs,k.capabilities=G,k.extensions=O,k.properties=J,k.renderLists=we,k.shadowMap=ve,k.state=Q,k.info=V}Ye();const ce=new dMe(k,q);this.xr=ce,this.getContext=function(){return q},this.getContextAttributes=function(){return q.getContextAttributes()},this.forceContextLoss=function(){const Ue=O.get("WEBGL_lose_context");Ue&&Ue.loseContext()},this.forceContextRestore=function(){const Ue=O.get("WEBGL_lose_context");Ue&&Ue.restoreContext()},this.getPixelRatio=function(){return ee},this.setPixelRatio=function(Ue){Ue!==void 0&&(ee=Ue,this.setSize(te,ae,!1))},this.getSize=function(Ue){return Ue.set(te,ae)},this.setSize=function(Ue,dt,pt=!0){if(ce.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}te=Ue,ae=dt,n.width=Math.floor(Ue*ee),n.height=Math.floor(dt*ee),pt===!0&&(n.style.width=Ue+"px",n.style.height=dt+"px"),this.setViewport(0,0,Ue,dt)},this.getDrawingBufferSize=function(Ue){return Ue.set(te*ee,ae*ee).floor()},this.setDrawingBufferSize=function(Ue,dt,pt){te=Ue,ae=dt,ee=pt,n.width=Math.floor(Ue*pt),n.height=Math.floor(dt*pt),this.setViewport(0,0,Ue,dt)},this.getCurrentViewport=function(Ue){return Ue.copy(F)},this.getViewport=function(Ue){return Ue.copy(ue)},this.setViewport=function(Ue,dt,pt,De){Ue.isVector4?ue.set(Ue.x,Ue.y,Ue.z,Ue.w):ue.set(Ue,dt,pt,De),Q.viewport(F.copy(ue).multiplyScalar(ee).floor())},this.getScissor=function(Ue){return Ue.copy(K)},this.setScissor=function(Ue,dt,pt,De){Ue.isVector4?K.set(Ue.x,Ue.y,Ue.z,Ue.w):K.set(Ue,dt,pt,De),Q.scissor($.copy(K).multiplyScalar(ee).floor())},this.getScissorTest=function(){return ne},this.setScissorTest=function(Ue){Q.setScissorTest(ne=Ue)},this.setOpaqueSort=function(Ue){me=Ue},this.setTransparentSort=function(Ue){le=Ue},this.getClearColor=function(Ue){return Ue.copy(Te.getClearColor())},this.setClearColor=function(){Te.setClearColor.apply(Te,arguments)},this.getClearAlpha=function(){return Te.getClearAlpha()},this.setClearAlpha=function(){Te.setClearAlpha.apply(Te,arguments)},this.clear=function(Ue=!0,dt=!0,pt=!0){let De=0;if(Ue){let Le=!1;if(A!==null){const at=A.texture.format;Le=at===AZ||at===TZ||at===PZ}if(Le){const at=A.texture.type,Ce=at===Oh||at===vh||at===zO||at===wf||at===NZ||at===CZ,We=Te.getClearColor(),Xe=Te.getClearAlpha(),Qe=We.r,Ze=We.g,rt=We.b;Ce?(f[0]=Qe,f[1]=Ze,f[2]=rt,f[3]=Xe,q.clearBufferuiv(q.COLOR,0,f)):(y[0]=Qe,y[1]=Ze,y[2]=rt,y[3]=Xe,q.clearBufferiv(q.COLOR,0,y))}else De|=q.COLOR_BUFFER_BIT}dt&&(De|=q.DEPTH_BUFFER_BIT),pt&&(De|=q.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),q.clear(De)},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",ze,!1),n.removeEventListener("webglcontextrestored",Ne,!1),n.removeEventListener("webglcontextcreationerror",Ge,!1),we.dispose(),ye.dispose(),J.dispose(),he.dispose(),fe.dispose(),R.dispose(),qe.dispose(),Re.dispose(),re.dispose(),ce.dispose(),ce.removeEventListener("sessionstart",xt),ce.removeEventListener("sessionend",wt),B&&(B.dispose(),B=null),Ht.stop()};function ze(Ue){Ue.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),P=!0}function Ne(){console.log("THREE.WebGLRenderer: Context Restored."),P=!1;const Ue=V.autoReset,dt=ve.enabled,pt=ve.autoUpdate,De=ve.needsUpdate,Le=ve.type;Ye(),V.autoReset=Ue,ve.enabled=dt,ve.autoUpdate=pt,ve.needsUpdate=De,ve.type=Le}function Ge(Ue){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",Ue.statusMessage)}function $e(Ue){const dt=Ue.target;dt.removeEventListener("dispose",$e),Pe(dt)}function Pe(Ue){Me(Ue),J.remove(Ue)}function Me(Ue){const dt=J.get(Ue).programs;dt!==void 0&&(dt.forEach(function(pt){re.releaseProgram(pt)}),Ue.isShaderMaterial&&re.releaseShaderCache(Ue))}this.renderBufferDirect=function(Ue,dt,pt,De,Le,at){dt===null&&(dt=z);const Ce=Le.isMesh&&Le.matrixWorld.determinant()<0,We=Mt(Ue,dt,pt,De,Le);Q.setMaterial(De,Ce);let Xe=pt.index,Qe=1;if(De.wireframe===!0){if(Xe=U.getWireframeAttribute(pt),Xe===void 0)return;Qe=2}const Ze=pt.drawRange,rt=pt.attributes.position;let bt=Ze.start*Qe,Pt=(Ze.start+Ze.count)*Qe;at!==null&&(bt=Math.max(bt,at.start*Qe),Pt=Math.min(Pt,(at.start+at.count)*Qe)),Xe!==null?(bt=Math.max(bt,0),Pt=Math.min(Pt,Xe.count)):rt!=null&&(bt=Math.max(bt,0),Pt=Math.min(Pt,rt.count));const vt=Pt-bt;if(vt<0||vt===1/0)return;qe.setup(Le,De,We,pt,Xe);let He,St=Ee;if(Xe!==null&&(He=se.get(Xe),St=Se,St.setIndex(He)),Le.isMesh)De.wireframe===!0?(Q.setLineWidth(De.wireframeLinewidth*W()),St.setMode(q.LINES)):St.setMode(q.TRIANGLES);else if(Le.isLine){let Ct=De.linewidth;Ct===void 0&&(Ct=1),Q.setLineWidth(Ct*W()),Le.isLineSegments?St.setMode(q.LINES):Le.isLineLoop?St.setMode(q.LINE_LOOP):St.setMode(q.LINE_STRIP)}else Le.isPoints?St.setMode(q.POINTS):Le.isSprite&&St.setMode(q.TRIANGLES);if(Le.isBatchedMesh)St.renderMultiDraw(Le._multiDrawStarts,Le._multiDrawCounts,Le._multiDrawCount);else if(Le.isInstancedMesh)St.renderInstances(bt,vt,Le.count);else if(pt.isInstancedBufferGeometry){const Ct=pt._maxInstanceCount!==void 0?pt._maxInstanceCount:1/0,Zt=Math.min(pt.instanceCount,Ct);St.renderInstances(bt,vt,Zt)}else St.render(bt,vt)};function Ve(Ue,dt,pt){Ue.transparent===!0&&Ue.side===ku&&Ue.forceSinglePass===!1?(Ue.side=Po,Ue.needsUpdate=!0,Ft(Ue,dt,pt),Ue.side=Gh,Ue.needsUpdate=!0,Ft(Ue,dt,pt),Ue.side=ku):Ft(Ue,dt,pt)}this.compile=function(Ue,dt,pt=null){pt===null&&(pt=Ue),b=ye.get(pt),b.init(),_.push(b),pt.traverseVisible(function(Le){Le.isLight&&Le.layers.test(dt.layers)&&(b.pushLight(Le),Le.castShadow&&b.pushShadow(Le))}),Ue!==pt&&Ue.traverseVisible(function(Le){Le.isLight&&Le.layers.test(dt.layers)&&(b.pushLight(Le),Le.castShadow&&b.pushShadow(Le))}),b.setupLights(k._useLegacyLights);const De=new Set;return Ue.traverse(function(Le){const at=Le.material;if(at)if(Array.isArray(at))for(let Ce=0;Ce<at.length;Ce++){const We=at[Ce];Ve(We,pt,Le),De.add(We)}else Ve(at,pt,Le),De.add(at)}),_.pop(),b=null,De},this.compileAsync=function(Ue,dt,pt=null){const De=this.compile(Ue,dt,pt);return new Promise(Le=>{function at(){if(De.forEach(function(Ce){J.get(Ce).currentProgram.isReady()&&De.delete(Ce)}),De.size===0){Le(Ue);return}setTimeout(at,10)}O.get("KHR_parallel_shader_compile")!==null?at():setTimeout(at,10)})};let tt=null;function ut(Ue){tt&&tt(Ue)}function xt(){Ht.stop()}function wt(){Ht.start()}const Ht=new WZ;Ht.setAnimationLoop(ut),typeof self<"u"&&Ht.setContext(self),this.setAnimationLoop=function(Ue){tt=Ue,ce.setAnimationLoop(Ue),Ue===null?Ht.stop():Ht.start()},ce.addEventListener("sessionstart",xt),ce.addEventListener("sessionend",wt),this.render=function(Ue,dt){if(dt!==void 0&&dt.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;Ue.matrixWorldAutoUpdate===!0&&Ue.updateMatrixWorld(),dt.parent===null&&dt.matrixWorldAutoUpdate===!0&&dt.updateMatrixWorld(),ce.enabled===!0&&ce.isPresenting===!0&&(ce.cameraAutoUpdate===!0&&ce.updateCamera(dt),dt=ce.getCamera()),Ue.isScene===!0&&Ue.onBeforeRender(k,Ue,dt,A),b=ye.get(Ue,_.length),b.init(),_.push(b),Y.multiplyMatrices(dt.projectionMatrix,dt.matrixWorldInverse),oe.setFromProjectionMatrix(Y),_e=this.localClippingEnabled,be=Ae.init(this.clippingPlanes,_e),v=we.get(Ue,g.length),v.init(),g.push(v),Xt(Ue,dt,0,k.sortObjects),v.finish(),k.sortObjects===!0&&v.sort(me,le),this.info.render.frame++,be===!0&&Ae.beginShadows();const pt=b.state.shadowsArray;if(ve.render(pt,Ue,dt),be===!0&&Ae.endShadows(),this.info.autoReset===!0&&this.info.reset(),Te.render(v,Ue),b.setupLights(k._useLegacyLights),dt.isArrayCamera){const De=dt.cameras;for(let Le=0,at=De.length;Le<at;Le++){const Ce=De[Le];Kt(v,Ue,Ce,Ce.viewport)}}else Kt(v,Ue,dt);A!==null&&(ie.updateMultisampleRenderTarget(A),ie.updateRenderTargetMipmap(A)),Ue.isScene===!0&&Ue.onAfterRender(k,Ue,dt),qe.resetDefaultState(),T=-1,C=null,_.pop(),_.length>0?b=_[_.length-1]:b=null,g.pop(),g.length>0?v=g[g.length-1]:v=null};function Xt(Ue,dt,pt,De){if(Ue.visible===!1)return;if(Ue.layers.test(dt.layers)){if(Ue.isGroup)pt=Ue.renderOrder;else if(Ue.isLOD)Ue.autoUpdate===!0&&Ue.update(dt);else if(Ue.isLight)b.pushLight(Ue),Ue.castShadow&&b.pushShadow(Ue);else if(Ue.isSprite){if(!Ue.frustumCulled||oe.intersectsSprite(Ue)){De&&j.setFromMatrixPosition(Ue.matrixWorld).applyMatrix4(Y);const Ce=R.update(Ue),We=Ue.material;We.visible&&v.push(Ue,Ce,We,pt,j.z,null)}}else if((Ue.isMesh||Ue.isLine||Ue.isPoints)&&(!Ue.frustumCulled||oe.intersectsObject(Ue))){const Ce=R.update(Ue),We=Ue.material;if(De&&(Ue.boundingSphere!==void 0?(Ue.boundingSphere===null&&Ue.computeBoundingSphere(),j.copy(Ue.boundingSphere.center)):(Ce.boundingSphere===null&&Ce.computeBoundingSphere(),j.copy(Ce.boundingSphere.center)),j.applyMatrix4(Ue.matrixWorld).applyMatrix4(Y)),Array.isArray(We)){const Xe=Ce.groups;for(let Qe=0,Ze=Xe.length;Qe<Ze;Qe++){const rt=Xe[Qe],bt=We[rt.materialIndex];bt&&bt.visible&&v.push(Ue,Ce,bt,pt,j.z,rt)}}else We.visible&&v.push(Ue,Ce,We,pt,j.z,null)}}const at=Ue.children;for(let Ce=0,We=at.length;Ce<We;Ce++)Xt(at[Ce],dt,pt,De)}function Kt(Ue,dt,pt,De){const Le=Ue.opaque,at=Ue.transmissive,Ce=Ue.transparent;b.setupLightsView(pt),be===!0&&Ae.setGlobalState(k.clippingPlanes,pt),at.length>0&&Ut(Le,at,dt,pt),De&&Q.viewport(F.copy(De)),Le.length>0&&en(Le,dt,pt),at.length>0&&en(at,dt,pt),Ce.length>0&&en(Ce,dt,pt),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function Ut(Ue,dt,pt,De){if((pt.isScene===!0?pt.overrideMaterial:null)!==null)return;const at=G.isWebGL2;B===null&&(B=new Vf(1,1,{generateMipmaps:!0,type:O.has("EXT_color_buffer_half_float")?$0:Oh,minFilter:q0,samples:at?4:0})),k.getDrawingBufferSize(D),at?B.setSize(D.x,D.y):B.setSize(bN(D.x),bN(D.y));const Ce=k.getRenderTarget();k.setRenderTarget(B),k.getClearColor(X),L=k.getClearAlpha(),L<1&&k.setClearColor(16777215,.5),k.clear();const We=k.toneMapping;k.toneMapping=Lh,en(Ue,pt,De),ie.updateMultisampleRenderTarget(B),ie.updateRenderTargetMipmap(B);let Xe=!1;for(let Qe=0,Ze=dt.length;Qe<Ze;Qe++){const rt=dt[Qe],bt=rt.object,Pt=rt.geometry,vt=rt.material,He=rt.group;if(vt.side===ku&&bt.layers.test(De.layers)){const St=vt.side;vt.side=Po,vt.needsUpdate=!0,Ke(bt,pt,De,Pt,vt,He),vt.side=St,vt.needsUpdate=!0,Xe=!0}}Xe===!0&&(ie.updateMultisampleRenderTarget(B),ie.updateRenderTargetMipmap(B)),k.setRenderTarget(Ce),k.setClearColor(X,L),k.toneMapping=We}function en(Ue,dt,pt){const De=dt.isScene===!0?dt.overrideMaterial:null;for(let Le=0,at=Ue.length;Le<at;Le++){const Ce=Ue[Le],We=Ce.object,Xe=Ce.geometry,Qe=De===null?Ce.material:De,Ze=Ce.group;We.layers.test(pt.layers)&&Ke(We,dt,pt,Xe,Qe,Ze)}}function Ke(Ue,dt,pt,De,Le,at){Ue.onBeforeRender(k,dt,pt,De,Le,at),Ue.modelViewMatrix.multiplyMatrices(pt.matrixWorldInverse,Ue.matrixWorld),Ue.normalMatrix.getNormalMatrix(Ue.modelViewMatrix),Le.onBeforeRender(k,dt,pt,De,Ue,at),Le.transparent===!0&&Le.side===ku&&Le.forceSinglePass===!1?(Le.side=Po,Le.needsUpdate=!0,k.renderBufferDirect(pt,dt,De,Le,Ue,at),Le.side=Gh,Le.needsUpdate=!0,k.renderBufferDirect(pt,dt,De,Le,Ue,at),Le.side=ku):k.renderBufferDirect(pt,dt,De,Le,Ue,at),Ue.onAfterRender(k,dt,pt,De,Le,at)}function Ft(Ue,dt,pt){dt.isScene!==!0&&(dt=z);const De=J.get(Ue),Le=b.state.lights,at=b.state.shadowsArray,Ce=Le.state.version,We=re.getParameters(Ue,Le.state,at,dt,pt),Xe=re.getProgramCacheKey(We);let Qe=De.programs;De.environment=Ue.isMeshStandardMaterial?dt.environment:null,De.fog=dt.fog,De.envMap=(Ue.isMeshStandardMaterial?fe:he).get(Ue.envMap||De.environment),Qe===void 0&&(Ue.addEventListener("dispose",$e),Qe=new Map,De.programs=Qe);let Ze=Qe.get(Xe);if(Ze!==void 0){if(De.currentProgram===Ze&&De.lightsStateVersion===Ce)return ht(Ue,We),Ze}else We.uniforms=re.getUniforms(Ue),Ue.onBuild(pt,We,k),Ue.onBeforeCompile(We,k),Ze=re.acquireProgram(We,Xe),Qe.set(Xe,Ze),De.uniforms=We.uniforms;const rt=De.uniforms;return(!Ue.isShaderMaterial&&!Ue.isRawShaderMaterial||Ue.clipping===!0)&&(rt.clippingPlanes=Ae.uniform),ht(Ue,We),De.needsLights=Wt(Ue),De.lightsStateVersion=Ce,De.needsLights&&(rt.ambientLightColor.value=Le.state.ambient,rt.lightProbe.value=Le.state.probe,rt.directionalLights.value=Le.state.directional,rt.directionalLightShadows.value=Le.state.directionalShadow,rt.spotLights.value=Le.state.spot,rt.spotLightShadows.value=Le.state.spotShadow,rt.rectAreaLights.value=Le.state.rectArea,rt.ltc_1.value=Le.state.rectAreaLTC1,rt.ltc_2.value=Le.state.rectAreaLTC2,rt.pointLights.value=Le.state.point,rt.pointLightShadows.value=Le.state.pointShadow,rt.hemisphereLights.value=Le.state.hemi,rt.directionalShadowMap.value=Le.state.directionalShadowMap,rt.directionalShadowMatrix.value=Le.state.directionalShadowMatrix,rt.spotShadowMap.value=Le.state.spotShadowMap,rt.spotLightMatrix.value=Le.state.spotLightMatrix,rt.spotLightMap.value=Le.state.spotLightMap,rt.pointShadowMap.value=Le.state.pointShadowMap,rt.pointShadowMatrix.value=Le.state.pointShadowMatrix),De.currentProgram=Ze,De.uniformsList=null,Ze}function Nt(Ue){if(Ue.uniformsList===null){const dt=Ue.currentProgram.getUniforms();Ue.uniformsList=Tk.seqWithValue(dt.seq,Ue.uniforms)}return Ue.uniformsList}function ht(Ue,dt){const pt=J.get(Ue);pt.outputColorSpace=dt.outputColorSpace,pt.batching=dt.batching,pt.instancing=dt.instancing,pt.instancingColor=dt.instancingColor,pt.skinning=dt.skinning,pt.morphTargets=dt.morphTargets,pt.morphNormals=dt.morphNormals,pt.morphColors=dt.morphColors,pt.morphTargetsCount=dt.morphTargetsCount,pt.numClippingPlanes=dt.numClippingPlanes,pt.numIntersection=dt.numClipIntersection,pt.vertexAlphas=dt.vertexAlphas,pt.vertexTangents=dt.vertexTangents,pt.toneMapping=dt.toneMapping}function Mt(Ue,dt,pt,De,Le){dt.isScene!==!0&&(dt=z),ie.resetTextureUnits();const at=dt.fog,Ce=De.isMeshStandardMaterial?dt.environment:null,We=A===null?k.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Qu,Xe=(De.isMeshStandardMaterial?fe:he).get(De.envMap||Ce),Qe=De.vertexColors===!0&&!!pt.attributes.color&&pt.attributes.color.itemSize===4,Ze=!!pt.attributes.tangent&&(!!De.normalMap||De.anisotropy>0),rt=!!pt.morphAttributes.position,bt=!!pt.morphAttributes.normal,Pt=!!pt.morphAttributes.color;let vt=Lh;De.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(vt=k.toneMapping);const He=pt.morphAttributes.position||pt.morphAttributes.normal||pt.morphAttributes.color,St=He!==void 0?He.length:0,Ct=J.get(De),Zt=b.state.lights;if(be===!0&&(_e===!0||Ue!==C)){const ar=Ue===C&&De.id===T;Ae.setState(De,Ue,ar)}let Jt=!1;De.version===Ct.__version?(Ct.needsLights&&Ct.lightsStateVersion!==Zt.state.version||Ct.outputColorSpace!==We||Le.isBatchedMesh&&Ct.batching===!1||!Le.isBatchedMesh&&Ct.batching===!0||Le.isInstancedMesh&&Ct.instancing===!1||!Le.isInstancedMesh&&Ct.instancing===!0||Le.isSkinnedMesh&&Ct.skinning===!1||!Le.isSkinnedMesh&&Ct.skinning===!0||Le.isInstancedMesh&&Ct.instancingColor===!0&&Le.instanceColor===null||Le.isInstancedMesh&&Ct.instancingColor===!1&&Le.instanceColor!==null||Ct.envMap!==Xe||De.fog===!0&&Ct.fog!==at||Ct.numClippingPlanes!==void 0&&(Ct.numClippingPlanes!==Ae.numPlanes||Ct.numIntersection!==Ae.numIntersection)||Ct.vertexAlphas!==Qe||Ct.vertexTangents!==Ze||Ct.morphTargets!==rt||Ct.morphNormals!==bt||Ct.morphColors!==Pt||Ct.toneMapping!==vt||G.isWebGL2===!0&&Ct.morphTargetsCount!==St)&&(Jt=!0):(Jt=!0,Ct.__version=De.version);let Nn=Ct.currentProgram;Jt===!0&&(Nn=Ft(De,dt,Le));let vn=!1,yn=!1,an=!1;const rn=Nn.getUniforms(),bn=Ct.uniforms;if(Q.useProgram(Nn.program)&&(vn=!0,yn=!0,an=!0),De.id!==T&&(T=De.id,yn=!0),vn||C!==Ue){rn.setValue(q,"projectionMatrix",Ue.projectionMatrix),rn.setValue(q,"viewMatrix",Ue.matrixWorldInverse);const ar=rn.map.cameraPosition;ar!==void 0&&ar.setValue(q,j.setFromMatrixPosition(Ue.matrixWorld)),G.logarithmicDepthBuffer&&rn.setValue(q,"logDepthBufFC",2/(Math.log(Ue.far+1)/Math.LN2)),(De.isMeshPhongMaterial||De.isMeshToonMaterial||De.isMeshLambertMaterial||De.isMeshBasicMaterial||De.isMeshStandardMaterial||De.isShaderMaterial)&&rn.setValue(q,"isOrthographic",Ue.isOrthographicCamera===!0),C!==Ue&&(C=Ue,yn=!0,an=!0)}if(Le.isSkinnedMesh){rn.setOptional(q,Le,"bindMatrix"),rn.setOptional(q,Le,"bindMatrixInverse");const ar=Le.skeleton;ar&&(G.floatVertexTextures?(ar.boneTexture===null&&ar.computeBoneTexture(),rn.setValue(q,"boneTexture",ar.boneTexture,ie)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}Le.isBatchedMesh&&(rn.setOptional(q,Le,"batchingTexture"),rn.setValue(q,"batchingTexture",Le._matricesTexture,ie));const Gn=pt.morphAttributes;if((Gn.position!==void 0||Gn.normal!==void 0||Gn.color!==void 0&&G.isWebGL2===!0)&&Fe.update(Le,pt,Nn),(yn||Ct.receiveShadow!==Le.receiveShadow)&&(Ct.receiveShadow=Le.receiveShadow,rn.setValue(q,"receiveShadow",Le.receiveShadow)),De.isMeshGouraudMaterial&&De.envMap!==null&&(bn.envMap.value=Xe,bn.flipEnvMap.value=Xe.isCubeTexture&&Xe.isRenderTargetTexture===!1?-1:1),yn&&(rn.setValue(q,"toneMappingExposure",k.toneMappingExposure),Ct.needsLights&&Qt(bn,an),at&&De.fog===!0&&xe.refreshFogUniforms(bn,at),xe.refreshMaterialUniforms(bn,De,ee,ae,B),Tk.upload(q,Nt(Ct),bn,ie)),De.isShaderMaterial&&De.uniformsNeedUpdate===!0&&(Tk.upload(q,Nt(Ct),bn,ie),De.uniformsNeedUpdate=!1),De.isSpriteMaterial&&rn.setValue(q,"center",Le.center),rn.setValue(q,"modelViewMatrix",Le.modelViewMatrix),rn.setValue(q,"normalMatrix",Le.normalMatrix),rn.setValue(q,"modelMatrix",Le.matrixWorld),De.isShaderMaterial||De.isRawShaderMaterial){const ar=De.uniformsGroups;for(let On=0,mi=ar.length;On<mi;On++)if(G.isWebGL2){const Rn=ar[On];Re.update(Rn,Nn),Re.bind(Rn,Nn)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return Nn}function Qt(Ue,dt){Ue.ambientLightColor.needsUpdate=dt,Ue.lightProbe.needsUpdate=dt,Ue.directionalLights.needsUpdate=dt,Ue.directionalLightShadows.needsUpdate=dt,Ue.pointLights.needsUpdate=dt,Ue.pointLightShadows.needsUpdate=dt,Ue.spotLights.needsUpdate=dt,Ue.spotLightShadows.needsUpdate=dt,Ue.rectAreaLights.needsUpdate=dt,Ue.hemisphereLights.needsUpdate=dt}function Wt(Ue){return Ue.isMeshLambertMaterial||Ue.isMeshToonMaterial||Ue.isMeshPhongMaterial||Ue.isMeshStandardMaterial||Ue.isShadowMaterial||Ue.isShaderMaterial&&Ue.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(Ue,dt,pt){J.get(Ue.texture).__webglTexture=dt,J.get(Ue.depthTexture).__webglTexture=pt;const De=J.get(Ue);De.__hasExternalTextures=!0,De.__hasExternalTextures&&(De.__autoAllocateDepthBuffer=pt===void 0,De.__autoAllocateDepthBuffer||O.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),De.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(Ue,dt){const pt=J.get(Ue);pt.__webglFramebuffer=dt,pt.__useDefaultFramebuffer=dt===void 0},this.setRenderTarget=function(Ue,dt=0,pt=0){A=Ue,N=dt,M=pt;let De=!0,Le=null,at=!1,Ce=!1;if(Ue){const Xe=J.get(Ue);Xe.__useDefaultFramebuffer!==void 0?(Q.bindFramebuffer(q.FRAMEBUFFER,null),De=!1):Xe.__webglFramebuffer===void 0?ie.setupRenderTarget(Ue):Xe.__hasExternalTextures&&ie.rebindTextures(Ue,J.get(Ue.texture).__webglTexture,J.get(Ue.depthTexture).__webglTexture);const Qe=Ue.texture;(Qe.isData3DTexture||Qe.isDataArrayTexture||Qe.isCompressedArrayTexture)&&(Ce=!0);const Ze=J.get(Ue).__webglFramebuffer;Ue.isWebGLCubeRenderTarget?(Array.isArray(Ze[dt])?Le=Ze[dt][pt]:Le=Ze[dt],at=!0):G.isWebGL2&&Ue.samples>0&&ie.useMultisampledRTT(Ue)===!1?Le=J.get(Ue).__webglMultisampledFramebuffer:Array.isArray(Ze)?Le=Ze[pt]:Le=Ze,F.copy(Ue.viewport),$.copy(Ue.scissor),I=Ue.scissorTest}else F.copy(ue).multiplyScalar(ee).floor(),$.copy(K).multiplyScalar(ee).floor(),I=ne;if(Q.bindFramebuffer(q.FRAMEBUFFER,Le)&&G.drawBuffers&&De&&Q.drawBuffers(Ue,Le),Q.viewport(F),Q.scissor($),Q.setScissorTest(I),at){const Xe=J.get(Ue.texture);q.framebufferTexture2D(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_CUBE_MAP_POSITIVE_X+dt,Xe.__webglTexture,pt)}else if(Ce){const Xe=J.get(Ue.texture),Qe=dt||0;q.framebufferTextureLayer(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,Xe.__webglTexture,pt||0,Qe)}T=-1},this.readRenderTargetPixels=function(Ue,dt,pt,De,Le,at,Ce){if(!(Ue&&Ue.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let We=J.get(Ue).__webglFramebuffer;if(Ue.isWebGLCubeRenderTarget&&Ce!==void 0&&(We=We[Ce]),We){Q.bindFramebuffer(q.FRAMEBUFFER,We);try{const Xe=Ue.texture,Qe=Xe.format,Ze=Xe.type;if(Qe!==Ol&&je.convert(Qe)!==q.getParameter(q.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const rt=Ze===$0&&(O.has("EXT_color_buffer_half_float")||G.isWebGL2&&O.has("EXT_color_buffer_float"));if(Ze!==Oh&&je.convert(Ze)!==q.getParameter(q.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Ze===ju&&(G.isWebGL2||O.has("OES_texture_float")||O.has("WEBGL_color_buffer_float")))&&!rt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}dt>=0&&dt<=Ue.width-De&&pt>=0&&pt<=Ue.height-Le&&q.readPixels(dt,pt,De,Le,je.convert(Qe),je.convert(Ze),at)}finally{const Xe=A!==null?J.get(A).__webglFramebuffer:null;Q.bindFramebuffer(q.FRAMEBUFFER,Xe)}}},this.copyFramebufferToTexture=function(Ue,dt,pt=0){const De=Math.pow(2,-pt),Le=Math.floor(dt.image.width*De),at=Math.floor(dt.image.height*De);ie.setTexture2D(dt,0),q.copyTexSubImage2D(q.TEXTURE_2D,pt,0,0,Ue.x,Ue.y,Le,at),Q.unbindTexture()},this.copyTextureToTexture=function(Ue,dt,pt,De=0){const Le=dt.image.width,at=dt.image.height,Ce=je.convert(pt.format),We=je.convert(pt.type);ie.setTexture2D(pt,0),q.pixelStorei(q.UNPACK_FLIP_Y_WEBGL,pt.flipY),q.pixelStorei(q.UNPACK_PREMULTIPLY_ALPHA_WEBGL,pt.premultiplyAlpha),q.pixelStorei(q.UNPACK_ALIGNMENT,pt.unpackAlignment),dt.isDataTexture?q.texSubImage2D(q.TEXTURE_2D,De,Ue.x,Ue.y,Le,at,Ce,We,dt.image.data):dt.isCompressedTexture?q.compressedTexSubImage2D(q.TEXTURE_2D,De,Ue.x,Ue.y,dt.mipmaps[0].width,dt.mipmaps[0].height,Ce,dt.mipmaps[0].data):q.texSubImage2D(q.TEXTURE_2D,De,Ue.x,Ue.y,Ce,We,dt.image),De===0&&pt.generateMipmaps&&q.generateMipmap(q.TEXTURE_2D),Q.unbindTexture()},this.copyTextureToTexture3D=function(Ue,dt,pt,De,Le=0){if(k.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const at=Ue.max.x-Ue.min.x+1,Ce=Ue.max.y-Ue.min.y+1,We=Ue.max.z-Ue.min.z+1,Xe=je.convert(De.format),Qe=je.convert(De.type);let Ze;if(De.isData3DTexture)ie.setTexture3D(De,0),Ze=q.TEXTURE_3D;else if(De.isDataArrayTexture)ie.setTexture2DArray(De,0),Ze=q.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}q.pixelStorei(q.UNPACK_FLIP_Y_WEBGL,De.flipY),q.pixelStorei(q.UNPACK_PREMULTIPLY_ALPHA_WEBGL,De.premultiplyAlpha),q.pixelStorei(q.UNPACK_ALIGNMENT,De.unpackAlignment);const rt=q.getParameter(q.UNPACK_ROW_LENGTH),bt=q.getParameter(q.UNPACK_IMAGE_HEIGHT),Pt=q.getParameter(q.UNPACK_SKIP_PIXELS),vt=q.getParameter(q.UNPACK_SKIP_ROWS),He=q.getParameter(q.UNPACK_SKIP_IMAGES),St=pt.isCompressedTexture?pt.mipmaps[0]:pt.image;q.pixelStorei(q.UNPACK_ROW_LENGTH,St.width),q.pixelStorei(q.UNPACK_IMAGE_HEIGHT,St.height),q.pixelStorei(q.UNPACK_SKIP_PIXELS,Ue.min.x),q.pixelStorei(q.UNPACK_SKIP_ROWS,Ue.min.y),q.pixelStorei(q.UNPACK_SKIP_IMAGES,Ue.min.z),pt.isDataTexture||pt.isData3DTexture?q.texSubImage3D(Ze,Le,dt.x,dt.y,dt.z,at,Ce,We,Xe,Qe,St.data):pt.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),q.compressedTexSubImage3D(Ze,Le,dt.x,dt.y,dt.z,at,Ce,We,Xe,St.data)):q.texSubImage3D(Ze,Le,dt.x,dt.y,dt.z,at,Ce,We,Xe,Qe,St),q.pixelStorei(q.UNPACK_ROW_LENGTH,rt),q.pixelStorei(q.UNPACK_IMAGE_HEIGHT,bt),q.pixelStorei(q.UNPACK_SKIP_PIXELS,Pt),q.pixelStorei(q.UNPACK_SKIP_ROWS,vt),q.pixelStorei(q.UNPACK_SKIP_IMAGES,He),Le===0&&De.generateMipmaps&&q.generateMipmap(Ze),Q.unbindTexture()},this.initTexture=function(Ue){Ue.isCubeTexture?ie.setTextureCube(Ue,0):Ue.isData3DTexture?ie.setTexture3D(Ue,0):Ue.isDataArrayTexture||Ue.isCompressedArrayTexture?ie.setTexture2DArray(Ue,0):ie.setTexture2D(Ue,0),Q.unbindTexture()},this.resetState=function(){N=0,M=0,A=null,Q.reset(),qe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return fd}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===UO?"display-p3":"srgb",n.unpackColorSpace=$r.workingColorSpace===RP?"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===rs?_f:jZ}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===_f?rs:Qu}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 hMe extends YF{}hMe.prototype.isWebGL1Renderer=!0;class GO{constructor(e,n=1,r=1e3){this.isFog=!0,this.name="",this.color=new An(e),this.near=n,this.far=r}clone(){return new GO(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class pMe extends Js{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n}}class fMe{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=VF,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=zu()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.InterleavedBuffer: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,n,r){e*=this.stride,r*=n.stride;for(let i=0,s=this.stride;i<s;i++)this.array[e+i]=n.array[r+i];return this}set(e,n=0){return this.array.set(e,n),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=zu()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const n=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),r=new this.constructor(n,this.stride);return r.setUsage(this.usage),r}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=zu()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const qs=new ot;class wh{constructor(e,n,r,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=n,this.offset=r,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let n=0,r=this.data.count;n<r;n++)qs.fromBufferAttribute(this,n),qs.applyMatrix4(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)qs.fromBufferAttribute(this,n),qs.applyNormalMatrix(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)qs.fromBufferAttribute(this,n),qs.transformDirection(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}setX(e,n){return this.normalized&&(n=qr(n,this.array)),this.data.array[e*this.data.stride+this.offset]=n,this}setY(e,n){return this.normalized&&(n=qr(n,this.array)),this.data.array[e*this.data.stride+this.offset+1]=n,this}setZ(e,n){return this.normalized&&(n=qr(n,this.array)),this.data.array[e*this.data.stride+this.offset+2]=n,this}setW(e,n){return this.normalized&&(n=qr(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=md(n,this.array)),n}getY(e){let n=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(n=md(n,this.array)),n}getZ(e){let n=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(n=md(n,this.array)),n}getW(e){let n=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(n=md(n,this.array)),n}setXY(e,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this}setXYZ(e,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array),i=qr(i,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(n=qr(n,this.array),r=qr(r,this.array),i=qr(i,this.array),s=qr(s,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=i,this.data.array[e+3]=s,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const n=[];for(let r=0;r<this.count;r++){const i=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[i+s])}return new al(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 wh(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const n=[];for(let r=0;r<this.count;r++){const i=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[i+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:n,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class gMe extends To{constructor(e=null,n=1,r=1,i,s,o,l,c,d=ns,u=ns,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function bMe(t,e){return t.z-e.z}function xMe(t,e){return e.z-t.z}class yMe{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,n){const r=this.pool,i=this.list;this.index>=r.length&&r.push({start:-1,count:-1,z:-1});const s=r[this.index];i.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=n}reset(){this.list.length=0,this.index=0}}const Ab="batchId",Qm=new oa,Zq=new oa,vMe=new oa,Jq=new oa,SE=new LP,S1=new $l,Bp=new vd,_v=new ot,_E=new yMe,Ns=new Ac,_1=[];function wMe(t,e,n=0){const r=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const i=t.count;for(let s=0;s<i;s++)for(let o=0;o<r;o++)e.setComponent(s+n,o,t.getComponent(s,o))}else e.array.set(t.array,n*r);e.needsUpdate=!0}class SMe extends Ac{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,n,r=n*2,i){super(new Rs,i),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._drawRanges=[],this._reservedRanges=[],this._visibility=[],this._active=[],this._bounds=[],this._maxGeometryCount=e,this._maxVertexCount=n,this._maxIndexCount=r,this._geometryInitialized=!1,this._geometryCount=0,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._visibilityChanged=!0,this._matricesTexture=null,this._initMatricesTexture()}_initMatricesTexture(){let e=Math.sqrt(this._maxGeometryCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const n=new Float32Array(e*e*4),r=new gMe(n,e,e,Ol,ju);this._matricesTexture=r}_initializeGeometry(e){const n=this.geometry,r=this._maxVertexCount,i=this._maxGeometryCount,s=this._maxIndexCount;if(this._geometryInitialized===!1){for(const l in e.attributes){const c=e.getAttribute(l),{array:d,itemSize:u,normalized:m}=c,p=new d.constructor(r*u),f=new c.constructor(p,u,m);f.setUsage(c.usage),n.setAttribute(l,f)}if(e.getIndex()!==null){const l=r>65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new al(l,1))}const o=i>65536?new Uint32Array(r):new Uint16Array(r);n.setAttribute(Ab,new al(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(Ab))throw new Error(`BatchedMesh: Geometry cannot use attribute "${Ab}"`);const n=this.geometry;if(!!e.getIndex()!=!!n.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const r in n.attributes){if(r===Ab)continue;if(!e.hasAttribute(r))throw new Error(`BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);const i=e.getAttribute(r),s=n.getAttribute(r);if(i.itemSize!==s.itemSize||i.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new $l);const e=this._geometryCount,n=this.boundingBox,r=this._active;n.makeEmpty();for(let i=0;i<e;i++)r[i]!==!1&&(this.getMatrixAt(i,Qm),this.getBoundingBoxAt(i,S1).applyMatrix4(Qm),n.union(S1))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new vd);const e=this._geometryCount,n=this.boundingSphere,r=this._active;n.makeEmpty();for(let i=0;i<e;i++)r[i]!==!1&&(this.getMatrixAt(i,Qm),this.getBoundingSphereAt(i,Bp).applyMatrix4(Qm),n.union(Bp))}addGeometry(e,n=-1,r=-1){if(this._initializeGeometry(e),this._validateGeometry(e),this._geometryCount>=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const o=this._reservedRanges,l=this._drawRanges,c=this._bounds;this._geometryCount!==0&&(s=o[o.length-1]),n===-1?i.vertexCount=e.getAttribute("position").count:i.vertexCount=n,s===null?i.vertexStart=0:i.vertexStart=s.vertexStart+s.vertexCount;const d=e.getIndex(),u=d!==null;if(u&&(r===-1?i.indexCount=d.count:i.indexCount=r,s===null?i.indexStart=0:i.indexStart=s.indexStart+s.indexCount),i.indexStart!==-1&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const m=this._visibility,p=this._active,f=this._matricesTexture,y=this._matricesTexture.image.data;m.push(!0),p.push(!0);const v=this._geometryCount;this._geometryCount++,vMe.toArray(y,v*16),f.needsUpdate=!0,o.push(i),l.push({start:u?i.indexStart:i.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new $l,sphereInitialized:!1,sphere:new vd});const b=this.geometry.getAttribute(Ab);for(let g=0;g<i.vertexCount;g++)b.setX(i.vertexStart+g,v);return b.needsUpdate=!0,this.setGeometryAt(v,e),v}setGeometryAt(e,n){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(n);const r=this.geometry,i=r.getIndex()!==null,s=r.getIndex(),o=n.getIndex(),l=this._reservedRanges[e];if(i&&o.count>l.indexCount||n.attributes.position.count>l.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const c=l.vertexStart,d=l.vertexCount;for(const f in r.attributes){if(f===Ab)continue;const y=n.getAttribute(f),v=r.getAttribute(f);wMe(y,v,c);const b=y.itemSize;for(let g=y.count,_=d;g<_;g++){const k=c+g;for(let P=0;P<b;P++)v.setComponent(k,P,0)}v.needsUpdate=!0}if(i){const f=l.indexStart;for(let y=0;y<o.count;y++)s.setX(f+y,c+o.getX(y));for(let y=o.count,v=l.indexCount;y<v;y++)s.setX(f+y,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(_v.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,S1),S1.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)),_v.fromBufferAttribute(c,f),u=Math.max(u,s.center.distanceToSquared(_v))}s.radius=Math.sqrt(u),i.sphereInitialized=!0}return n.copy(s),n}setMatrixAt(e,n){const r=this._active,i=this._matricesTexture,s=this._matricesTexture.image.data,o=this._geometryCount;return e>=o||r[e]===!1?this:(n.toArray(s,e*16),i.needsUpdate=!0,this)}getMatrixAt(e,n){const r=this._active,i=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||r[e]===!1?null:n.fromArray(i,e*16)}setVisibleAt(e,n){const r=this._visibility,i=this._active,s=this._geometryCount;return e>=s||i[e]===!1||r[e]===n?this:(r[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,r=this._active,i=this._geometryCount;return e>=i||r[e]===!1?!1:n[e]}raycast(e,n){const r=this._visibility,i=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;Ns.material=this.material,Ns.geometry.index=c.index,Ns.geometry.attributes=c.attributes,Ns.geometry.boundingBox===null&&(Ns.geometry.boundingBox=new $l),Ns.geometry.boundingSphere===null&&(Ns.geometry.boundingSphere=new vd);for(let d=0;d<o;d++){if(!r[d]||!i[d])continue;const u=s[d];Ns.geometry.setDrawRange(u.start,u.count),this.getMatrixAt(d,Ns.matrixWorld).premultiply(l),this.getBoundingBoxAt(d,Ns.geometry.boundingBox),this.getBoundingSphereAt(d,Ns.geometry.boundingSphere),Ns.raycast(e,_1);for(let m=0,p=_1.length;m<p;m++){const f=_1[m];f.object=this,f.batchId=d,n.push(f)}_1.length=0}Ns.material=null,Ns.geometry.index=null,Ns.geometry.attributes={},Ns.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._drawRanges=e._drawRanges.map(n=>({...n})),this._reservedRanges=e._reservedRanges.map(n=>({...n})),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map(n=>({boxInitialized:n.boxInitialized,box:n.box.clone(),sphereInitialized:n.sphereInitialized,sphere:n.sphere.clone()})),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,n,r,i,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=i.getIndex(),l=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._visibility,d=this._multiDrawStarts,u=this._multiDrawCounts,m=this._drawRanges,p=this.perObjectFrustumCulled;p&&(Jq.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),SE.setFromProjectionMatrix(Jq,e.isWebGPURenderer?V0:fd));let f=0;if(this.sortObjects){Zq.copy(this.matrixWorld).invert(),_v.setFromMatrixPosition(r.matrixWorld).applyMatrix4(Zq);for(let b=0,g=c.length;b<g;b++)if(c[b]){this.getMatrixAt(b,Qm),this.getBoundingSphereAt(b,Bp).applyMatrix4(Qm);let _=!1;if(p&&(_=!SE.intersectsSphere(Bp)),!_){const k=_v.distanceTo(Bp.center);_E.push(m[b],k)}}const y=_E.list,v=this.customSort;v===null?y.sort(s.transparent?xMe:bMe):v.call(this,y,r);for(let b=0,g=y.length;b<g;b++){const _=y[b];d[f]=_.start*l,u[f]=_.count,f++}_E.reset()}else for(let y=0,v=c.length;y<v;y++)if(c[y]){let b=!1;if(p&&(this.getMatrixAt(y,Qm),this.getBoundingSphereAt(y,Bp).applyMatrix4(Qm),b=!SE.intersectsSphere(Bp)),!b){const g=m[y];d[f]=g.start*l,u[f]=g.count,f++}}this._multiDrawCount=f,this._visibilityChanged=!1}onBeforeShadow(e,n,r,i,s,o){this.onBeforeRender(e,null,i,s,o)}}class Bw extends sy{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new An(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 e$=new ot,t$=new ot,n$=new oa,kE=new HO,k1=new vd;let _Me=class extends Js{constructor(e=new Rs,n=new Bw){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[0];for(let i=1,s=n.count;i<s;i++)e$.fromBufferAttribute(n,i-1),t$.fromBufferAttribute(n,i),r[i]=r[i-1],r[i]+=e$.distanceTo(t$);e.setAttribute("lineDistance",new Qa(r,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),k1.copy(r.boundingSphere),k1.applyMatrix4(i),k1.radius+=s,e.ray.intersectsSphere(k1)===!1)return;n$.copy(i).invert(),kE.copy(e.ray).applyMatrix4(n$);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=new ot,u=new ot,m=new ot,p=new ot,f=this.isLineSegments?2:1,y=r.index,b=r.attributes.position;if(y!==null){const g=Math.max(0,o.start),_=Math.min(y.count,o.start+o.count);for(let k=g,P=_-1;k<P;k+=f){const N=y.getX(k),M=y.getX(k+1);if(d.fromBufferAttribute(b,N),u.fromBufferAttribute(b,M),kE.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})}}else{const g=Math.max(0,o.start),_=Math.min(b.count,o.start+o.count);for(let k=g,P=_-1;k<P;k+=f){if(d.fromBufferAttribute(b,k),u.fromBufferAttribute(b,k+1),kE.distanceSqToSegment(d,u,p,m)>c)continue;p.applyMatrix4(this.matrixWorld);const M=e.ray.origin.distanceTo(p);M<e.near||M>e.far||n.push({distance:M,point:m.clone().applyMatrix4(this.matrixWorld),index:k,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};const r$=new ot,a$=new ot;class IP extends _Me{constructor(e,n){super(e,n),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[];for(let i=0,s=n.count;i<s;i+=2)r$.fromBufferAttribute(n,i),a$.fromBufferAttribute(n,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+r$.distanceTo(a$);e.setAttribute("lineDistance",new Qa(r,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class kMe extends Rs{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const n=[],r=new Set,i=new ot,s=new ot;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 y=p,v=p+f;y<v;y+=3)for(let b=0;b<3;b++){const g=l.getX(y+b),_=l.getX(y+(b+1)%3);i.fromBufferAttribute(o,g),s.fromBufferAttribute(o,_),i$(i,s,r)===!0&&(n.push(i.x,i.y,i.z),n.push(s.x,s.y,s.z))}}}else{const o=e.attributes.position;for(let l=0,c=o.count/3;l<c;l++)for(let d=0;d<3;d++){const u=3*l+d,m=3*l+(d+1)%3;i.fromBufferAttribute(o,u),s.fromBufferAttribute(o,m),i$(i,s,r)===!0&&(n.push(i.x,i.y,i.z),n.push(s.x,s.y,s.z))}}this.setAttribute("position",new Qa(n,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function i$(t,e,n){const r=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,i=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return n.has(r)===!0||n.has(i)===!0?!1:(n.add(r),n.add(i),!0)}class NMe extends sy{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new An(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new An(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=EZ,this.normalScale=new Hn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=IO,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 CMe extends Bw{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 eJ extends Js{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new An(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 NE=new oa,s$=new ot,o$=new ot;class PMe{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Hn(512,512),this.map=null,this.mapPass=null,this.matrix=new oa,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new LP,this._frameExtents=new Hn(1,1),this._viewportCount=1,this._viewports=[new Gr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;s$.setFromMatrixPosition(e.matrixWorld),n.position.copy(s$),o$.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(o$),n.updateMatrixWorld(),NE.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(NE),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(NE)}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 l$=new oa,kv=new ot,CE=new ot;class TMe extends PMe{constructor(){super(new Zo(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Hn(4,2),this._viewportCount=6,this._viewports=[new Gr(2,1,1,1),new Gr(0,1,1,1),new Gr(3,1,1,1),new Gr(1,1,1,1),new Gr(3,0,1,1),new Gr(1,0,1,1)],this._cubeDirections=[new ot(1,0,0),new ot(-1,0,0),new ot(0,0,1),new ot(0,0,-1),new ot(0,1,0),new ot(0,-1,0)],this._cubeUps=[new ot(0,1,0),new ot(0,1,0),new ot(0,1,0),new ot(0,1,0),new ot(0,0,1),new ot(0,0,-1)]}updateMatrices(e,n=0){const r=this.camera,i=this.matrix,s=e.distance||r.far;s!==r.far&&(r.far=s,r.updateProjectionMatrix()),kv.setFromMatrixPosition(e.matrixWorld),r.position.copy(kv),CE.copy(r.position),CE.add(this._cubeDirections[n]),r.up.copy(this._cubeUps[n]),r.lookAt(CE),r.updateMatrixWorld(),i.makeTranslation(-kv.x,-kv.y,-kv.z),l$.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),this._frustum.setFromProjectionMatrix(l$)}}class AMe extends eJ{constructor(e,n,r=0,i=2){super(e,n),this.isPointLight=!0,this.type="PointLight",this.distance=r,this.decay=i,this.shadow=new TMe}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 MMe extends eJ{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}}class jMe extends Rs{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 XF extends fMe{constructor(e,n,r=1){super(e,n),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const n=super.clone(e);return n.meshPerAttribute=this.meshPerAttribute,n}toJSON(e){const n=super.toJSON(e);return n.isInstancedInterleavedBuffer=!0,n.meshPerAttribute=this.meshPerAttribute,n}}class c${constructor(e=1,n=0,r=0){return this.radius=e,this.phi=n,this.theta=r,this}set(e,n,r){return this.radius=e,this.phi=n,this.theta=r,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Math.max(1e-6,Math.min(Math.PI-1e-6,this.phi)),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,n,r){return this.radius=Math.sqrt(e*e+n*n+r*r),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,r),this.phi=Math.acos(as(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const d$=new ot,N1=new ot;class EMe{constructor(e=new ot,n=new ot){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){d$.subVectors(e,this.start),N1.subVectors(this.end,this.start);const r=N1.dot(N1);let s=N1.dot(d$)/r;return n&&(s=as(s,0,1)),s}closestPointToPoint(e,n,r){const i=this.closestPointToPointParameter(e,n);return this.delta(r).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}class DMe extends IP{constructor(e=1){const n=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],r=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new Rs;i.setAttribute("position",new Qa(n,3)),i.setAttribute("color",new Qa(r,3));const s=new Bw({vertexColors:!0,toneMapped:!1});super(i,s),this.type="AxesHelper"}setColors(e,n,r){const i=new An,s=this.geometry.attributes.color.array;return i.set(e),i.toArray(s,0),i.toArray(s,3),i.set(n),i.toArray(s,6),i.toArray(s,9),i.set(r),i.toArray(s,12),i.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:DP}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=DP);class wd{constructor(e,n,r,i,s="div"){this.parent=e,this.object=n,this.property=r,this._disabled=!1,this._hidden=!1,this.initialValue=this.getValue(),this.domElement=document.createElement(s),this.domElement.classList.add("controller"),this.domElement.classList.add(i),this.$name=document.createElement("div"),this.$name.classList.add("name"),wd.nextNameID=wd.nextNameID||0,this.$name.id=`lil-gui-name-${++wd.nextNameID}`,this.$widget=document.createElement("div"),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.domElement.addEventListener("keydown",o=>o.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.textContent=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){const n=this.parent.add(this.object,this.property,e);return n.name(this._name),this.destroy(),n}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.getValue()!==e&&(this.object[this.property]=e,this._callOnChange(),this.updateDisplay()),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class FMe extends wd{constructor(e,n,r){super(e,n,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function QF(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 RMe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:QF,toHexString:QF},W0={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},LMe={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const r=W0.fromHexString(t);e[0]=(r>>16&255)/255*n,e[1]=(r>>8&255)/255*n,e[2]=(r&255)/255*n},toHexString([t,e,n],r=1){r=255/r;const i=t*r<<16^e*r<<8^n*r<<0;return W0.toHexString(i)}},OMe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const r=W0.fromHexString(t);e.r=(r>>16&255)/255*n,e.g=(r>>8&255)/255*n,e.b=(r&255)/255*n},toHexString({r:t,g:e,b:n},r=1){r=255/r;const i=t*r<<16^e*r<<8^n*r<<0;return W0.toHexString(i)}},IMe=[RMe,W0,LMe,OMe];function zMe(t){return IMe.find(e=>e.match(t))}class UMe extends wd{constructor(e,n,r,i){super(e,n,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=zMe(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=QF(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 PE extends wd{constructor(e,n,r){super(e,n,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",i=>{i.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class BMe extends wd{constructor(e,n,r,i,s,o){super(e,n,r,"number"),this._initInput(),this.min(i),this.max(s);const l=o!==void 0;this.step(l?o:this._getImplicitStep(),l),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,n=!0){return this._step=e,this._stepExplicit=n,this}updateDisplay(){const e=this.getValue();if(this._hasSlider){let n=(e-this._min)/(this._max-this._min);n=Math.max(0,Math.min(n,1)),this.$fill.style.width=n*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;const n=()=>{let _=parseFloat(this.$input.value);isNaN(_)||(this._stepExplicit&&(_=this._snap(_)),this.setValue(this._clamp(_)))},r=_=>{const k=parseFloat(this.$input.value);isNaN(k)||(this._snapClampSetValue(k+_),this.$input.value=this.getValue())},i=_=>{_.key==="Enter"&&this.$input.blur(),_.code==="ArrowUp"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_))),_.code==="ArrowDown"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_)*-1))},s=_=>{this._inputFocused&&(_.preventDefault(),r(this._step*this._normalizeMouseWheel(_)))};let o=!1,l,c,d,u,m;const p=5,f=_=>{l=_.clientX,c=d=_.clientY,o=!0,u=this.getValue(),m=0,window.addEventListener("mousemove",y),window.addEventListener("mouseup",v)},y=_=>{if(o){const k=_.clientX-l,P=_.clientY-c;Math.abs(P)>p?(_.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(k)>p&&v()}if(!o){const k=_.clientY-d;m-=k*this._step*this._arrowKeyMultiplier(_),u+m>this._max?m=this._max-u:u+m<this._min&&(m=this._min-u),this._snapClampSetValue(u+m)}d=_.clientY},v=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",v)},b=()=>{this._inputFocused=!0},g=()=>{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",g)}_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=(g,_,k,P,N)=>(g-_)/(k-_)*(N-P)+P,n=g=>{const _=this.$slider.getBoundingClientRect();let k=e(g,_.left,_.right,this._min,this._max);this._snapClampSetValue(k)},r=g=>{this._setDraggingStyle(!0),n(g.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},i=g=>{n(g.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};let o=!1,l,c;const d=g=>{g.preventDefault(),this._setDraggingStyle(!0),n(g.touches[0].clientX),o=!1},u=g=>{g.touches.length>1||(this._hasScrollBar?(l=g.touches[0].clientX,c=g.touches[0].clientY,o=!0):d(g),window.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("touchend",p))},m=g=>{if(o){const _=g.touches[0].clientX-l,k=g.touches[0].clientY-c;Math.abs(_)>Math.abs(k)?d(g):(window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p))}else g.preventDefault(),n(g.touches[0].clientX)},p=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p)},f=this._callOnFinishChange.bind(this),y=400;let v;const b=g=>{if(Math.abs(g.deltaX)<Math.abs(g.deltaY)&&this._hasScrollBar)return;g.preventDefault();const k=this._normalizeMouseWheel(g)*this._step;this._snapClampSetValue(this.getValue()+k),this.$input.value=this.getValue(),clearTimeout(v),v=setTimeout(f,y)};this.$slider.addEventListener("mousedown",r),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:r}=e;return Math.floor(e.deltaY)!==e.deltaY&&e.wheelDelta&&(n=0,r=-e.wheelDelta/120,r*=this._stepExplicit?1:10),n+-r}_arrowKeyMultiplier(e){let n=this._stepExplicit?1:10;return e.shiftKey?n*=10:e.altKey&&(n/=10),n}_snap(e){const n=Math.round(e/this._step)*this._step;return parseFloat(n.toPrecision(15))}_clamp(e){return e<this._min&&(e=this._min),e>this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){const e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}}class HMe extends wd{constructor(e,n,r,i){super(e,n,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.options(i)}options(e){return this._values=Array.isArray(e)?e:Object.values(e),this._names=Array.isArray(e)?e:Object.keys(e),this.$select.replaceChildren(),this._names.forEach(n=>{const r=document.createElement("option");r.textContent=n,this.$select.appendChild(r)}),this.updateDisplay(),this}updateDisplay(){const e=this.getValue(),n=this._values.indexOf(e);return this.$select.selectedIndex=n,this.$display.textContent=n===-1?e:this._names[n],this}}class qMe extends wd{constructor(e,n,r){super(e,n,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("spellcheck","false"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",i=>{i.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}const $Me=`.lil-gui {
  7418. font-family: var(--font-family);
  7419. font-size: var(--font-size);
  7420. line-height: 1;
  7421. font-weight: normal;
  7422. font-style: normal;
  7423. text-align: left;
  7424. color: var(--text-color);
  7425. user-select: none;
  7426. -webkit-user-select: none;
  7427. touch-action: manipulation;
  7428. --background-color: #1f1f1f;
  7429. --text-color: #ebebeb;
  7430. --title-background-color: #111111;
  7431. --title-text-color: #ebebeb;
  7432. --widget-color: #424242;
  7433. --hover-color: #4f4f4f;
  7434. --focus-color: #595959;
  7435. --number-color: #2cc9ff;
  7436. --string-color: #a2db3c;
  7437. --font-size: 11px;
  7438. --input-font-size: 11px;
  7439. --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
  7440. --font-family-mono: Menlo, Monaco, Consolas, "Droid Sans Mono", monospace;
  7441. --padding: 4px;
  7442. --spacing: 4px;
  7443. --widget-height: 20px;
  7444. --title-height: calc(var(--widget-height) + var(--spacing) * 1.25);
  7445. --name-width: 45%;
  7446. --slider-knob-width: 2px;
  7447. --slider-input-width: 27%;
  7448. --color-input-width: 27%;
  7449. --slider-input-min-width: 45px;
  7450. --color-input-min-width: 45px;
  7451. --folder-indent: 7px;
  7452. --widget-padding: 0 0 0 3px;
  7453. --widget-border-radius: 2px;
  7454. --checkbox-size: calc(0.75 * var(--widget-height));
  7455. --scrollbar-width: 5px;
  7456. }
  7457. .lil-gui, .lil-gui * {
  7458. box-sizing: border-box;
  7459. margin: 0;
  7460. padding: 0;
  7461. }
  7462. .lil-gui.root {
  7463. width: var(--width, 245px);
  7464. display: flex;
  7465. flex-direction: column;
  7466. background: var(--background-color);
  7467. }
  7468. .lil-gui.root > .title {
  7469. background: var(--title-background-color);
  7470. color: var(--title-text-color);
  7471. }
  7472. .lil-gui.root > .children {
  7473. overflow-x: hidden;
  7474. overflow-y: auto;
  7475. }
  7476. .lil-gui.root > .children::-webkit-scrollbar {
  7477. width: var(--scrollbar-width);
  7478. height: var(--scrollbar-width);
  7479. background: var(--background-color);
  7480. }
  7481. .lil-gui.root > .children::-webkit-scrollbar-thumb {
  7482. border-radius: var(--scrollbar-width);
  7483. background: var(--focus-color);
  7484. }
  7485. @media (pointer: coarse) {
  7486. .lil-gui.allow-touch-styles, .lil-gui.allow-touch-styles .lil-gui {
  7487. --widget-height: 28px;
  7488. --padding: 6px;
  7489. --spacing: 6px;
  7490. --font-size: 13px;
  7491. --input-font-size: 16px;
  7492. --folder-indent: 10px;
  7493. --scrollbar-width: 7px;
  7494. --slider-input-min-width: 50px;
  7495. --color-input-min-width: 65px;
  7496. }
  7497. }
  7498. .lil-gui.force-touch-styles, .lil-gui.force-touch-styles .lil-gui {
  7499. --widget-height: 28px;
  7500. --padding: 6px;
  7501. --spacing: 6px;
  7502. --font-size: 13px;
  7503. --input-font-size: 16px;
  7504. --folder-indent: 10px;
  7505. --scrollbar-width: 7px;
  7506. --slider-input-min-width: 50px;
  7507. --color-input-min-width: 65px;
  7508. }
  7509. .lil-gui.autoPlace {
  7510. max-height: 100%;
  7511. position: fixed;
  7512. top: 0;
  7513. right: 15px;
  7514. z-index: 1001;
  7515. }
  7516. .lil-gui .controller {
  7517. display: flex;
  7518. align-items: center;
  7519. padding: 0 var(--padding);
  7520. margin: var(--spacing) 0;
  7521. }
  7522. .lil-gui .controller.disabled {
  7523. opacity: 0.5;
  7524. }
  7525. .lil-gui .controller.disabled, .lil-gui .controller.disabled * {
  7526. pointer-events: none !important;
  7527. }
  7528. .lil-gui .controller > .name {
  7529. min-width: var(--name-width);
  7530. flex-shrink: 0;
  7531. white-space: pre;
  7532. padding-right: var(--spacing);
  7533. line-height: var(--widget-height);
  7534. }
  7535. .lil-gui .controller .widget {
  7536. position: relative;
  7537. display: flex;
  7538. align-items: center;
  7539. width: 100%;
  7540. min-height: var(--widget-height);
  7541. }
  7542. .lil-gui .controller.string input {
  7543. color: var(--string-color);
  7544. }
  7545. .lil-gui .controller.boolean {
  7546. cursor: pointer;
  7547. }
  7548. .lil-gui .controller.color .display {
  7549. width: 100%;
  7550. height: var(--widget-height);
  7551. border-radius: var(--widget-border-radius);
  7552. position: relative;
  7553. }
  7554. @media (hover: hover) {
  7555. .lil-gui .controller.color .display:hover:before {
  7556. content: " ";
  7557. display: block;
  7558. position: absolute;
  7559. border-radius: var(--widget-border-radius);
  7560. border: 1px solid #fff9;
  7561. top: 0;
  7562. right: 0;
  7563. bottom: 0;
  7564. left: 0;
  7565. }
  7566. }
  7567. .lil-gui .controller.color input[type=color] {
  7568. opacity: 0;
  7569. width: 100%;
  7570. height: 100%;
  7571. cursor: pointer;
  7572. }
  7573. .lil-gui .controller.color input[type=text] {
  7574. margin-left: var(--spacing);
  7575. font-family: var(--font-family-mono);
  7576. min-width: var(--color-input-min-width);
  7577. width: var(--color-input-width);
  7578. flex-shrink: 0;
  7579. }
  7580. .lil-gui .controller.option select {
  7581. opacity: 0;
  7582. position: absolute;
  7583. width: 100%;
  7584. max-width: 100%;
  7585. }
  7586. .lil-gui .controller.option .display {
  7587. position: relative;
  7588. pointer-events: none;
  7589. border-radius: var(--widget-border-radius);
  7590. height: var(--widget-height);
  7591. line-height: var(--widget-height);
  7592. max-width: 100%;
  7593. overflow: hidden;
  7594. word-break: break-all;
  7595. padding-left: 0.55em;
  7596. padding-right: 1.75em;
  7597. background: var(--widget-color);
  7598. }
  7599. @media (hover: hover) {
  7600. .lil-gui .controller.option .display.focus {
  7601. background: var(--focus-color);
  7602. }
  7603. }
  7604. .lil-gui .controller.option .display.active {
  7605. background: var(--focus-color);
  7606. }
  7607. .lil-gui .controller.option .display:after {
  7608. font-family: "lil-gui";
  7609. content: "↕";
  7610. position: absolute;
  7611. top: 0;
  7612. right: 0;
  7613. bottom: 0;
  7614. padding-right: 0.375em;
  7615. }
  7616. .lil-gui .controller.option .widget,
  7617. .lil-gui .controller.option select {
  7618. cursor: pointer;
  7619. }
  7620. @media (hover: hover) {
  7621. .lil-gui .controller.option .widget:hover .display {
  7622. background: var(--hover-color);
  7623. }
  7624. }
  7625. .lil-gui .controller.number input {
  7626. color: var(--number-color);
  7627. }
  7628. .lil-gui .controller.number.hasSlider input {
  7629. margin-left: var(--spacing);
  7630. width: var(--slider-input-width);
  7631. min-width: var(--slider-input-min-width);
  7632. flex-shrink: 0;
  7633. }
  7634. .lil-gui .controller.number .slider {
  7635. width: 100%;
  7636. height: var(--widget-height);
  7637. background: var(--widget-color);
  7638. border-radius: var(--widget-border-radius);
  7639. padding-right: var(--slider-knob-width);
  7640. overflow: hidden;
  7641. cursor: ew-resize;
  7642. touch-action: pan-y;
  7643. }
  7644. @media (hover: hover) {
  7645. .lil-gui .controller.number .slider:hover {
  7646. background: var(--hover-color);
  7647. }
  7648. }
  7649. .lil-gui .controller.number .slider.active {
  7650. background: var(--focus-color);
  7651. }
  7652. .lil-gui .controller.number .slider.active .fill {
  7653. opacity: 0.95;
  7654. }
  7655. .lil-gui .controller.number .fill {
  7656. height: 100%;
  7657. border-right: var(--slider-knob-width) solid var(--number-color);
  7658. box-sizing: content-box;
  7659. }
  7660. .lil-gui-dragging .lil-gui {
  7661. --hover-color: var(--widget-color);
  7662. }
  7663. .lil-gui-dragging * {
  7664. cursor: ew-resize !important;
  7665. }
  7666. .lil-gui-dragging.lil-gui-vertical * {
  7667. cursor: ns-resize !important;
  7668. }
  7669. .lil-gui .title {
  7670. height: var(--title-height);
  7671. line-height: calc(var(--title-height) - 4px);
  7672. font-weight: 600;
  7673. padding: 0 var(--padding);
  7674. -webkit-tap-highlight-color: transparent;
  7675. cursor: pointer;
  7676. outline: none;
  7677. text-decoration-skip: objects;
  7678. }
  7679. .lil-gui .title:before {
  7680. font-family: "lil-gui";
  7681. content: "▾";
  7682. padding-right: 2px;
  7683. display: inline-block;
  7684. }
  7685. .lil-gui .title:active {
  7686. background: var(--title-background-color);
  7687. opacity: 0.75;
  7688. }
  7689. @media (hover: hover) {
  7690. body:not(.lil-gui-dragging) .lil-gui .title:hover {
  7691. background: var(--title-background-color);
  7692. opacity: 0.85;
  7693. }
  7694. .lil-gui .title:focus {
  7695. text-decoration: underline var(--focus-color);
  7696. }
  7697. }
  7698. .lil-gui.root > .title:focus {
  7699. text-decoration: none !important;
  7700. }
  7701. .lil-gui.closed > .title:before {
  7702. content: "▸";
  7703. }
  7704. .lil-gui.closed > .children {
  7705. transform: translateY(-7px);
  7706. opacity: 0;
  7707. }
  7708. .lil-gui.closed:not(.transition) > .children {
  7709. display: none;
  7710. }
  7711. .lil-gui.transition > .children {
  7712. transition-duration: 300ms;
  7713. transition-property: height, opacity, transform;
  7714. transition-timing-function: cubic-bezier(0.2, 0.6, 0.35, 1);
  7715. overflow: hidden;
  7716. pointer-events: none;
  7717. }
  7718. .lil-gui .children:empty:before {
  7719. content: "Empty";
  7720. padding: 0 var(--padding);
  7721. margin: var(--spacing) 0;
  7722. display: block;
  7723. height: var(--widget-height);
  7724. font-style: italic;
  7725. line-height: var(--widget-height);
  7726. opacity: 0.5;
  7727. }
  7728. .lil-gui.root > .children > .lil-gui > .title {
  7729. border: 0 solid var(--widget-color);
  7730. border-width: 1px 0;
  7731. transition: border-color 300ms;
  7732. }
  7733. .lil-gui.root > .children > .lil-gui.closed > .title {
  7734. border-bottom-color: transparent;
  7735. }
  7736. .lil-gui + .controller {
  7737. border-top: 1px solid var(--widget-color);
  7738. margin-top: 0;
  7739. padding-top: var(--spacing);
  7740. }
  7741. .lil-gui .lil-gui .lil-gui > .title {
  7742. border: none;
  7743. }
  7744. .lil-gui .lil-gui .lil-gui > .children {
  7745. border: none;
  7746. margin-left: var(--folder-indent);
  7747. border-left: 2px solid var(--widget-color);
  7748. }
  7749. .lil-gui .lil-gui .controller {
  7750. border: none;
  7751. }
  7752. .lil-gui label, .lil-gui input, .lil-gui button {
  7753. -webkit-tap-highlight-color: transparent;
  7754. }
  7755. .lil-gui input {
  7756. border: 0;
  7757. outline: none;
  7758. font-family: var(--font-family);
  7759. font-size: var(--input-font-size);
  7760. border-radius: var(--widget-border-radius);
  7761. height: var(--widget-height);
  7762. background: var(--widget-color);
  7763. color: var(--text-color);
  7764. width: 100%;
  7765. }
  7766. @media (hover: hover) {
  7767. .lil-gui input:hover {
  7768. background: var(--hover-color);
  7769. }
  7770. .lil-gui input:active {
  7771. background: var(--focus-color);
  7772. }
  7773. }
  7774. .lil-gui input:disabled {
  7775. opacity: 1;
  7776. }
  7777. .lil-gui input[type=text],
  7778. .lil-gui input[type=number] {
  7779. padding: var(--widget-padding);
  7780. -moz-appearance: textfield;
  7781. }
  7782. .lil-gui input[type=text]:focus,
  7783. .lil-gui input[type=number]:focus {
  7784. background: var(--focus-color);
  7785. }
  7786. .lil-gui input[type=checkbox] {
  7787. appearance: none;
  7788. width: var(--checkbox-size);
  7789. height: var(--checkbox-size);
  7790. border-radius: var(--widget-border-radius);
  7791. text-align: center;
  7792. cursor: pointer;
  7793. }
  7794. .lil-gui input[type=checkbox]:checked:before {
  7795. font-family: "lil-gui";
  7796. content: "✓";
  7797. font-size: var(--checkbox-size);
  7798. line-height: var(--checkbox-size);
  7799. }
  7800. @media (hover: hover) {
  7801. .lil-gui input[type=checkbox]:focus {
  7802. box-shadow: inset 0 0 0 1px var(--focus-color);
  7803. }
  7804. }
  7805. .lil-gui button {
  7806. outline: none;
  7807. cursor: pointer;
  7808. font-family: var(--font-family);
  7809. font-size: var(--font-size);
  7810. color: var(--text-color);
  7811. width: 100%;
  7812. height: var(--widget-height);
  7813. text-transform: none;
  7814. background: var(--widget-color);
  7815. border-radius: var(--widget-border-radius);
  7816. border: none;
  7817. }
  7818. @media (hover: hover) {
  7819. .lil-gui button:hover {
  7820. background: var(--hover-color);
  7821. }
  7822. .lil-gui button:focus {
  7823. box-shadow: inset 0 0 0 1px var(--focus-color);
  7824. }
  7825. }
  7826. .lil-gui button:active {
  7827. background: var(--focus-color);
  7828. }
  7829. @font-face {
  7830. font-family: "lil-gui";
  7831. 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");
  7832. }`;function VMe(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 u$=!1;class yN{constructor({parent:e,autoPlace:n=e===void 0,container:r,width:i,title:s="Controls",closeFolders:o=!1,injectStyles:l=!0,touchStyles:c=!0}={}){if(this.parent=e,this.root=e?e.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",d=>{(d.code==="Enter"||d.code==="Space")&&(d.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{},{passive:!0}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(s),this.parent){this.parent.children.push(this),this.parent.folders.push(this),this.parent.$children.appendChild(this.domElement);return}this.domElement.classList.add("root"),c&&this.domElement.classList.add("allow-touch-styles"),!u$&&l&&(VMe($Me),u$=!0),r?r.appendChild(this.domElement):n&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),i&&this.domElement.style.setProperty("--width",i+"px"),this._closeFolders=o}add(e,n,r,i,s){if(Object(r)===r)return new HMe(this,e,n,r);const o=e[n];switch(typeof o){case"number":return new BMe(this,e,n,r,i,s);case"boolean":return new FMe(this,e,n);case"string":return new qMe(this,e,n);case"function":return new PE(this,e,n)}console.error(`gui.add failed
  7833. property:`,n,`
  7834. object:`,e,`
  7835. value:`,o)}addColor(e,n,r=1){return new UMe(this,e,n,r)}addFolder(e){const n=new yN({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(r=>{r instanceof PE||r._name in e.controllers&&r.load(e.controllers[r._name])}),n&&e.folders&&this.folders.forEach(r=>{r._title in e.folders&&r.load(e.folders[r._title])}),this}save(e=!0){const n={controllers:{},folders:{}};return this.controllers.forEach(r=>{if(!(r instanceof PE)){if(r._name in n.controllers)throw new Error(`Cannot save GUI with duplicate property "${r._name}"`);n.controllers[r._name]=r.save()}}),e&&this.folders.forEach(r=>{if(r._title in n.folders)throw new Error(`Cannot save GUI with duplicate folder "${r._title}"`);n.folders[r._title]=r.save()}),n}open(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}_setClosed(e){this._closed!==e&&(this._closed=e,this._callOnOpenClose(this))}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const n=this.$children.clientHeight;this.$children.style.height=n+"px",this.domElement.classList.add("transition");const r=s=>{s.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",r))};this.$children.addEventListener("transitionend",r);const i=e?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!e),requestAnimationFrame(()=>{this.$children.style.height=i+"px"})}),this}title(e){return this._title=e,this.$title.textContent=e,this}reset(e=!0){return(e?this.controllersRecursive():this.controllers).forEach(r=>r.reset()),this}onChange(e){return this._onChange=e,this}_callOnChange(e){this.parent&&this.parent._callOnChange(e),this._onChange!==void 0&&this._onChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(e){this.parent&&this.parent._callOnFinishChange(e),this._onFinishChange!==void 0&&this._onFinishChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onOpenClose(e){return this._onOpenClose=e,this}_callOnOpenClose(e){this.parent&&this.parent._callOnOpenClose(e),this._onOpenClose!==void 0&&this._onOpenClose.call(this,e)}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(e=>e.destroy())}controllersRecursive(){let e=Array.from(this.controllers);return this.folders.forEach(n=>{e=e.concat(n.controllersRecursive())}),e}foldersRecursive(){let e=Array.from(this.folders);return this.folders.forEach(n=>{e=e.concat(n.foldersRecursive())}),e}}function TE(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(d){try{c(r.next(d))}catch(u){s(u)}}function l(d){try{c(r.throw(d))}catch(u){s(u)}}function c(d){var u;d.done?i(d.value):(u=d.value,u instanceof n?u:new n((function(m){m(u)}))).then(o,l)}c((r=r.apply(t,[])).next())}))}class WO{constructor(e,n,r,i){this.size=e,this.width=n,this.height=r,this.charLength=i,this.chars=""}static parse(e){const n=e.split(" "),r=n[0],i=r.split("x");return new WO(r,+i[0],+i[1],+n[1])}get src(){return"data:image/jpeg;base64,"+this.chars}get isValid(){return this.chars.length==this.charLength&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(this.chars)}}class KO{constructor(e,n,r,i){this.src=e,this.gcode=n,this.params=r,this.comment=i}}class m$ extends KO{constructor(e,n,r,i){super(e,n,r,i),this.params=r}}class Zm extends KO{constructor(e,n,r,i){super(e,n,void 0,r),this.toolIndex=i}}class h${constructor(e,n,r,i=0){this.layer=e,this.commands=n,this.lineNumber=r,this.height=i}}class vN{constructor(e){this.lines=[],this.preamble=new h$(-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(`
  7836. `);this.lines=this.lines.concat(n);const r=this.lines2commands(n);this.groupIntoLayers(r);const i=this.parseMetadata(r.filter((s=>s.comment))).thumbnails;for(const[s,o]of Object.entries(i))this.metadata.thumbnails[s]=o;return{layers:this.layers,metadata:this.metadata}}lines2commands(e){return e.map((n=>this.parseCommand(n)))}parseCommand(e,n=!0){var r;const i=e.trim().split(";"),s=i[0],o=n&&i[1]||void 0,l=s.split(/([a-zA-Z])/g).slice(1).map((u=>u.trim())),c=l.length?`${(r=l[0])===null||r===void 0?void 0:r.toLowerCase()}${l[1]}`:"",d=this.parseParams(l.slice(2));switch(c){case"g0":case"g00":case"g1":case"g01":case"g2":case"g02":case"g3":case"g03":return new m$(e,c,d,o);case"t0":return new Zm(e,c,o,0);case"t1":return new Zm(e,c,o,1);case"t2":return new Zm(e,c,o,2);case"t3":return new Zm(e,c,o,3);case"t4":return new Zm(e,c,o,4);case"t5":return new Zm(e,c,o,5);case"t6":return new Zm(e,c,o,6);case"t7":return new Zm(e,c,o,7);default:return new KO(e,c,d,o)}}parseMove(e){return e.reduce(((n,r)=>{const i=r.charAt(0).toLowerCase();return i!="x"&&i!="y"&&i!="z"&&i!="e"&&i!="r"&&i!="f"&&i!="i"&&i!="j"||(n[i]=parseFloat(r.slice(1))),n}),{})}isAlpha(e){const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90}parseParams(e){return e.reduce(((n,r,i,s)=>{if(i%2==0)return n;let o=s[i-1];return o=o.toLowerCase(),this.isAlpha(o)&&(n[o]=parseFloat(r)),n}),{})}groupIntoLayers(e){var n;for(let r=0;r<e.length;r++){const i=e[r];if(i instanceof m$){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 h$(this.layers.length,[],r,o))}}this.maxLayer.commands.push(i)}return this.layers}get maxLayer(){var e;return(e=this.layers[this.layers.length-1])!==null&&e!==void 0?e:this.preamble}parseMetadata(e){const n={};let r;for(const i of e){const s=i.comment;if(!s)continue;const o=s.indexOf("thumbnail begin"),l=s.indexOf("thumbnail end");o>-1?r=WO.parse(s.slice(o+15).trim()):r&&(l==-1?r.chars+=s.trim():(r.isValid&&(n[r.size]=r),r=void 0))}return{thumbnails:n}}}vN.prototype.parseGcode=vN.prototype.parseGCode;const p$={type:"change"},AE={type:"start"},f$={type:"end"},C1=new HO,g$=new ah,GMe=Math.cos(70*FZ.DEG2RAD);class WMe extends ug{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new ot,this.cursor=new ot,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:ub.ROTATE,MIDDLE:ub.DOLLY,RIGHT:ub.PAN},this.touches={ONE:mb.ROTATE,TWO:mb.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(){r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=function(){r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(p$),r.update(),s=i.NONE},this.update=(function(){const G=new ot,Q=new Gf().setFromUnitVectors(e.up,new ot(0,1,0)),V=Q.clone().invert(),J=new ot,ie=new Gf,he=new ot,fe=2*Math.PI;return function(se=null){const U=r.object.position;G.copy(U).sub(r.target),G.applyQuaternion(Q),l.setFromVector3(G),r.autoRotate&&s===i.NONE&&F((function(we){return we!==null?2*Math.PI/60*r.autoRotateSpeed*we:2*Math.PI/60/60*r.autoRotateSpeed})(se)),r.enableDamping?(l.theta+=c.theta*r.dampingFactor,l.phi+=c.phi*r.dampingFactor):(l.theta+=c.theta,l.phi+=c.phi);let R=r.minAzimuthAngle,re=r.maxAzimuthAngle;isFinite(R)&&isFinite(re)&&(R<-Math.PI?R+=fe:R>Math.PI&&(R-=fe),re<-Math.PI?re+=fe:re>Math.PI&&(re-=fe),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(r.minPolarAngle,Math.min(r.maxPolarAngle,l.phi)),l.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(u,r.dampingFactor):r.target.add(u),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&M||r.object.isOrthographicCamera?l.radius=me(l.radius):l.radius=me(l.radius*d),G.setFromSpherical(l),G.applyQuaternion(V),U.copy(r.target).add(G),r.object.lookAt(r.target),r.enableDamping===!0?(c.theta*=1-r.dampingFactor,c.phi*=1-r.dampingFactor,u.multiplyScalar(1-r.dampingFactor)):(c.set(0,0,0),u.set(0,0,0));let xe=!1;if(r.zoomToCursor&&M){let we=null;if(r.object.isPerspectiveCamera){const ye=G.length();we=me(ye*d);const Ae=ye-we;r.object.position.addScaledVector(P,Ae),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const ye=new ot(N.x,N.y,0);ye.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/d)),r.object.updateProjectionMatrix(),xe=!0;const Ae=new ot(N.x,N.y,0);Ae.unproject(r.object),r.object.position.sub(Ae).add(ye),r.object.updateMatrixWorld(),we=G.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;we!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(we).add(r.object.position):(C1.origin.copy(r.object.position),C1.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(C1.direction))<GMe?e.lookAt(r.target):(g$.setFromNormalAndCoplanarPoint(r.object.up,r.target),C1.intersectPlane(g$,r.target))))}else r.object.isOrthographicCamera&&(r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/d)),r.object.updateProjectionMatrix(),xe=!0);return d=1,M=!1,!!(xe||J.distanceToSquared(r.object.position)>o||8*(1-ie.dot(r.object.quaternion))>o||he.distanceToSquared(r.target)>0)&&(r.dispatchEvent(p$),J.copy(r.object.position),ie.copy(r.object.quaternion),he.copy(r.target),!0)}})(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",q),r.domElement.removeEventListener("pointerdown",Y),r.domElement.removeEventListener("pointercancel",j),r.domElement.removeEventListener("wheel",z),r.domElement.removeEventListener("pointermove",D),r.domElement.removeEventListener("pointerup",j),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",W),r._domElementKeyEvents=null)};const r=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=i.NONE;const o=1e-6,l=new c$,c=new c$;let d=1;const u=new ot,m=new Hn,p=new Hn,f=new Hn,y=new Hn,v=new Hn,b=new Hn,g=new Hn,_=new Hn,k=new Hn,P=new ot,N=new Hn;let M=!1;const A=[],T={};function C(){return Math.pow(.95,r.zoomSpeed)}function F(G){c.theta-=G}function $(G){c.phi-=G}const I=(function(){const G=new ot;return function(Q,V){G.setFromMatrixColumn(V,0),G.multiplyScalar(-Q),u.add(G)}})(),X=(function(){const G=new ot;return function(Q,V){r.screenSpacePanning===!0?G.setFromMatrixColumn(V,1):(G.setFromMatrixColumn(V,0),G.crossVectors(r.object.up,G)),G.multiplyScalar(Q),u.add(G)}})(),L=(function(){const G=new ot;return function(Q,V){const J=r.domElement;if(r.object.isPerspectiveCamera){const ie=r.object.position;G.copy(ie).sub(r.target);let he=G.length();he*=Math.tan(r.object.fov/2*Math.PI/180),I(2*Q*he/J.clientHeight,r.object.matrix),X(2*V*he/J.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(I(Q*(r.object.right-r.object.left)/r.object.zoom/J.clientWidth,r.object.matrix),X(V*(r.object.top-r.object.bottom)/r.object.zoom/J.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function te(G){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?d/=G:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ae(G){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?d*=G:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ee(G){if(!r.zoomToCursor)return;M=!0;const Q=r.domElement.getBoundingClientRect(),V=G.clientX-Q.left,J=G.clientY-Q.top,ie=Q.width,he=Q.height;N.x=V/ie*2-1,N.y=-J/he*2+1,P.set(N.x,N.y,1).unproject(r.object).sub(r.object.position).normalize()}function me(G){return Math.max(r.minDistance,Math.min(r.maxDistance,G))}function le(G){m.set(G.clientX,G.clientY)}function ue(G){y.set(G.clientX,G.clientY)}function K(){if(A.length===1)m.set(A[0].pageX,A[0].pageY);else{const G=.5*(A[0].pageX+A[1].pageX),Q=.5*(A[0].pageY+A[1].pageY);m.set(G,Q)}}function ne(){if(A.length===1)y.set(A[0].pageX,A[0].pageY);else{const G=.5*(A[0].pageX+A[1].pageX),Q=.5*(A[0].pageY+A[1].pageY);y.set(G,Q)}}function oe(){const G=A[0].pageX-A[1].pageX,Q=A[0].pageY-A[1].pageY,V=Math.sqrt(G*G+Q*Q);g.set(0,V)}function be(G){if(A.length==1)p.set(G.pageX,G.pageY);else{const V=O(G),J=.5*(G.pageX+V.x),ie=.5*(G.pageY+V.y);p.set(J,ie)}f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const Q=r.domElement;F(2*Math.PI*f.x/Q.clientHeight),$(2*Math.PI*f.y/Q.clientHeight),m.copy(p)}function _e(G){if(A.length===1)v.set(G.pageX,G.pageY);else{const Q=O(G),V=.5*(G.pageX+Q.x),J=.5*(G.pageY+Q.y);v.set(V,J)}b.subVectors(v,y).multiplyScalar(r.panSpeed),L(b.x,b.y),y.copy(v)}function B(G){const Q=O(G),V=G.pageX-Q.x,J=G.pageY-Q.y,ie=Math.sqrt(V*V+J*J);_.set(0,ie),k.set(0,Math.pow(_.y/g.y,r.zoomSpeed)),te(k.y),g.copy(_)}function Y(G){r.enabled!==!1&&(A.length===0&&(r.domElement.setPointerCapture(G.pointerId),r.domElement.addEventListener("pointermove",D),r.domElement.addEventListener("pointerup",j)),(function(Q){A.push(Q)})(G),G.pointerType==="touch"?(function(Q){switch(de(Q),A.length){case 1:switch(r.touches.ONE){case mb.ROTATE:if(r.enableRotate===!1)return;K(),s=i.TOUCH_ROTATE;break;case mb.PAN:if(r.enablePan===!1)return;ne(),s=i.TOUCH_PAN;break;default:s=i.NONE}break;case 2:switch(r.touches.TWO){case mb.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;r.enableZoom&&oe(),r.enablePan&&ne(),s=i.TOUCH_DOLLY_PAN;break;case mb.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;r.enableZoom&&oe(),r.enableRotate&&K(),s=i.TOUCH_DOLLY_ROTATE;break;default:s=i.NONE}break;default:s=i.NONE}s!==i.NONE&&r.dispatchEvent(AE)})(G):(function(Q){let V;switch(Q.button){case 0:V=r.mouseButtons.LEFT;break;case 1:V=r.mouseButtons.MIDDLE;break;case 2:V=r.mouseButtons.RIGHT;break;default:V=-1}switch(V){case ub.DOLLY:if(r.enableZoom===!1)return;(function(J){ee(J),g.set(J.clientX,J.clientY)})(Q),s=i.DOLLY;break;case ub.ROTATE:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(r.enablePan===!1)return;ue(Q),s=i.PAN}else{if(r.enableRotate===!1)return;le(Q),s=i.ROTATE}break;case ub.PAN:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(r.enableRotate===!1)return;le(Q),s=i.ROTATE}else{if(r.enablePan===!1)return;ue(Q),s=i.PAN}break;default:s=i.NONE}s!==i.NONE&&r.dispatchEvent(AE)})(G))}function D(G){r.enabled!==!1&&(G.pointerType==="touch"?(function(Q){switch(de(Q),s){case i.TOUCH_ROTATE:if(r.enableRotate===!1)return;be(Q),r.update();break;case i.TOUCH_PAN:if(r.enablePan===!1)return;_e(Q),r.update();break;case i.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;(function(V){r.enableZoom&&B(V),r.enablePan&&_e(V)})(Q),r.update();break;case i.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;(function(V){r.enableZoom&&B(V),r.enableRotate&&be(V)})(Q),r.update();break;default:s=i.NONE}})(G):(function(Q){switch(s){case i.ROTATE:if(r.enableRotate===!1)return;(function(V){p.set(V.clientX,V.clientY),f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const J=r.domElement;F(2*Math.PI*f.x/J.clientHeight),$(2*Math.PI*f.y/J.clientHeight),m.copy(p),r.update()})(Q);break;case i.DOLLY:if(r.enableZoom===!1)return;(function(V){_.set(V.clientX,V.clientY),k.subVectors(_,g),k.y>0?te(C()):k.y<0&&ae(C()),g.copy(_),r.update()})(Q);break;case i.PAN:if(r.enablePan===!1)return;(function(V){v.set(V.clientX,V.clientY),b.subVectors(v,y).multiplyScalar(r.panSpeed),L(b.x,b.y),y.copy(v),r.update()})(Q)}})(G))}function j(G){(function(Q){delete T[Q.pointerId];for(let V=0;V<A.length;V++)if(A[V].pointerId==Q.pointerId)return void A.splice(V,1)})(G),A.length===0&&(r.domElement.releasePointerCapture(G.pointerId),r.domElement.removeEventListener("pointermove",D),r.domElement.removeEventListener("pointerup",j)),r.dispatchEvent(f$),s=i.NONE}function z(G){r.enabled!==!1&&r.enableZoom!==!1&&s===i.NONE&&(G.preventDefault(),r.dispatchEvent(AE),(function(Q){ee(Q),Q.deltaY<0?ae(C()):Q.deltaY>0&&te(C()),r.update()})(G),r.dispatchEvent(f$))}function W(G){r.enabled!==!1&&r.enablePan!==!1&&(function(Q){let V=!1;switch(Q.code){case r.keys.UP:Q.ctrlKey||Q.metaKey||Q.shiftKey?$(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,r.keyPanSpeed),V=!0;break;case r.keys.BOTTOM:Q.ctrlKey||Q.metaKey||Q.shiftKey?$(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,-r.keyPanSpeed),V=!0;break;case r.keys.LEFT:Q.ctrlKey||Q.metaKey||Q.shiftKey?F(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(r.keyPanSpeed,0),V=!0;break;case r.keys.RIGHT:Q.ctrlKey||Q.metaKey||Q.shiftKey?F(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(-r.keyPanSpeed,0),V=!0}V&&(Q.preventDefault(),r.update())})(G)}function q(G){r.enabled!==!1&&G.preventDefault()}function de(G){let Q=T[G.pointerId];Q===void 0&&(Q=new Hn,T[G.pointerId]=Q),Q.set(G.pageX,G.pageY)}function O(G){const Q=G.pointerId===A[0].pointerId?A[1]:A[0];return T[Q.pointerId]}r.domElement.addEventListener("contextmenu",q),r.domElement.addEventListener("pointerdown",Y),r.domElement.addEventListener("pointercancel",j),r.domElement.addEventListener("wheel",z,{passive:!1}),this.update()}}Yt.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Hn(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},wo.line={uniforms:qO.merge([Yt.common,Yt.fog,Yt.line]),vertexShader:`
  7837. #include <common>
  7838. #include <color_pars_vertex>
  7839. #include <fog_pars_vertex>
  7840. #include <logdepthbuf_pars_vertex>
  7841. #include <clipping_planes_pars_vertex>
  7842. uniform float linewidth;
  7843. uniform vec2 resolution;
  7844. attribute vec3 instanceStart;
  7845. attribute vec3 instanceEnd;
  7846. attribute vec3 instanceColorStart;
  7847. attribute vec3 instanceColorEnd;
  7848. #ifdef WORLD_UNITS
  7849. varying vec4 worldPos;
  7850. varying vec3 worldStart;
  7851. varying vec3 worldEnd;
  7852. #ifdef USE_DASH
  7853. varying vec2 vUv;
  7854. #endif
  7855. #else
  7856. varying vec2 vUv;
  7857. #endif
  7858. #ifdef USE_DASH
  7859. uniform float dashScale;
  7860. attribute float instanceDistanceStart;
  7861. attribute float instanceDistanceEnd;
  7862. varying float vLineDistance;
  7863. #endif
  7864. void trimSegment( const in vec4 start, inout vec4 end ) {
  7865. // trim end segment so it terminates between the camera plane and the near plane
  7866. // conservative estimate of the near plane
  7867. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  7868. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  7869. float nearEstimate = - 0.5 * b / a;
  7870. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  7871. end.xyz = mix( start.xyz, end.xyz, alpha );
  7872. }
  7873. void main() {
  7874. #ifdef USE_COLOR
  7875. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  7876. #endif
  7877. #ifdef USE_DASH
  7878. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  7879. vUv = uv;
  7880. #endif
  7881. float aspect = resolution.x / resolution.y;
  7882. // camera space
  7883. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  7884. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  7885. #ifdef WORLD_UNITS
  7886. worldStart = start.xyz;
  7887. worldEnd = end.xyz;
  7888. #else
  7889. vUv = uv;
  7890. #endif
  7891. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7892. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7893. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7894. // perhaps there is a more elegant solution -- WestLangley
  7895. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  7896. if ( perspective ) {
  7897. if ( start.z < 0.0 && end.z >= 0.0 ) {
  7898. trimSegment( start, end );
  7899. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  7900. trimSegment( end, start );
  7901. }
  7902. }
  7903. // clip space
  7904. vec4 clipStart = projectionMatrix * start;
  7905. vec4 clipEnd = projectionMatrix * end;
  7906. // ndc space
  7907. vec3 ndcStart = clipStart.xyz / clipStart.w;
  7908. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  7909. // direction
  7910. vec2 dir = ndcEnd.xy - ndcStart.xy;
  7911. // account for clip-space aspect ratio
  7912. dir.x *= aspect;
  7913. dir = normalize( dir );
  7914. #ifdef WORLD_UNITS
  7915. // get the offset direction as perpendicular to the view vector
  7916. vec3 worldDir = normalize( end.xyz - start.xyz );
  7917. vec3 offset;
  7918. if ( position.y < 0.5 ) {
  7919. offset = normalize( cross( start.xyz, worldDir ) );
  7920. } else {
  7921. offset = normalize( cross( end.xyz, worldDir ) );
  7922. }
  7923. // sign flip
  7924. if ( position.x < 0.0 ) offset *= - 1.0;
  7925. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  7926. // don't extend the line if we're rendering dashes because we
  7927. // won't be rendering the endcaps
  7928. #ifndef USE_DASH
  7929. // extend the line bounds to encompass endcaps
  7930. start.xyz += - worldDir * linewidth * 0.5;
  7931. end.xyz += worldDir * linewidth * 0.5;
  7932. // shift the position of the quad so it hugs the forward edge of the line
  7933. offset.xy -= dir * forwardOffset;
  7934. offset.z += 0.5;
  7935. #endif
  7936. // endcaps
  7937. if ( position.y > 1.0 || position.y < 0.0 ) {
  7938. offset.xy += dir * 2.0 * forwardOffset;
  7939. }
  7940. // adjust for linewidth
  7941. offset *= linewidth * 0.5;
  7942. // set the world position
  7943. worldPos = ( position.y < 0.5 ) ? start : end;
  7944. worldPos.xyz += offset;
  7945. // project the worldpos
  7946. vec4 clip = projectionMatrix * worldPos;
  7947. // shift the depth of the projected points so the line
  7948. // segments overlap neatly
  7949. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  7950. clip.z = clipPose.z * clip.w;
  7951. #else
  7952. vec2 offset = vec2( dir.y, - dir.x );
  7953. // undo aspect ratio adjustment
  7954. dir.x /= aspect;
  7955. offset.x /= aspect;
  7956. // sign flip
  7957. if ( position.x < 0.0 ) offset *= - 1.0;
  7958. // endcaps
  7959. if ( position.y < 0.0 ) {
  7960. offset += - dir;
  7961. } else if ( position.y > 1.0 ) {
  7962. offset += dir;
  7963. }
  7964. // adjust for linewidth
  7965. offset *= linewidth;
  7966. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7967. offset /= resolution.y;
  7968. // select end
  7969. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  7970. // back to clip space
  7971. offset *= clip.w;
  7972. clip.xy += offset;
  7973. #endif
  7974. gl_Position = clip;
  7975. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  7976. #include <logdepthbuf_vertex>
  7977. #include <clipping_planes_vertex>
  7978. #include <fog_vertex>
  7979. }
  7980. `,fragmentShader:`
  7981. uniform vec3 diffuse;
  7982. uniform float opacity;
  7983. uniform float linewidth;
  7984. #ifdef USE_DASH
  7985. uniform float dashOffset;
  7986. uniform float dashSize;
  7987. uniform float gapSize;
  7988. #endif
  7989. varying float vLineDistance;
  7990. #ifdef WORLD_UNITS
  7991. varying vec4 worldPos;
  7992. varying vec3 worldStart;
  7993. varying vec3 worldEnd;
  7994. #ifdef USE_DASH
  7995. varying vec2 vUv;
  7996. #endif
  7997. #else
  7998. varying vec2 vUv;
  7999. #endif
  8000. #include <common>
  8001. #include <color_pars_fragment>
  8002. #include <fog_pars_fragment>
  8003. #include <logdepthbuf_pars_fragment>
  8004. #include <clipping_planes_pars_fragment>
  8005. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  8006. float mua;
  8007. float mub;
  8008. vec3 p13 = p1 - p3;
  8009. vec3 p43 = p4 - p3;
  8010. vec3 p21 = p2 - p1;
  8011. float d1343 = dot( p13, p43 );
  8012. float d4321 = dot( p43, p21 );
  8013. float d1321 = dot( p13, p21 );
  8014. float d4343 = dot( p43, p43 );
  8015. float d2121 = dot( p21, p21 );
  8016. float denom = d2121 * d4343 - d4321 * d4321;
  8017. float numer = d1343 * d4321 - d1321 * d4343;
  8018. mua = numer / denom;
  8019. mua = clamp( mua, 0.0, 1.0 );
  8020. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  8021. mub = clamp( mub, 0.0, 1.0 );
  8022. return vec2( mua, mub );
  8023. }
  8024. void main() {
  8025. #include <clipping_planes_fragment>
  8026. #ifdef USE_DASH
  8027. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  8028. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  8029. #endif
  8030. float alpha = opacity;
  8031. #ifdef WORLD_UNITS
  8032. // Find the closest points on the view ray and the line segment
  8033. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  8034. vec3 lineDir = worldEnd - worldStart;
  8035. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  8036. vec3 p1 = worldStart + lineDir * params.x;
  8037. vec3 p2 = rayEnd * params.y;
  8038. vec3 delta = p1 - p2;
  8039. float len = length( delta );
  8040. float norm = len / linewidth;
  8041. #ifndef USE_DASH
  8042. #ifdef USE_ALPHA_TO_COVERAGE
  8043. float dnorm = fwidth( norm );
  8044. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  8045. #else
  8046. if ( norm > 0.5 ) {
  8047. discard;
  8048. }
  8049. #endif
  8050. #endif
  8051. #else
  8052. #ifdef USE_ALPHA_TO_COVERAGE
  8053. // artifacts appear on some hardware if a derivative is taken within a conditional
  8054. float a = vUv.x;
  8055. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8056. float len2 = a * a + b * b;
  8057. float dlen = fwidth( len2 );
  8058. if ( abs( vUv.y ) > 1.0 ) {
  8059. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  8060. }
  8061. #else
  8062. if ( abs( vUv.y ) > 1.0 ) {
  8063. float a = vUv.x;
  8064. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8065. float len2 = a * a + b * b;
  8066. if ( len2 > 1.0 ) discard;
  8067. }
  8068. #endif
  8069. #endif
  8070. vec4 diffuseColor = vec4( diffuse, alpha );
  8071. #include <logdepthbuf_fragment>
  8072. #include <color_fragment>
  8073. gl_FragColor = vec4( diffuseColor.rgb, alpha );
  8074. #include <tonemapping_fragment>
  8075. #include <colorspace_fragment>
  8076. #include <fog_fragment>
  8077. #include <premultiplied_alpha_fragment>
  8078. }
  8079. `};class tJ extends Wh{constructor(e){super({type:"LineMaterial",uniforms:qO.clone(wo.line.uniforms),vertexShader:wo.line.vertexShader,fragmentShader:wo.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 b$=new $l,P1=new ot;class nJ extends jMe{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 Qa([-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 Qa([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,r=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),r.applyMatrix4(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new XF(n,6,1);return this.setAttribute("instanceStart",new wh(r,3,0)),this.setAttribute("instanceEnd",new wh(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new XF(n,6,1);return this.setAttribute("instanceColorStart",new wh(r,3,0)),this.setAttribute("instanceColorEnd",new wh(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new kMe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new $l);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),b$.setFromBufferAttribute(n),this.boundingBox.union(b$))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new vd),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let i=0;for(let s=0,o=e.count;s<o;s++)P1.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(P1)),P1.fromBufferAttribute(n,s),i=Math.max(i,r.distanceToSquared(P1));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 x$=new ot,y$=new ot,Xi=new Gr,Qi=new Gr,Zc=new Gr,ME=new ot,jE=new oa,Zi=new EMe,v$=new ot,T1=new $l,A1=new vd,Jc=new Gr;let ed,nf;function w$(t,e,n){return Jc.set(0,0,-e,1).applyMatrix4(t.projectionMatrix),Jc.multiplyScalar(1/Jc.w),Jc.x=nf/n.width,Jc.y=nf/n.height,Jc.applyMatrix4(t.projectionMatrixInverse),Jc.multiplyScalar(1/Jc.w),Math.abs(Math.max(Jc.x,Jc.y))}class KMe extends Ac{constructor(e=new nJ,n=new tJ({color:16777215*Math.random()})){super(e,n),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,n=e.attributes.instanceStart,r=e.attributes.instanceEnd,i=new Float32Array(2*n.count);for(let o=0,l=0,c=n.count;o<c;o++,l+=2)x$.fromBufferAttribute(n,o),y$.fromBufferAttribute(r,o),i[l]=l===0?0:i[l-1],i[l+1]=i[l]+x$.distanceTo(y$);const s=new XF(i,2,1);return e.setAttribute("instanceDistanceStart",new wh(s,1,0)),e.setAttribute("instanceDistanceEnd",new wh(s,1,1)),this}raycast(e,n){const r=this.material.worldUnits,i=e.camera;i!==null||r||console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const s=e.params.Line2!==void 0&&e.params.Line2.threshold||0;ed=e.ray;const o=this.matrixWorld,l=this.geometry,c=this.material;let d,u;nf=c.linewidth+s,l.boundingSphere===null&&l.computeBoundingSphere(),A1.copy(l.boundingSphere).applyMatrix4(o),r?d=.5*nf:d=w$(i,Math.max(i.near,A1.distanceToPoint(ed.origin)),c.resolution),A1.radius+=d,ed.intersectsSphere(A1)!==!1&&(l.boundingBox===null&&l.computeBoundingBox(),T1.copy(l.boundingBox).applyMatrix4(o),r?u=.5*nf:u=w$(i,Math.max(i.near,T1.distanceToPoint(ed.origin)),c.resolution),T1.expandByScalar(u),ed.intersectsBox(T1)!==!1&&(r?(function(m,p){const f=m.matrixWorld,y=m.geometry,v=y.attributes.instanceStart,b=y.attributes.instanceEnd;for(let g=0,_=Math.min(y.instanceCount,v.count);g<_;g++){Zi.start.fromBufferAttribute(v,g),Zi.end.fromBufferAttribute(b,g),Zi.applyMatrix4(f);const k=new ot,P=new ot;ed.distanceSqToSegment(Zi.start,Zi.end,P,k),P.distanceTo(k)<.5*nf&&p.push({point:P,pointOnLine:k,distance:ed.origin.distanceTo(P),object:m,face:null,faceIndex:g,uv:null,uv1:null})}})(this,n):(function(m,p,f){const y=p.projectionMatrix,v=m.material.resolution,b=m.matrixWorld,g=m.geometry,_=g.attributes.instanceStart,k=g.attributes.instanceEnd,P=Math.min(g.instanceCount,_.count),N=-p.near;ed.at(1,Zc),Zc.w=1,Zc.applyMatrix4(p.matrixWorldInverse),Zc.applyMatrix4(y),Zc.multiplyScalar(1/Zc.w),Zc.x*=v.x/2,Zc.y*=v.y/2,Zc.z=0,ME.copy(Zc),jE.multiplyMatrices(p.matrixWorldInverse,b);for(let M=0,A=P;M<A;M++){if(Xi.fromBufferAttribute(_,M),Qi.fromBufferAttribute(k,M),Xi.w=1,Qi.w=1,Xi.applyMatrix4(jE),Qi.applyMatrix4(jE),Xi.z>N&&Qi.z>N)continue;if(Xi.z>N){const I=Xi.z-Qi.z,X=(Xi.z-N)/I;Xi.lerp(Qi,X)}else if(Qi.z>N){const I=Qi.z-Xi.z,X=(Qi.z-N)/I;Qi.lerp(Xi,X)}Xi.applyMatrix4(y),Qi.applyMatrix4(y),Xi.multiplyScalar(1/Xi.w),Qi.multiplyScalar(1/Qi.w),Xi.x*=v.x/2,Xi.y*=v.y/2,Qi.x*=v.x/2,Qi.y*=v.y/2,Zi.start.copy(Xi),Zi.start.z=0,Zi.end.copy(Qi),Zi.end.z=0;const T=Zi.closestPointToPointParameter(ME,!0);Zi.at(T,v$);const C=FZ.lerp(Xi.z,Qi.z,T),F=C>=-1&&C<=1,$=ME.distanceTo(v$)<.5*nf;if(F&&$){Zi.start.fromBufferAttribute(_,M),Zi.end.fromBufferAttribute(k,M),Zi.start.applyMatrix4(b),Zi.end.applyMatrix4(b);const I=new ot,X=new ot;ed.distanceSqToSegment(Zi.start,Zi.end,X,I),f.push({point:X,pointOnLine:I,distance:ed.origin.distanceTo(X),object:m,face:null,faceIndex:M,uv:null,uv1:null})}}})(this,i,n)))}}class YMe extends IP{constructor(e,n,r,i,s=4473924,o=8947848){s=new An(s),o=new An(o);const l=Math.round(e/n);r=Math.round(r/i)*i/2;const c=[],d=[];let u=0;for(let p=-1*(e=l*n/2);p<=e;p+=n){c.push(p,0,-1*r,p,0,r);const f=p===0?s:o;f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3}for(let p=-1*r;p<=r;p+=i){c.push(-1*e,0,p,e,0,p);const f=p===0?s:o;f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3}const m=new Rs;m.setAttribute("position",new Qa(c,3)),m.setAttribute("color",new Qa(d,3)),super(m,new Bw({vertexColors:!0,toneMapped:!1}))}}function XMe(t,e,n,r){const i=(function(o,l,c){o*=.5,l*=.5,c*=.5;const d=new Rs,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 Qa(u,3)),d})(t,e,n),s=new IP(i,new CMe({color:new An(r),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var d0=function(){var t=0,e=document.createElement("div");function n(u){return e.appendChild(u.dom),u}function r(u){for(var m=0;m<e.children.length;m++)e.children[m].style.display=m===u?"block":"none";t=u}e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",(function(u){u.preventDefault(),r(++t%e.children.length)}),!1);var i=(performance||Date).now(),s=i,o=0,l=n(new d0.Panel("FPS","#0ff","#002")),c=n(new d0.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=n(new d0.Panel("MB","#f08","#201"));return r(0),{REVISION:16,dom:e,addPanel:n,showPanel:r,begin:function(){i=(performance||Date).now()},end:function(){o++;var u=(performance||Date).now();if(c.update(u-i,200),u>=s+1e3&&(l.update(1e3*o/(u-s),100),s=u,o=0,d)){var m=performance.memory;d.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return u},update:function(){i=this.end()},domElement:e,setMode:r}};d0.Panel=function(t,e,n){var r=1/0,i=0,s=Math.round,o=s(window.devicePixelRatio||1),l=80*o,c=48*o,d=3*o,u=2*o,m=3*o,p=15*o,f=74*o,y=30*o,v=document.createElement("canvas");v.width=l,v.height=c,v.style.cssText="width:80px;height:48px";var b=v.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,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m,p,f,y),{dom:v,update:function(g,_){r=Math.min(r,g),i=Math.max(i,g),b.fillStyle=n,b.globalAlpha=1,b.fillRect(0,0,l,p),b.fillStyle=e,b.fillText(s(g)+" "+t+" ("+s(r)+"-"+s(i)+")",d,u),b.drawImage(v,m+o,p,f-o,y,m,p,f-o,y),b.fillRect(m+f-o,p,o,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m+f-o,p,o,s((1-g/_)*y))}}};var QMe=d0;class S${constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new yN,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 yN,this.gui.title("Dev info"),this.setup()}loadOpenFolders(){this.openFolders=JSON.parse(localStorage.getItem("dev-gui-open")||"{}").open||[]}saveOpenFolders(){this.openFolders=this.gui.foldersRecursive().filter((e=>!e._closed)).map((e=>e._title)),console.log(this.openFolders),localStorage.setItem("dev-gui-open",JSON.stringify({open:this.openFolders}))}setupRedererFolder(){const e=this.gui.addFolder("Render Info");this.openFolders.includes("Render Info")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.renderer.info.render,"triangles").listen(),e.add(this.watchedObject.renderer.info.render,"calls").listen(),e.add(this.watchedObject.renderer.info.render,"lines").listen(),e.add(this.watchedObject.renderer.info.render,"points").listen(),e.add(this.watchedObject.renderer.info.memory,"geometries").listen(),e.add(this.watchedObject.renderer.info.memory,"textures").listen(),e.add(this.watchedObject,"_lastRenderTime").listen()}setupCameraFolder(){const e=this.gui.addFolder("Camera");this.openFolders.includes("Camera")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()}));const n=e.addFolder("Camera position");n.add(this.watchedObject.camera.position,"x").listen(),n.add(this.watchedObject.camera.position,"y").listen(),n.add(this.watchedObject.camera.position,"z").listen();const r=e.addFolder("Camera rotation");r.add(this.watchedObject.camera.rotation,"x").listen(),r.add(this.watchedObject.camera.rotation,"y").listen(),r.add(this.watchedObject.camera.rotation,"z").listen()}setupParserFolder(){const e=this.gui.addFolder("Parser");this.openFolders.includes("Parser")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.parser,"curZ").listen(),e.add(this.watchedObject.parser,"maxZ").listen(),e.add(this.watchedObject.parser,"tolerance").listen(),e.add(this.watchedObject.parser.layers,"length").name("layers.count").listen(),e.add(this.watchedObject.parser.lines,"length").name("lines.count").listen()}setupBuildVolumeFolder(){const e=this.gui.addFolder("Build Volume");this.openFolders.includes("Build Volume")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.buildVolume,"x").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"y").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"z").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()}))}setupDevHelpers(){const e=this.gui.addFolder("Dev Helpers");this.openFolders.includes("Dev Helpers")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject,"_wireframe").listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject,"render").listen(),e.add(this.watchedObject,"clear").listen()}}class ZMe extends Rs{constructor(e=[new ot],n=.6,r=.2,i=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:i,closed:!1};const s=new ot,o=new ot,l=new Hn,c=[],d=[],u=[],m=[];function p(f){const[y,v,b]=(function(g){const _=e[g],k=new ot,P=new ot,N=new ot,M=new ot;k.copy(_).sub(e[g-1]||_).normalize().add((e[g+1]||_).clone().sub(_).normalize()).normalize();let A=Number.MAX_VALUE;const T=Math.abs(k.x),C=Math.abs(k.y),F=Math.abs(k.z);return T<=A&&(A=T,P.set(1,0,0)),C<=A&&(A=C,P.set(0,1,0)),F<=A&&P.set(0,0,1),M.crossVectors(k,P).normalize(),P.crossVectors(k,M),N.crossVectors(k,P),[_,P,N]})(f);for(let g=0;g<=i;g++){const _=g/i*Math.PI*2,k=Math.sin(_),P=-Math.cos(_);o.x=P*v.x+k*b.x,o.y=P*v.y+k*b.y,o.z=P*v.z+k*b.z,o.normalize(),d.push(o.x,o.y,o.z),s.x=y.x+n*o.x*.5,s.y=y.y+n*o.y*.5,s.z=y.z+r*o.z*.5,c.push(s.x,s.y,s.z)}}(function(){for(let f=0;f<e.length;f++)p(f);p(closed===!1?e.length-1:0),(function(){for(let f=0;f<e.length;f++)for(let y=0;y<=i;y++)l.x=f/e.length,l.y=y/i,u.push(l.x,l.y)})(),(function(){for(let f=1;f<e.length;f++)for(let y=1;y<=i;y++){const v=(i+1)*(f-1)+(y-1),b=(i+1)*f+(y-1),g=(i+1)*f+y,_=(i+1)*(f-1)+y;m.push(v,b,_),m.push(b,g,_)}})()})(),this.setIndex(m),this.setAttribute("position",new Qa(c,3)),this.setAttribute("normal",new Qa(d,3)),this.setAttribute("uv",new Qa(u,2))}}class u0{static get initial(){const e=new u0;return Object.assign(e,{x:0,y:0,z:0,r:0,e:0,i:0,j:0,t:0}),e}}const EE={h:0,s:0,l:0};class lx{constructor(e){var n,r,i,s,o,l,c,d,u;if(this.minLayerThreshold=.05,this.renderExtrusion=!0,this.renderTravel=!1,this.renderTubes=!1,this.extrusionWidth=.6,this.singleLayerMode=!1,this.initialCameraPosition=[-100,400,450],this.debug=!1,this.inches=!1,this.nonTravelmoves=[],this.disableGradient=!1,this.state=u0.initial,this.beyondFirstMove=!1,this.disposables=[],this._extrusionColor=lx.defaultExtrusionColor,this.renderLayerIndex=0,this._geometries={},this._backgroundColor=new An(14737632),this._travelColor=new An(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 vN(this.minLayerThreshold),this.scene=new pMe,this.scene.background=this._backgroundColor,e.backgroundColor!==void 0&&(this.backgroundColor=new An(e.backgroundColor)),this.targetId=e.targetId,this.endLayer=e.endLayer,this.startLayer=e.startLayer,this.lineWidth=e.lineWidth,this.lineHeight=e.lineHeight,this.buildVolume=e.buildVolume,this.initialCameraPosition=(r=e.initialCameraPosition)!==null&&r!==void 0?r:this.initialCameraPosition,this.debug=(i=e.debug)!==null&&i!==void 0?i:this.debug,this.renderExtrusion=(s=e.renderExtrusion)!==null&&s!==void 0?s:this.renderExtrusion,this.renderTravel=(o=e.renderTravel)!==null&&o!==void 0?o:this.renderTravel,this.nonTravelmoves=(l=e.nonTravelMoves)!==null&&l!==void 0?l:this.nonTravelmoves,this.renderTubes=(c=e.renderTubes)!==null&&c!==void 0?c:this.renderTubes,this.extrusionWidth=(d=e.extrusionWidth)!==null&&d!==void 0?d:this.extrusionWidth,this.devMode=(u=e.devMode)!==null&&u!==void 0?u:this.devMode,this.stats=this.devMode?new QMe:void 0,e.extrusionColor!==void 0&&(this.extrusionColor=e.extrusionColor),e.travelColor!==void 0&&(this.travelColor=new An(e.travelColor)),e.topLayerColor!==void 0&&(this.topLayerColor=new An(e.topLayerColor)),e.lastSegmentColor!==void 0&&(this.lastSegmentColor=new An(e.lastSegmentColor)),e.toolColors){this._toolColors={};for(const[f,y]of Object.entries(e.toolColors))this._toolColors[parseInt(f)]=new An(y)}if(e.disableGradient!==void 0&&(this.disableGradient=e.disableGradient),console.info("Using THREE r"+DP),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 YF({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 YF({preserveDrawingBuffer:!0}),this.canvas=this.renderer.domElement,f.appendChild(this.canvas)}this.camera=new Zo(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 GO(this._backgroundColor,p,m),this.resize(),this.controls=new WMe(this.camera,this.renderer.domElement),this.initScene(),this.animate(),e.allowDragNDrop&&this._enableDropHandler(),this.initStats()}get extrusionColor(){return this._extrusionColor}set extrusionColor(e){if(Array.isArray(e)){this._extrusionColor=[];for(const[n,r]of e.entries())this._extrusionColor[n]=new An(r)}else this._extrusionColor=new An(e)}get currentToolColor(){var e;return this._extrusionColor===void 0?lx.defaultExtrusionColor:this._extrusionColor instanceof An?this._extrusionColor:(e=this._extrusionColor[this.state.t])!==null&&e!==void 0?e:lx.defaultExtrusionColor}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){this._backgroundColor=new An(e),this.scene.background=this._backgroundColor}get travelColor(){return this._travelColor}set travelColor(e){this._travelColor=new An(e)}get topLayerColor(){return this._topLayerColor}set topLayerColor(e){this._topLayerColor=e!==void 0?new An(e):void 0}get lastSegmentColor(){return this._lastSegmentColor}set lastSegmentColor(e){this._lastSegmentColor=e!==void 0?new An(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 DMe(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 MMe(13421772,.3*Math.PI),n=new AMe(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 Gv;return n.name=e,n.quaternion.setFromEuler(new zw(-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=u0.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 TE(this,void 0,void 0,(function*(){return this.initScene(),this.renderLayerIndex=0,this.renderFrameLoop(e>0?e:1)}))}renderFrameLoop(e){return new Promise((n=>{const r=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(r))};r()}))}renderFrame(e){this.group=this.createGroup("layer"+this.renderLayerIndex);for(let n=0;n<e&&this.renderLayerIndex+n<this.layers.length;n++)this.renderLayer(this.renderLayerIndex),this.renderLayerIndex++;this.batchGeometries(),this.scene.add(this.group)}renderLayer(e){var n,r,i,s,o,l,c,d;if(e>this.maxLayerIndex)return;const u=this.layers[e],m={extrusion:[],travel:[],z:this.state.z,height:u.height};for(const p of u.commands)if(p.gcode!="g20"){if(p.gcode.startsWith("t")){this.doRenderExtrusion(m,e),m.extrusion=[];const f=p;this.state.t=f.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(p.gcode)>-1){const f=p,y={x:(n=f.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=f.params.y)!==null&&r!==void 0?r:this.state.y,z:(i=f.params.z)!==null&&i!==void 0?i:this.state.z,r:(s=f.params.r)!==null&&s!==void 0?s:this.state.r,e:(o=f.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=f.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=f.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((d=f.params.e)!==null&&d!==void 0?d:0)>0||this.nonTravelmoves.indexOf(p.gcode)>-1;(y.x!=this.state.x||y.y!=this.state.y||y.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(p.gcode=="g2"||p.gcode=="g3"||p.gcode=="g02"||p.gcode=="g03"?this.addArcSegment(m,this.state,y,v,p.gcode=="g2"||p.gcode=="g02"):this.addLineSegment(m,this.state,y,v))}this.state.x=y.x,this.state.y=y.y,this.state.z=y.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(m,e)}doRenderExtrusion(e,n){var r,i;if(this.renderExtrusion){let s=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;s.getHSL(EE),s=new An().setHSL(EE.h,EE.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:s,l=(i=this._lastSegmentColor)!==null&&i!==void 0?i:o,c=e.extrusion.splice(-3),d=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...d,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...d,...c],l.getHex()))}else this.renderTubes?this.addTubeLine(e.extrusion,s.getHex(),e.height):this.addLine(e.extrusion,s.getHex())}this.renderTravel&&this.addLine(e.travel,this._travelColor.getHex())}setInches(){this.beyondFirstMove?console.warn("Switching units after movement is already made is discouraged and is not supported."):this.inches=!0}drawBuildVolume(){if(!this.buildVolume)return;this.scene.add(new YMe(this.buildVolume.x,10,this.buildVolume.y,10));const e=XMe(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 vN(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=u0.initial,(e=this.devGui)===null||e===void 0||e.reset(),this._geometries={}}resize(){const[e,n]=[this.canvas.offsetWidth,this.canvas.offsetHeight];this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,n,!1)}addLineSegment(e,n,r,i){(i?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,i,s){const o=i?e.extrusion:e.travel,l=n.x,c=n.y,d=n.z,u=r.x,m=r.y,p=r.z;let f=r.r,y=r.i,v=r.j;if(f){const te=u-l,ae=m-c,ee=Math.sqrt(Math.pow(te/2,2)+Math.pow(ae/2,2));f=Math.max(f,ee);const me=Math.pow(te,2)+Math.pow(ae,2),le=Math.pow(f,2)-me/4;let ue=Math.sqrt(le/me);(s&&f<0||!s&&f>0)&&(ue=-ue),y=te/2+ae*ue,v=ae/2-te*ue}const b=l==u&&c==m,g=l+y,_=c+v,k=Math.sqrt(y*y+v*v),P=Math.atan2(-v,-y),N=Math.atan2(m-_,u-g);let M;b?M=2*Math.PI:(M=s?P-N:N-P,M<0&&(M+=2*Math.PI));let A=k*M/1.8;this.inches&&(A*=25),A<1&&(A=1);let T=M/A;T*=s?-1:1;const C=[];C.push({x:l,y:c,z:d});const F=(d-p)/A;let $=l,I=c,X=d,L=P;for(let te=0;te<A-1;te++)L+=T,$=g+k*Math.cos(L),I=_+k*Math.sin(L),X+=F,C.push({x:$,y:I,z:X});C.push({x:r.x,y:r.y,z:r.z});for(let te=0;te<C.length-1;te++)o.push(C[te].x,C[te].y,C[te].z,C[te+1].x,C[te+1].y,C[te+1].z)}addLine(e,n){var r;if(typeof this.lineWidth=="number"&&this.lineWidth>0)return void this.addThickLine(e,n);const i=new Rs;i.setAttribute("position",new Qa(e,3)),this.disposables.push(i);const s=new Bw({color:n});this.disposables.push(s);const o=new IP(i,s);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let i=[];const s=[];for(let o=0;o<e.length;o+=6){const l=e.slice(o,o+9),c=new ot(l[0],l[1],l[2]),d=new ot(l[3],l[4],l[5]),u=new ot(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 ZMe(o,this.extrusionWidth,this.lineHeight||r,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const i=new nJ;this.disposables.push(i);const s=new tJ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),i.setPositions(e);const o=new KMe(i,s);(r=this.group)===null||r===void 0||r.add(o)}dispose(){this.disposables.forEach((e=>e.dispose())),this.disposables=[],this.controls.dispose(),this.renderer.dispose(),this.cancelAnimation()}cancelAnimation(){this.animationFrameId!==void 0&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0}_enableDropHandler(){console.warn("Drag and drop is deprecated as a library feature. See the demo how to implement your own."),this.canvas.addEventListener("dragover",(e=>{e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),this.canvas.classList.add("dragging")})),this.canvas.addEventListener("dragleave",(e=>{e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging")})),this.canvas.addEventListener("drop",(e=>TE(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const i=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(i.stream()),this.render()}))))}batchGeometries(){if(this._geometries)for(const e in this._geometries){const n=this.createBatchMesh(parseInt(e));for(;this._geometries[e].length>0;){const r=this._geometries[e].pop();n.addGeometry(r)}}}createBatchMesh(e){var n;const r=this._geometries[e],i=new NMe({color:e,wireframe:this._wireframe});this.disposables.push(i);const s=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new SMe(r.length,s,void 0,i);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return TE(this,void 0,void 0,(function*(){const i=e.getReader();let s,o="",l=0;do{console.debug("reading from stream"),s=yield i.read(),l+=(r=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const d=(c=s.value,new TextDecoder("utf-8").decode(c)),u=d.lastIndexOf(`
  8080. `),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 S$(this):typeof this.devMode=="object"&&(this.devGui=new S$(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())}}lx.defaultExtrusionColor=new An("hotpink");function rJ({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:r=""}){const i=w.useRef(null),s=w.useRef(null),o=w.useRef(null),l=w.useRef(!1),[c,d]=w.useState(!0),[u,m]=w.useState(null),[p,f]=w.useState(!1),[y,v]=w.useState(0),[b,g]=w.useState(0),_=w.useMemo(()=>JSON.stringify(n),[n]);w.useEffect(()=>{if(!i.current||l.current)return;l.current=!0;const N=i.current,M=N.parentElement?.getBoundingClientRect();M&&(N.width=M.width,N.height=M.height);const A=n&&n.length>1,T=n?.[0]||"#00ae42",C=new lx({canvas:N,buildVolume:e,backgroundColor:1710618,extrusionColor:A?n:T,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});s.current=C;const F={},$=Yu();$&&(F.Authorization=`Bearer ${$}`),fetch(t,{headers:F}).then(async X=>{if(!X.ok)throw X.status===404&&(await X.json().catch(()=>({}))).detail?.includes("sliced")?(f(!0),new Error("not_sliced")):new Error("Failed to load G-code");return X.text()}).then(X=>{const L=new Set,te=/^(\s*)T(\d+)(\s*;.*)?$/gim;let ae;for(;(ae=te.exec(X))!==null;){const ne=parseInt(ae[2],10);ne<=15&&L.add(ne)}const ee=new Map,me=Array.from(L).sort((ne,oe)=>ne-oe);me.forEach((ne,oe)=>{ee.set(ne,oe%8)});const le=[];me.forEach((ne,oe)=>{const be=n?.[ne]||"#00ae42";le[oe%8]=be});const ue=X.split(`
  8081. `).map(ne=>{const oe=ne.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(oe){const be=parseInt(oe[2],10);if(be>15)return`; FILTERED: ${ne.trim()}`;const _e=ee.get(be)??0;return`${oe[1]}T${_e}${oe[3]||""}`}return ne}).join(`
  8082. `);le.length>0&&(C.extrusionColor=le),C.processGCode(ue);const K=C.layers?.length||0;g(K),v(K),C.render(),d(!1)}).catch(X=>{X.message!=="not_sliced"&&m(X.message),d(!1)});const I=()=>{if(N.parentElement&&s.current){const X=N.parentElement.getBoundingClientRect();N.width=X.width,N.height=X.height,s.current.resize()}};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),o.current&&cancelAnimationFrame(o.current),s.current&&(s.current.dispose(),s.current=null),l.current=!1}},[t,_]);const k=w.useCallback(N=>{if(!s.current)return;const M=Math.max(1,Math.min(N,b));v(M),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{s.current&&(s.current.endLayer=M,s.current.render())})},[b]),P=N=>{k(parseInt(N.target.value,10))};return a.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[a.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("canvas",{ref:i,className:"w-full h-full"}),c&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsxs("div",{className:"text-center",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),p&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsxs("div",{className:"text-center max-w-sm px-4",children:[a.jsx(Mfe,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),a.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing in Bambu Studio or Orca Slicer."})]})}),u&&!p&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx("div",{className:"text-center text-red-400",children:a.jsx("p",{className:"text-sm",children:u})})})]}),!c&&!u&&!p&&b>0&&a.jsx("div",{className:"mt-4 px-2",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("button",{onClick:()=>k(y-1),disabled:y<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsx("input",{type:"range",min:1,max:b,value:y,onChange:P,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),a.jsx("button",{onClick:()=>k(y+1),disabled:y>=b,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:a.jsx(Va,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[y," / ",b]})]})})]})}function JMe({printerId:t,filePath:e,filename:n,onClose:r}){const[i,s]=w.useState(null),[o,l]=w.useState([]),[c,d]=w.useState(!1),[u,m]=w.useState(null),p=n.toLowerCase().split(".").pop()||"",f=p==="3mf"||p==="stl",y=p==="gcode"||p==="3mf";w.useEffect(()=>{s(f?"3d":y?"gcode":null)},[f,y]),w.useEffect(()=>{l([]),m(null),f&&(d(!0),pe.getPrinterFilePlates(t,e).then(g=>l(g.plates||[])).catch(()=>l([])).finally(()=>d(!1)))},[e,f,t]);const v=o.length>1,b=u==null?null:o.find(g=>g.index===u)??null;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6",onClick:r,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col",onClick:g=>g.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:n}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>f&&s("3d"),disabled:!f,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${i==="3d"?"text-bambu-green border-b-2 border-bambu-green":f?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(si,{className:"w-4 h-4"}),"3D Model",!f&&a.jsx("span",{className:"text-xs",children:"(not available)"})]}),a.jsxs("button",{onClick:()=>y&&s("gcode"),disabled:!y,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":y?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Ms,{className:"w-4 h-4"}),"G-code Preview",!y&&a.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:i==="3d"&&f?a.jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[v&&a.jsxs("div",{className:"rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(si,{className:"w-4 h-4"}),"Plates",c&&a.jsx(ct,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[a.jsxs("button",{type:"button",onClick:()=>m(null),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${u==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(si,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:"All Plates"}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[o.length," plate",o.length!==1?"s":""]})]}),u==null&&a.jsx(us,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]}),o.map(g=>a.jsxs("button",{type:"button",onClick:()=>m(g.index),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${u===g.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[g.has_thumbnail?a.jsx("img",{src:pe.getPrinterFilePlateThumbnail(t,g.index,e),alt:`Plate ${g.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(si,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:g.name||`Plate ${g.index}`}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:g.objects.length>0?g.objects.slice(0,2).join(", ")+(g.objects.length>2?"…":""):`${g.filaments.length} filament${g.filaments.length!==1?"s":""}`})]}),u===g.index&&a.jsx(us,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},g.index))]}),b&&a.jsxs("div",{className:"mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1",children:[a.jsxs("span",{children:["Plate ",b.index]}),b.print_time_seconds!=null&&a.jsxs("span",{children:["ETA ",Math.round(b.print_time_seconds/60)," min"]}),b.filament_used_grams!=null&&a.jsxs("span",{children:[b.filament_used_grams.toFixed(1)," g"]}),b.filaments.length>0&&a.jsxs("span",{children:[b.filaments.length," filament",b.filaments.length!==1?"s":""]})]})]}),a.jsx("div",{className:"flex-1",children:a.jsx(wZ,{url:pe.getPrinterFileDownloadUrl(t,e),fileType:p,selectedPlateId:u,className:"w-full h-full"})})]}):i==="gcode"&&y?a.jsx(rJ,{gcodeUrl:pe.getPrinterFileGcodeUrl(t,e),className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function _$(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 eje(t,e){if(e)return pQ;switch(t.toLowerCase().split(".").pop()||""){case"3mf":return yf;case"gcode":return Ms;case"mp4":case"avi":return jh;case"png":case"jpg":case"jpeg":return Vu;default:return _P}}const tje=[{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 nje({printerId:t,printerName:e,onClose:n}){const{t:r}=Lt(),{showToast:i}=xn(),s=mn(),[o,l]=w.useState("/"),[c,d]=w.useState(new Set),[u,m]=w.useState(""),[p,f]=w.useState([]),[y,v]=w.useState("name-asc"),[b,g]=w.useState(null),[_,k]=w.useState(null);w.useEffect(()=>{const ee=me=>{me.key==="Escape"&&n()};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[n]);const{data:P,isLoading:N,refetch:M}=et({queryKey:["printerFiles",t,o],queryFn:()=>pe.getPrinterFiles(t,o),refetchInterval:3e4}),{data:A}=et({queryKey:["printerStorage",t],queryFn:()=>pe.getPrinterStorage(t),staleTime:3e4}),T=lt({mutationFn:async ee=>{for(const me of ee)await pe.deletePrinterFile(t,me)},onSuccess:()=>{i(r("printerFiles.toast.filesDeleted",{count:p.length})),s.invalidateQueries({queryKey:["printerFiles",t]}),d(new Set),f([])},onError:ee=>{i(r("printerFiles.toast.deleteFailed",{error:ee.message}),"error")}}),C=ee=>{l(ee),d(new Set)},F=()=>{if(o==="/")return;const ee=o.split("/").filter(Boolean);ee.pop(),l(ee.length?"/"+ee.join("/"):"/"),d(new Set)},$=(ee,me)=>{me.stopPropagation(),d(le=>{const ue=new Set(le);return ue.has(ee)?ue.delete(ee):ue.add(ee),ue})},I=()=>{if(!P?.files)return;const ee=P.files.filter(me=>!me.is_directory&&(!u||me.name.toLowerCase().includes(u.toLowerCase()))).map(me=>me.path);d(new Set(ee))},X=()=>{d(new Set)},L=async()=>{if(c.size===0)return;const ee=Array.from(c);if(ee.length===1){pe.downloadPrinterFile(t,ee[0]).catch(me=>{console.error("Printer file download failed:",me)}),d(new Set);return}g({current:0,total:ee.length});try{const me=await pe.downloadPrinterFilesAsZip(t,ee),le=URL.createObjectURL(me),ue=document.createElement("a");ue.href=le,ue.download=`${e.replace(/[^a-zA-Z0-9]/g,"_")}-files.zip`,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue),URL.revokeObjectURL(le),i(`Downloaded ${ee.length} files as ZIP`),d(new Set)}catch(me){i(`Download failed: ${me instanceof Error?me.message:"Unknown error"}`,"error")}finally{g(null)}},te=()=>{c.size!==0&&f(Array.from(c))},ae=[{path:"/",label:"Root"},{path:"/cache",label:"Cache"},{path:"/model",label:"Models"},{path:"/timelapse",label:"Timelapse"}];return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:n,children:[a.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden",onClick:ee=>ee.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ty,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("printerFiles.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e})]})]}),a.jsxs("div",{className:"flex items-center gap-4",children:[A&&(A.used_bytes!=null||A.free_bytes!=null)&&a.jsxs("div",{className:"text-sm text-bambu-gray flex items-center gap-2",children:[A.used_bytes!=null&&a.jsxs("span",{children:[r("printerFiles.storageUsed")," ",_$(A.used_bytes)]}),A.used_bytes!=null&&A.free_bytes!=null&&a.jsx("span",{className:"text-bambu-dark-tertiary",children:"|"}),A.free_bytes!=null&&a.jsxs("span",{children:[r("printerFiles.storageFree")," ",_$(A.free_bytes)]})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:"Close file manager","aria-label":"Close file manager",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[ae.map(ee=>a.jsx("button",{onClick:()=>{C(ee.path),m("")},className:`px-3 py-1 text-sm rounded-full transition-colors ${o===ee.path?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:ee.label},ee.path)),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:r("printerFiles.filterPlaceholder"),value:u,onChange:ee=>m(ee.target.value),className:"w-40 pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"relative flex items-center gap-1",children:[a.jsx(lO,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("select",{value:y,onChange:ee=>v(ee.target.value),className:"appearance-none bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm py-1.5 pl-2 pr-6 focus:border-bambu-green focus:outline-none cursor-pointer",title:"Sort files","aria-label":"Sort files",children:tje.map(ee=>a.jsx("option",{value:ee.value,children:ee.label},ee.value))})]}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>M(),disabled:N,children:a.jsx(vr,{className:`w-4 h-4 ${N?"animate-spin":""}`})})]}),a.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0",children:[a.jsx("button",{onClick:F,disabled:o==="/",className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed",title:"Go to parent folder","aria-label":"Go to parent folder",children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-bambu-gray font-mono",children:o})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:N?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):P?.files?.length?a.jsx("div",{className:"space-y-1",children:[...P.files].filter(ee=>!u||ee.name.toLowerCase().includes(u.toLowerCase())).sort((ee,me)=>{if(ee.is_directory&&!me.is_directory)return-1;if(!ee.is_directory&&me.is_directory)return 1;switch(y){case"name-asc":return ee.name.localeCompare(me.name);case"name-desc":return me.name.localeCompare(ee.name);case"size-asc":return ee.size-me.size;case"size-desc":return me.size-ee.size;case"date-asc":{const le=ee.mtime?Qn(ee.mtime)?.getTime()??0:0,ue=me.mtime?Qn(me.mtime)?.getTime()??0:0;return le-ue}case"date-desc":{const le=ee.mtime?Qn(ee.mtime)?.getTime()??0:0;return(me.mtime?Qn(me.mtime)?.getTime()??0:0)-le}default:return ee.name.localeCompare(me.name)}}).map(ee=>{const me=eje(ee.name,ee.is_directory),le=c.has(ee.path);return a.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${le?"bg-bambu-green/20 border border-bambu-green/50":"hover:bg-bambu-dark-tertiary"}`,onClick:()=>{ee.is_directory&&C(ee.path)},children:[ee.is_directory?null:a.jsx("button",{onClick:ue=>$(ee.path,ue),className:"flex-shrink-0 text-bambu-gray hover:text-white",children:le?a.jsx(us,{className:"w-5 h-5 text-bambu-green"}):a.jsx(eo,{className:"w-5 h-5"})}),a.jsx(me,{className:`w-5 h-5 flex-shrink-0 ${ee.is_directory?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:"flex-1 text-white truncate",children:ee.name}),!ee.is_directory&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:_o(ee.size)}),(ee.name.toLowerCase().endsWith(".3mf")||ee.name.toLowerCase().endsWith(".gcode")||ee.name.toLowerCase().endsWith(".stl"))&&a.jsx("button",{onClick:ue=>{ue.stopPropagation(),k({path:ee.path,name:ee.name})},className:"p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green",title:"3D View",children:a.jsx(si,{className:"w-4 h-4"})})]}),ee.is_directory&&a.jsx(ol,{className:"w-4 h-4 text-bambu-gray rotate-180"})]},ee.path)})}):a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"No files in this directory"})}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("div",{className:"text-sm text-bambu-gray",children:c.size>0?`${c.size} selected`:u?`${P?.files?.filter(ee=>ee.name.toLowerCase().includes(u.toLowerCase())).length||0} of ${P?.files?.length||0} items`:`${P?.files?.length||0} items`}),P?.files?.some(ee=>!ee.is_directory)&&a.jsx("div",{className:"flex items-center gap-2",children:c.size>0?a.jsxs("button",{onClick:X,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(Bbe,{className:"w-4 h-4"}),"Deselect All"]}):a.jsxs("button",{onClick:I,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(us,{className:"w-4 h-4"}),"Select All"]})})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",disabled:c.size===0||b!==null,onClick:L,children:b?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),b.current,"/",b.total]}):a.jsxs(a.Fragment,{children:[a.jsx(va,{className:"w-4 h-4"}),"Download",c.size>1?` (${c.size})`:""]})}),a.jsxs(Ie,{variant:"secondary",disabled:c.size===0||T.isPending,onClick:te,className:"text-red-400 hover:text-red-300",children:[T.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),r("printerFiles.deleteButton"),c.size>1?` (${c.size})`:""]})]})]})]}),p.length>0&&a.jsx(kn,{title:p.length>1?r("printerFiles.deleteFiles",{count:p.length}):r("fileManager.deleteFile"),message:p.length>1?r("printerFiles.deleteFilesConfirm",{count:p.length}):r("printerFiles.deleteFileConfirm",{name:p[0].split("/").pop()}),confirmText:r("common.delete"),variant:"danger",onConfirm:()=>{T.mutate(p)},onCancel:()=>f([])}),_&&a.jsx(JMe,{printerId:t,filePath:_.path,filename:_.name,onClose:()=>k(null)})]})}function YO({on:t,className:e="w-5 h-5"}){const n=t?"#facc15":"none",r=t?"#78350f":"currentColor",i=t?1:0;return a.jsxs("svg",{viewBox:"0 0 32 32",fill:"none",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[a.jsxs("g",{stroke:r,opacity:i,children:[a.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),a.jsx("line",{x1:"6.1",y1:"6.1",x2:"8.9",y2:"8.9"}),a.jsx("line",{x1:"25.9",y1:"6.1",x2:"23.1",y2:"8.9"}),a.jsx("line",{x1:"2",y1:"16",x2:"6",y2:"16"}),a.jsx("line",{x1:"30",y1:"16",x2:"26",y2:"16"})]}),a.jsx("path",{d:"M12 24v-2.3c0-.9-.4-1.7-1-2.3C9.2 17.6 8 15.4 8 13c0-4.4 3.6-8 8-8s8 3.6 8 8c0 2.4-1.2 4.6-3 6.4-.6.6-1 1.4-1 2.3V24",fill:n,stroke:r}),a.jsx("path",{d:"M12 24h8",stroke:r}),a.jsx("path",{d:"M12 27h8",stroke:r}),a.jsx("path",{d:"M13 30h6",stroke:r})]})}const zP=({className:t})=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[a.jsx("rect",{x:"2",y:"15",width:"5",height:"5",rx:"0.5"}),a.jsx("rect",{x:"9.5",y:"15",width:"5",height:"5",rx:"0.5",fill:"currentColor",opacity:"0.3"}),a.jsx("rect",{x:"17",y:"15",width:"5",height:"5",rx:"0.5"}),a.jsx("path",{d:"M4 12 C4 6, 14 6, 14 12"}),a.jsx("polyline",{points:"12,10 14,12 12,14"})]});function XO({printerId:t,isOpen:e,onClose:n}){const{t:r}=Lt(),{showToast:i}=xn(),{hasPermission:s}=_r(),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=et({queryKey:["printerStatus",t],queryFn:()=>pe.getPrinterStatus(t),refetchInterval:3e4,enabled:e}),{data:m,refetch:p}=et({queryKey:["printableObjects",t],queryFn:()=>pe.getPrintableObjects(t),enabled:e,refetchInterval:e?5e3:!1}),f=lt({mutationFn:y=>pe.skipObjects(t,y),onSuccess:y=>{i(y.message||r("printers.skipObjects.objectsSkipped")),l(null),p()},onError:y=>i(y.message||r("printers.toast.failedToSkipObjects"),"error")});return e?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:n,onKeyDown:y=>{y.key==="Escape"&&(c?d(!1):n())},tabIndex:-1,ref:y=>y?.focus(),children:[a.jsx("div",{className:"absolute inset-0 bg-black/50 z-0"}),a.jsxs("div",{className:"relative z-10 bg-white dark:bg-bambu-dark border border-gray-200 dark:border-bambu-dark-tertiary rounded-xl shadow-2xl w-[560px] max-h-[85vh] flex flex-col overflow-hidden",onClick:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zP,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:r("printers.skipObjects.title")})]}),a.jsx("button",{onClick:n,className:"p-1 text-gray-500 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),m?m.objects.length===0?a.jsxs("div",{className:"text-center py-8 px-4 text-bambu-gray",children:[a.jsx("p",{className:"text-sm",children:r("printers.noObjectsFound")}),a.jsx("p",{className:"text-xs mt-1 opacity-70",children:r("printers.objectsLoadedOnPrintStart")})]}):a.jsxs("div",{className:"flex flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-blue-50 dark:bg-blue-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[a.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center",children:a.jsx(xQ,{className:"w-4 h-4 text-blue-500 dark:text-blue-400"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300",children:r("printers.skipObjects.matchIdsInfo")}),a.jsx("p",{className:"text-[10px] text-blue-500/70 dark:text-blue-300/60",children:r("printers.skipObjects.printerShowsIds")})]}),a.jsxs("div",{className:"flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray",children:[m.skipped_count,"/",m.total," ",r("printers.skipObjects.skipped")]})]}),(u?.layer_num??0)<=1&&a.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-50 dark:bg-amber-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[a.jsx(qa,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0"}),a.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:r("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0})})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx("div",{className:"w-52 flex-shrink-0 p-4 border-r border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark-secondary overflow-y-auto",children:a.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>d(!0),children:[u?.cover_url?a.jsx("img",{src:Ra(`${u.cover_url}?view=top`),alt:r("printers.printPreview"),className:"w-full aspect-square object-contain rounded-lg bg-gray-900 dark:bg-gray-900 border border-gray-300 dark:border-gray-600"}):a.jsx("div",{className:"w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center",children:a.jsx(si,{className:"w-8 h-8 text-gray-300 dark:text-bambu-gray/30"})}),a.jsx("div",{className:"absolute top-2 right-2 p-1 bg-black/60 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(NP,{className:"w-3.5 h-3.5 text-white"})}),m.objects.length>0&&a.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((y,v)=>{let b,g;if(y.x!=null&&y.y!=null&&m.bbox_all){const[_,k,P,N]=m.bbox_all,M=P-_,A=N-k,T=8,C=100-T*2;b=T+(y.x-_)/M*C,g=T+(N-y.y)/A*C,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g))}else if(y.x!=null&&y.y!=null)b=y.x/256*100,g=100-y.y/256*100,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g));else{const _=Math.ceil(Math.sqrt(m.objects.length)),k=Math.floor(v/_),P=v%_,N=Math.ceil(m.objects.length/_);b=15+P*(70/_)+35/_,g=15+k*(70/N)+35/N}return a.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${y.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${g}%`,transform:"translate(-50%, -50%)"},title:y.name,children:y.id},y.id)})}),a.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:m.objects.filter(y=>!y.skipped).length})})]})}),a.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:m.objects.map(y=>a.jsxs("div",{className:`
  8083. flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary/50 last:border-0
  8084. ${y.skipped?"bg-red-50 dark:bg-red-500/10":"hover:bg-gray-50 dark:hover:bg-bambu-dark/50"}
  8085. `,children:[a.jsxs("div",{className:`
  8086. w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center
  8087. ${y.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"}
  8088. `,children:[a.jsx("span",{className:`text-lg font-mono font-bold ${y.skipped?"text-red-500 dark:text-red-400":"text-green-600 dark:text-bambu-green"}`,children:y.id}),a.jsx("span",{className:`text-[8px] uppercase tracking-wider ${y.skipped?"text-red-400/60":"text-green-500/60 dark:text-bambu-green/60"}`,children:"ID"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:`block text-sm truncate ${y.skipped?"text-red-500 dark:text-red-400 line-through":"text-gray-900 dark:text-white"}`,children:y.name}),y.skipped&&a.jsx("span",{className:"text-[10px] text-red-400/60",children:r("printers.willBeSkipped")})]}),y.skipped?a.jsx("span",{className:"px-4 py-2 text-xs text-red-500 dark:text-red-400/70 bg-red-100 dark:bg-red-500/10 rounded-lg",children:r("printers.skipObjects.skipped")}):a.jsx("button",{onClick:()=>l({id:y.id,name:y.name}),disabled:f.isPending||(u?.layer_num??0)<=1||!s("printers:control"),className:`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${(u?.layer_num??0)<=1||!s("printers:control")?"bg-gray-100 dark:bg-bambu-dark text-gray-400 dark:text-bambu-gray/50 cursor-not-allowed":"bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 border border-red-300 dark:border-red-500/30"}`,title:s("printers:control")?(u?.layer_num??0)<=1?r("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0}):r("printers.skipObjects.skip"):r("printers.permission.noControl"),children:r("printers.skipObjects.skip")})]},y.id))})]})]}):a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&a.jsx(kn,{variant:"warning",title:r("printers.skipObjects.confirmTitle"),message:r("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:r("printers.skipObjects.skip"),isLoading:f.isPending,onConfirm:()=>f.mutate([o.id]),onCancel:()=>l(null)}),c&&m&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>d(!1),children:[a.jsx("button",{onClick:()=>d(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})}),a.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:y=>y.stopPropagation(),children:[u?.cover_url?a.jsx("img",{src:`${u.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):a.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:a.jsx(si,{className:"w-16 h-16 text-gray-500"})}),m.objects.length>0&&a.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((y,v)=>{let b,g;if(y.x!=null&&y.y!=null&&m.bbox_all){const[_,k,P,N]=m.bbox_all,M=P-_,A=N-k,T=8,C=100-T*2;b=T+(y.x-_)/M*C,g=T+(N-y.y)/A*C,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g))}else if(y.x!=null&&y.y!=null)b=y.x/256*100,g=100-y.y/256*100,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g));else{const _=Math.ceil(Math.sqrt(m.objects.length)),k=Math.floor(v/_),P=v%_,N=Math.ceil(m.objects.length/_);b=15+P*(70/_)+35/_,g=15+k*(70/N)+35/N}return a.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${y.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${g}%`,transform:"translate(-50%, -50%)"},title:y.name,children:y.id},y.id)})}),a.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:m.objects.filter(y=>!y.skipped).length})})]})]})]}):null}const rje="embeddedCameraState_",k$=5,aje=2e3,ije=3e4,sje=5e3,DE={x:window.innerWidth-420,y:20,width:400,height:300};function oje({printerId:t,printerName:e,viewerIndex:n=0,onClose:r}){const{t:i}=Lt(),s=mn(),{showToast:o}=xn(),{hasPermission:l}=_r(),c=`${rje}${t}`,d=()=>{try{const Ve=localStorage.getItem(c);if(Ve){const tt=JSON.parse(Ve);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 Me=n*30;return{...DE,x:Math.max(0,DE.x-Me),y:Math.max(0,DE.y+Me)}},[u,m]=w.useState(d),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState({x:0,y:0}),[_,k]=w.useState(!1),[P,N]=w.useState(!1),[M,A]=w.useState(1),[T,C]=w.useState({x:0,y:0}),[F,$]=w.useState(!1),[I,X]=w.useState({x:0,y:0}),[L,te]=w.useState(null),[ae,ee]=w.useState(null),[me,le]=w.useState(!1),[ue,K]=w.useState(!0),[ne,oe]=w.useState(Date.now()),[be,_e]=w.useState(0),[B,Y]=w.useState(!1),[D,j]=w.useState(0),z=w.useRef(null),W=w.useRef(null),q=w.useRef(null),de=w.useRef(null),O=w.useRef(null),[G,Q]=w.useState(!1),{data:V}=et({queryKey:["printer",t],queryFn:()=>pe.getPrinter(t),enabled:t>0}),{data:J}=et({queryKey:["printerStatus",t],queryFn:()=>pe.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),ie=lt({mutationFn:Me=>pe.setChamberLight(t,Me),onMutate:async Me=>{await s.cancelQueries({queryKey:["printerStatus",t]});const Ve=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],tt=>({...tt,chamber_light:Me})),{previousStatus:Ve}},onSuccess:(Me,Ve)=>{o(`Chamber light ${Ve?"on":"off"}`)},onError:(Me,Ve,tt)=>{tt?.previousStatus&&s.setQueryData(["printerStatus",t],tt.previousStatus),o(Me.message||i("printers.toast.failedToControlChamberLight"),"error")}}),he=(J?.state==="RUNNING"||J?.state==="PAUSE")&&(J?.printable_objects_count??0)>=2;w.useEffect(()=>{const Me=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(u))},500);return()=>clearTimeout(Me)},[u,c]);const fe=w.useRef(!1);w.useEffect(()=>{fe.current=!1;const Me=`/api/v1/printers/${t}/camera/stop`,Ve=()=>{if(t>0&&!fe.current){fe.current=!0;const ut={},xt=Yu();xt&&(ut.Authorization=`Bearer ${xt}`),fetch(Me,{method:"POST",keepalive:!0,headers:ut}).catch(()=>{})}},tt=W.current;return()=>{tt&&(tt.src=""),Ve(),q.current&&clearTimeout(q.current),de.current&&clearInterval(de.current),O.current&&clearInterval(O.current)}},[t]),w.useEffect(()=>{if(ue){const Me=setTimeout(()=>K(!1),3e3);return()=>clearTimeout(Me)}},[ue,ne]);const se=w.useCallback(()=>{if(be>=k$){Y(!1),le(!0);return}const Me=Math.min(aje*Math.pow(2,be),ije);Y(!0),j(Math.ceil(Me/1e3)),de.current=setInterval(()=>{j(Ve=>Ve<=1?(de.current&&clearInterval(de.current),0):Ve-1)},1e3),q.current=setTimeout(()=>{_e(Ve=>Ve+1),Y(!1),K(!0),le(!1),W.current&&(W.current.src=""),oe(Date.now())},Me)},[be]);w.useEffect(()=>{if(ue||B||_){O.current&&(clearInterval(O.current),O.current=null);return}return O.current=setInterval(async()=>{try{const Me=await pe.getCameraStatus(t);(Me.stalled||!Me.active&&!me)&&(O.current&&(clearInterval(O.current),O.current=null),K(!1),se())}catch{}},sje),()=>{O.current&&(clearInterval(O.current),O.current=null)}},[ue,me,B,_,t,se]),w.useEffect(()=>{const Me=()=>{const Ve=!!document.fullscreenElement;N(Ve),Ve||(A(1),C({x:0,y:0}))};return document.addEventListener("fullscreenchange",Me),()=>document.removeEventListener("fullscreenchange",Me)},[]);const U=()=>{z.current&&(document.fullscreenElement?document.exitFullscreen():z.current.requestFullscreen())},R=()=>{A(Me=>Math.min(Me+.5,4))},re=()=>{A(Me=>{const Ve=Math.max(Me-.5,1);return Ve===1&&C({x:0,y:0}),Ve})},xe=Me=>{Me.preventDefault(),Me.deltaY<0?R():re()},we=Me=>{M>1&&(Me.preventDefault(),$(!0),X({x:Me.clientX-T.x,y:Me.clientY-T.y}))},ye=w.useCallback(()=>{if(!z.current||!W.current)return{x:200,y:150};const Me=z.current.getBoundingClientRect(),Ve=Me.width*(M-1)/2,tt=Me.height*(M-1)/2;return{x:Math.max(50,Ve),y:Math.max(50,tt)}},[M]),Ae=Me=>{if(F&&M>1){const Ve=Me.clientX-I.x,tt=Me.clientY-I.y,ut=ye();C({x:Math.max(-ut.x,Math.min(ut.x,Ve)),y:Math.max(-ut.y,Math.min(ut.y,tt))})}},ve=()=>{$(!1)},Te=Me=>{if(Me.length<2)return 0;const Ve=Me[0].clientX-Me[1].clientX,tt=Me[0].clientY-Me[1].clientY;return Math.sqrt(Ve*Ve+tt*tt)},Fe=Me=>Me.length<2?{x:Me[0].clientX,y:Me[0].clientY}:{x:(Me[0].clientX+Me[1].clientX)/2,y:(Me[0].clientY+Me[1].clientY)/2},Ee=Me=>{Me.touches.length===2?(Me.preventDefault(),te(Te(Me.touches)),ee(Fe(Me.touches))):Me.touches.length===1&&M>1&&(Me.preventDefault(),$(!0),X({x:Me.touches[0].clientX-T.x,y:Me.touches[0].clientY-T.y}))},Se=Me=>{if(Me.touches.length===2&&L!==null){Me.preventDefault();const Ve=Te(Me.touches),tt=Ve/L;A(xt=>{const wt=Math.max(1,Math.min(4,xt*tt));return wt===1&&C({x:0,y:0}),wt}),te(Ve);const ut=Fe(Me.touches);if(ae){const xt=ye();C(wt=>({x:Math.max(-xt.x,Math.min(xt.x,wt.x+(ut.x-ae.x))),y:Math.max(-xt.y,Math.min(xt.y,wt.y+(ut.y-ae.y)))}))}ee(ut)}else if(Me.touches.length===1&&F&&M>1){Me.preventDefault();const Ve=Me.touches[0].clientX-I.x,tt=Me.touches[0].clientY-I.y,ut=ye();C({x:Math.max(-ut.x,Math.min(ut.x,Ve)),y:Math.max(-ut.y,Math.min(ut.y,tt))})}},je=Me=>{Me.touches.length<2&&(te(null),ee(null)),Me.touches.length===0&&$(!1)},qe=()=>{A(1),C({x:0,y:0})},Re=()=>{K(!1),be<k$?se():le(!0)},Ye=()=>{K(!1),le(!1),_e(0),Y(!1),q.current&&clearTimeout(q.current),de.current&&clearInterval(de.current)},ce=()=>{K(!0),le(!1),_e(0),Y(!1),q.current&&clearTimeout(q.current),de.current&&clearInterval(de.current);const Me={},Ve=Yu();Ve&&(Me.Authorization=`Bearer ${Ve}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Me}).catch(()=>{}),W.current&&(W.current.src=""),setTimeout(()=>oe(Date.now()),100)},ze=Me=>{Me.target.closest(".no-drag")||(f(!0),g({x:Me.clientX-u.x,y:Me.clientY-u.y}))},Ne=Me=>{if(Me.target.closest(".no-drag"))return;const Ve=Me.touches[0];f(!0),g({x:Ve.clientX-u.x,y:Ve.clientY-u.y})},Ge=Me=>{Me.stopPropagation(),v(!0)},$e=Me=>{Me.stopPropagation(),v(!0)};w.useEffect(()=>{const Me=ut=>{if(p)m(xt=>({...xt,x:Math.max(0,Math.min(ut.clientX-b.x,window.innerWidth-xt.width)),y:Math.max(0,Math.min(ut.clientY-b.y,window.innerHeight-xt.height))}));else if(y&&z.current){const xt=z.current.getBoundingClientRect();m(wt=>({...wt,width:Math.max(200,Math.min(ut.clientX-xt.left,window.innerWidth-wt.x-10)),height:Math.max(150,Math.min(ut.clientY-xt.top,window.innerHeight-wt.y-10))}))}},Ve=ut=>{if(!p&&!y)return;ut.preventDefault();const xt=ut.touches[0];if(p)m(wt=>({...wt,x:Math.max(0,Math.min(xt.clientX-b.x,window.innerWidth-wt.width)),y:Math.max(0,Math.min(xt.clientY-b.y,window.innerHeight-wt.height))}));else if(y&&z.current){const wt=z.current.getBoundingClientRect();m(Ht=>({...Ht,width:Math.max(200,Math.min(xt.clientX-wt.left,window.innerWidth-Ht.x-10)),height:Math.max(150,Math.min(xt.clientY-wt.top,window.innerHeight-Ht.y-10))}))}},tt=()=>{f(!1),v(!1)};if(p||y)return document.addEventListener("mousemove",Me),document.addEventListener("mouseup",tt),document.addEventListener("touchmove",Ve,{passive:!1}),document.addEventListener("touchend",tt),document.addEventListener("touchcancel",tt),()=>{document.removeEventListener("mousemove",Me),document.removeEventListener("mouseup",tt),document.removeEventListener("touchmove",Ve),document.removeEventListener("touchend",tt),document.removeEventListener("touchcancel",tt)}},[p,y,b]);const Pe=Ra(`/api/v1/printers/${t}/camera/stream?fps=15&t=${ne}`);return a.jsxs("div",{ref:z,className:`${P?"fixed inset-0 z-[100]":"fixed z-40 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:P?void 0:{left:u.x,top:u.y,width:_?200:u.width,height:_?40:u.height,cursor:p?"grabbing":"default"},children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-bambu-dark border-b border-bambu-dark-tertiary cursor-grab active:cursor-grabbing",onMouseDown:ze,onTouchStart:Ne,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[a.jsx(Eh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:V?.name||e})]}),a.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[a.jsx("button",{onClick:()=>ie.mutate(!J?.chamber_light),disabled:!J?.connected||ie.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${J?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:l("printers:control")?i("camera.chamberLight"):i("printers.permission.noControl"),children:a.jsx(YO,{on:J?.chamber_light??!1,className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>Q(!0),disabled:!he||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${he&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?i(he?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):i("printers.permission.noControl"),children:a.jsx(zP,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:ce,disabled:ue||B,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:a.jsx(vr,{className:`w-3.5 h-3.5 text-bambu-gray ${ue?"animate-spin":""}`})}),a.jsx("button",{onClick:U,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:P?"Exit fullscreen":"Fullscreen",children:P?a.jsx(bQ,{className:"w-3.5 h-3.5 text-bambu-gray"}):a.jsx(Vfe,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:()=>k(!_),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:_?"Expand":"Minimize",children:_?a.jsx(NP,{className:"w-3.5 h-3.5 text-bambu-gray"}):a.jsx(hO,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:a.jsx(Bt,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!_&&a.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:xe,onMouseMove:Ae,onMouseUp:ve,onMouseLeave:ve,onTouchStart:Ee,onTouchMove:Se,onTouchEnd:je,style:{touchAction:"none"},children:[ue&&!B&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsx(vr,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),B&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-2",children:[a.jsx(Ku,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",D,"s..."]})]})}),me&&!B&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-2",children:[a.jsx(Ln,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Camera unavailable"}),a.jsx("button",{onClick:ce,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:"Retry"})]})}),a.jsx("img",{ref:W,src:Pe,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${M}) translate(${T.x/M}px, ${T.y/M}px) rotate(${V?.camera_rotation||0}deg)`,...V?.camera_rotation===90||V?.camera_rotation===270?{maxWidth:"100%",maxHeight:"100%"}:{},cursor:M>1?F?"grabbing":"grab":"default"},onError:Re,onLoad:Ye,onMouseDown:we,draggable:!1},ne),a.jsxs("div",{className:"absolute bottom-2 left-2 flex items-center gap-1 bg-black/60 rounded px-1.5 py-1 no-drag",children:[a.jsx("button",{onClick:re,disabled:M<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:a.jsx(xO,{className:"w-3.5 h-3.5 text-white"})}),a.jsxs("button",{onClick:qe,className:"px-1.5 py-0.5 text-xs text-white hover:bg-white/10 rounded min-w-[32px]",title:"Reset zoom",children:[Math.round(M*100),"%"]}),a.jsx("button",{onClick:R,disabled:M>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:a.jsx(bO,{className:"w-3.5 h-3.5 text-white"})})]}),!P&&a.jsx("div",{className:"absolute bottom-0 right-0 w-6 h-6 cursor-se-resize no-drag hover:bg-white/10 rounded-tl transition-colors",onMouseDown:Ge,onTouchStart:$e,title:"Drag to resize",children:a.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),a.jsx(XO,{printerId:t,isOpen:G,onClose:()=>Q(!1)})]})}function lje({printerId:t,printerName:e,onClose:n}){const{t:r}=Lt(),i=mn(),[s,o]=w.useState(!0),[l,c]=w.useState(new Set),[d,u]=w.useState(""),[m,p]=w.useState("all"),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["mqtt-logs",t],queryFn:()=>pe.getMQTTLogs(t),refetchInterval:1e3}),g=lt({mutationFn:()=>pe.enableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),_=lt({mutationFn:()=>pe.disableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),k=lt({mutationFn:()=>pe.clearMQTTLogs(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}});w.useEffect(()=>{const F=$=>{$.key==="Escape"&&n()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[n]),w.useEffect(()=>{s&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[y?.logs,s]);const P=F=>{c($=>{const I=new Set($);return I.has(F)?I.delete(F):I.add(F),I})},N=F=>new Date(F).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),M=(F,$)=>{if(F==null)return"<empty>";const I=typeof F=="string"?JSON.parse(F):F,X=JSON.stringify(I,null,$?2:0);return!$&&X.length>100?X.substring(0,100)+"...":X},A=y?.logging_enabled??!1,T=w.useMemo(()=>y?.logs??[],[y?.logs]),C=w.useMemo(()=>T.filter(F=>{if(m!=="all"&&F.direction!==m)return!1;if(d.trim()){const $=d.toLowerCase(),I=F.topic.toLowerCase().includes($),L=JSON.stringify(F.payload).toLowerCase().includes($);return I||L}return!0}),[T,d,m]);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("mqttDebug.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[A?a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),disabled:_.isPending,children:[a.jsx(eo,{className:"w-4 h-4"}),r("mqttDebug.stopLogging")]}):a.jsxs(Ie,{size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,children:[a.jsx(Ds,{className:"w-4 h-4"}),r("mqttDebug.startLogging")]}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>k.mutate(),disabled:k.isPending||T.length===0,children:[a.jsx(un,{className:"w-4 h-4"}),r("mqttDebug.clearLog")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>b(),disabled:v,children:a.jsx(vr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:s,onChange:F=>o(F.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[C.length,"/",T.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:r("mqttDebug.searchPlaceholder"),value:d,onChange:F=>u(F.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),d&&a.jsx("button",{onClick:()=>u(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>p("all"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${m==="all"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:r("mqttDebug.all")}),a.jsxs("button",{onClick:()=>p("in"),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${m==="in"?"bg-blue-500 text-white":"text-bambu-gray hover:text-white"}`,children:[a.jsx(bx,{className:"w-3 h-3"}),r("mqttDebug.incoming")]}),a.jsxs("button",{onClick:()=>p("out"),className:`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${m==="out"?"bg-green-500 text-white":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Lf,{className:"w-3 h-3"}),r("mqttDebug.outgoing")]})]})]})]}),a.jsx("div",{ref:f,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:T.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessages")}),!A&&a.jsx("p",{className:"text-sm",children:r("mqttDebug.startLoggingHint")})]}):C.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessagesMatch")}),a.jsx("p",{className:"text-sm",children:r("mqttDebug.adjustFilterHint")})]}):a.jsx("div",{className:"space-y-1",children:C.map((F,$)=>{const I=l.has($),X=F.direction==="in";return a.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${I?"bg-bambu-dark-secondary":""}`,onClick:()=>P($),children:[a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-bambu-gray shrink-0",children:N(F.timestamp)}),a.jsx("span",{className:`shrink-0 ${X?"text-blue-400":"text-green-400"}`,title:r(X?"mqttDebug.incoming":"mqttDebug.outgoing"),children:X?a.jsx(bx,{className:"w-3 h-3"}):a.jsx(Lf,{className:"w-3 h-3"})}),a.jsx("span",{className:"text-purple-400 shrink-0",children:F.topic})]}),I?a.jsx("pre",{className:"mt-2 p-3 bg-gray-900 border border-gray-700 rounded text-green-400 overflow-x-auto whitespace-pre-wrap break-all max-h-96 overflow-y-auto text-xs",children:M(F.payload,!0)}):a.jsx("pre",{className:"mt-1 text-white/80 truncate",children:M(F.payload,!1)})]},$)})})}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-sm text-bambu-gray",children:A?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),r("mqttDebug.loggingActive")]}):a.jsx("span",{children:r("mqttDebug.loggingStopped")})}),a.jsx(Ie,{variant:"secondary",onClick:n,children:r("common.close")})]})]})})}function aJ(t){if(!t)return"/img/printers/default.png";const e=t.toLowerCase().replace(/\s+/g,"");return e.includes("x1e")?"/img/printers/x1e.png":e.includes("x1c")||e.includes("x1carbon")||e.includes("x1")?"/img/printers/x1c.png":e.includes("h2dpro")||e.includes("h2d-pro")?"/img/printers/h2dpro.png":e.includes("h2d")?"/img/printers/h2d.png":e.includes("h2c")?"/img/printers/h2c.png":e.includes("h2s")?"/img/printers/h2d.png":e.includes("p2s")||e.includes("p1s")?"/img/printers/p1s.png":e.includes("p1p")?"/img/printers/p1p.png":e.includes("a1mini")?"/img/printers/a1mini.png":e.includes("a1")?"/img/printers/a1.png":"/img/printers/default.png"}function iJ(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 sJ(t,e,n){return t.filter(r=>{if(r.required_filament_types&&r.required_filament_types.length>0&&e!==void 0&&!r.required_filament_types.every(i=>e.has(i.toUpperCase())))return!1;if(r.filament_overrides&&r.filament_overrides.length>0&&n!==void 0){const i=r.filament_overrides.filter(o=>o.force_color_match===!0),s=r.filament_overrides.filter(o=>o.force_color_match!==!0);if(i.length>0&&!i.every(l=>{const c=(l.type||"").toUpperCase(),d=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${d}`)})||s.length>0&&i.length===0&&!s.some(l=>{const c=(l.type||"").toUpperCase(),d=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${d}`)}))return!1}return!0})}function cje({printerId:t,printerModel:e,printerState:n,plateCleared:r,requirePlateClear:i=!0,loadedFilamentTypes:s,loadedFilaments:o}){const{t:l}=Lt(),c=mn(),{showToast:d}=xn(),{hasPermission:u}=_r(),{data:m}=et({queryKey:["queue",t,"pending",e],queryFn:()=>pe.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),p=lt({mutationFn:()=>pe.clearPlate(t),onSuccess:()=>{c.invalidateQueries({queryKey:["queue",t]}),c.invalidateQueries({queryKey:["printerStatus",t]}),d(l("queue.clearPlateSuccess"),"success")},onError:k=>{d(k.message,"error")}});w.useEffect(()=>{n!=="FINISH"&&n!=="FAILED"&&p.reset()},[n,p]);const f=m?sJ(m,s,o):void 0,y=f?.filter(k=>!k.manual_start)??[],v=f?.length||0;if(v===0)return null;const b=y[0],g=f?.[0];if(i&&(n==="FINISH"||n==="FAILED")&&!r&&y.length>0){const k=b||g;return a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx(Wr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:l("queue.nextInQueue")}),a.jsx("p",{className:"text-sm text-white truncate",children:k?.archive_name||k?.library_file_name||`File #${k?.archive_id||k?.library_file_id}`})]}),v>1&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0",children:["+",v-1]})]}),p.isSuccess?a.jsxs("div",{className:"w-full py-2 px-3 rounded-lg bg-bambu-green/10 border border-bambu-green/20 text-bambu-green text-sm flex items-center justify-center gap-2",children:[a.jsx(Cc,{className:"w-4 h-4"}),l("queue.plateReady")]}):a.jsxs("button",{onClick:()=>p.mutate(),disabled:p.isPending||!u("printers:clear_plate"),className:"w-full py-2 px-3 rounded-lg bg-bambu-green/20 border border-bambu-green/40 text-bambu-green hover:bg-bambu-green/30 transition-colors text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50",children:[p.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Cc,{className:"w-4 h-4"}),l("queue.clearPlate")]})]})}return a.jsx(vo,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx(Wr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:l("queue.nextInQueue")}),a.jsx("p",{className:"text-sm text-white truncate",children:g?.archive_name||g?.library_file_name||`File #${g?.archive_id||g?.library_file_id}`})]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),g?.scheduled_time?Sx(g.scheduled_time,"system",l):l("time.waiting")]}),v>1&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",v-1]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function oJ(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=oJ(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function wr(){for(var t,e,n=0,r="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=oJ(t))&&(r&&(r+=" "),r+=e);return r}var dje=["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 QO(t){if(typeof t!="string")return!1;var e=dje;return e.includes(t)}var uje=["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"],mje=new Set(uje);function lJ(t){return typeof t!="string"?!1:mje.has(t)}function cJ(t){return typeof t=="string"&&t.startsWith("data-")}function to(t){if(typeof t!="object"||t===null)return{};var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(lJ(n)||cJ(n))&&(e[n]=t[n]);return e}function Wf(t){if(t==null)return null;if(w.isValidElement(t)&&typeof t.props=="object"&&t.props!==null){var e=t.props;return to(e)}return typeof t=="object"&&!Array.isArray(t)?to(t):null}function ms(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(lJ(n)||cJ(n)||QO(n))&&(e[n]=t[n]);return e}function hje(t){return t==null?null:w.isValidElement(t)?ms(t.props):typeof t=="object"&&!Array.isArray(t)?ms(t):null}var pje=["children","width","height","viewBox","className","style","title","desc"];function ZF(){return ZF=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ZF.apply(null,arguments)}function fje(t,e){if(t==null)return{};var n,r,i=gje(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function gje(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var ZO=w.forwardRef((t,e)=>{var{children:n,width:r,height:i,viewBox:s,className:o,style:l,title:c,desc:d}=t,u=fje(t,pje),m=s||{width:r,height:i,x:0,y:0},p=wr("recharts-surface",o);return w.createElement("svg",ZF({},ms(u),{className:p,width:r,height:i,style:l,viewBox:"".concat(m.x," ").concat(m.y," ").concat(m.width," ").concat(m.height),ref:e}),w.createElement("title",null,c),w.createElement("desc",null,d),n)}),bje=["children","className"];function JF(){return JF=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},JF.apply(null,arguments)}function xje(t,e){if(t==null)return{};var n,r,i=yje(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function yje(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var Pa=w.forwardRef((t,e)=>{var{children:n,className:r}=t,i=xje(t,bje),s=wr("recharts-layer",r);return w.createElement("g",JF({className:s},ms(i),{ref:e}),n)}),dJ=w.createContext(null),vje=()=>w.useContext(dJ);function ia(t){return function(){return t}}const uJ=Math.cos,wN=Math.sin,Uc=Math.sqrt,SN=Math.PI,UP=2*SN,eR=Math.PI,tR=2*eR,Kp=1e-6,wje=tR-Kp;function mJ(t){this._+=t[0];for(let e=1,n=t.length;e<n;++e)this._+=arguments[e]+t[e]}function Sje(t){let e=Math.floor(t);if(!(e>=0))throw new Error(`invalid digits: ${t}`);if(e>15)return mJ;const n=10**e;return function(r){this._+=r[0];for(let i=1,s=r.length;i<s;++i)this._+=Math.round(arguments[i]*n)/n+r[i]}}class _je{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?mJ:Sje(e)}moveTo(e,n){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,n){this._append`L${this._x1=+e},${this._y1=+n}`}quadraticCurveTo(e,n,r,i){this._append`Q${+e},${+n},${this._x1=+r},${this._y1=+i}`}bezierCurveTo(e,n,r,i,s,o){this._append`C${+e},${+n},${+r},${+i},${this._x1=+s},${this._y1=+o}`}arcTo(e,n,r,i,s){if(e=+e,n=+n,r=+r,i=+i,s=+s,s<0)throw new Error(`negative radius: ${s}`);let o=this._x1,l=this._y1,c=r-e,d=i-n,u=o-e,m=l-n,p=u*u+m*m;if(this._x1===null)this._append`M${this._x1=e},${this._y1=n}`;else if(p>Kp)if(!(Math.abs(m*c-d*u)>Kp)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let f=r-o,y=i-l,v=c*c+d*d,b=f*f+y*y,g=Math.sqrt(v),_=Math.sqrt(p),k=s*Math.tan((eR-Math.acos((v+p-b)/(2*g*_)))/2),P=k/_,N=k/g;Math.abs(P-1)>Kp&&this._append`L${e+P*u},${n+P*m}`,this._append`A${s},${s},0,0,${+(m*f>u*y)},${this._x1=e+N*c},${this._y1=n+N*d}`}}arc(e,n,r,i,s,o){if(e=+e,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(i),c=r*Math.sin(i),d=e+l,u=n+c,m=1^o,p=o?i-s:s-i;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>Kp||Math.abs(this._y1-u)>Kp)&&this._append`L${d},${u}`,r&&(p<0&&(p=p%tR+tR),p>wje?this._append`A${r},${r},0,1,${m},${e-l},${n-c}A${r},${r},0,1,${m},${this._x1=d},${this._y1=u}`:p>Kp&&this._append`A${r},${r},0,${+(p>=eR)},${m},${this._x1=e+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(e,n,r,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+i}h${-r}Z`}toString(){return this._}}function JO(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);e=r}return t},()=>new _je(e)}function eI(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function hJ(t){this._context=t}hJ.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 BP(t){return new hJ(t)}function pJ(t){return t[0]}function fJ(t){return t[1]}function gJ(t,e){var n=ia(!0),r=null,i=BP,s=null,o=JO(l);t=typeof t=="function"?t:t===void 0?pJ:ia(t),e=typeof e=="function"?e:e===void 0?fJ:ia(e);function l(c){var d,u=(c=eI(c)).length,m,p=!1,f;for(r==null&&(s=i(f=o())),d=0;d<=u;++d)!(d<u&&n(m=c[d],d,c))===p&&((p=!p)?s.lineStart():s.lineEnd()),p&&s.point(+t(m,d,c),+e(m,d,c));if(f)return s=null,f+""||null}return l.x=function(c){return arguments.length?(t=typeof c=="function"?c:ia(+c),l):t},l.y=function(c){return arguments.length?(e=typeof c=="function"?c:ia(+c),l):e},l.defined=function(c){return arguments.length?(n=typeof c=="function"?c:ia(!!c),l):n},l.curve=function(c){return arguments.length?(i=c,r!=null&&(s=i(r)),l):i},l.context=function(c){return arguments.length?(c==null?r=s=null:s=i(r=c),l):r},l}function M1(t,e,n){var r=null,i=ia(!0),s=null,o=BP,l=null,c=JO(d);t=typeof t=="function"?t:t===void 0?pJ:ia(+t),e=typeof e=="function"?e:ia(e===void 0?0:+e),n=typeof n=="function"?n:n===void 0?fJ:ia(+n);function d(m){var p,f,y,v=(m=eI(m)).length,b,g=!1,_,k=new Array(v),P=new Array(v);for(s==null&&(l=o(_=c())),p=0;p<=v;++p){if(!(p<v&&i(b=m[p],p,m))===g)if(g=!g)f=p,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),y=p-1;y>=f;--y)l.point(k[y],P[y]);l.lineEnd(),l.areaEnd()}g&&(k[p]=+t(b,p,m),P[p]=+e(b,p,m),l.point(r?+r(b,p,m):k[p],n?+n(b,p,m):P[p]))}if(_)return l=null,_+""||null}function u(){return gJ().defined(i).curve(o).context(s)}return d.x=function(m){return arguments.length?(t=typeof m=="function"?m:ia(+m),r=null,d):t},d.x0=function(m){return arguments.length?(t=typeof m=="function"?m:ia(+m),d):t},d.x1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:ia(+m),d):r},d.y=function(m){return arguments.length?(e=typeof m=="function"?m:ia(+m),n=null,d):e},d.y0=function(m){return arguments.length?(e=typeof m=="function"?m:ia(+m),d):e},d.y1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:ia(+m),d):n},d.lineX0=d.lineY0=function(){return u().x(t).y(e)},d.lineY1=function(){return u().x(t).y(n)},d.lineX1=function(){return u().x(r).y(e)},d.defined=function(m){return arguments.length?(i=typeof m=="function"?m:ia(!!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 bJ{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 kje(t){return new bJ(t,!0)}function Nje(t){return new bJ(t,!1)}const tI={draw(t,e){const n=Uc(e/SN);t.moveTo(n,0),t.arc(0,0,n,0,UP)}},Cje={draw(t,e){const n=Uc(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()}},xJ=Uc(1/3),Pje=xJ*2,Tje={draw(t,e){const n=Uc(e/Pje),r=n*xJ;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},Aje={draw(t,e){const n=Uc(e),r=-n/2;t.rect(r,r,n,n)}},Mje=.8908130915292852,yJ=wN(SN/10)/wN(7*SN/10),jje=wN(UP/10)*yJ,Eje=-uJ(UP/10)*yJ,Dje={draw(t,e){const n=Uc(e*Mje),r=jje*n,i=Eje*n;t.moveTo(0,-n),t.lineTo(r,i);for(let s=1;s<5;++s){const o=UP*s/5,l=uJ(o),c=wN(o);t.lineTo(c*n,-l*n),t.lineTo(l*r-c*i,c*r+l*i)}t.closePath()}},FE=Uc(3),Fje={draw(t,e){const n=-Uc(e/(FE*3));t.moveTo(0,n*2),t.lineTo(-FE*n,-n),t.lineTo(FE*n,-n),t.closePath()}},kl=-.5,Nl=Uc(3)/2,nR=1/Uc(12),Rje=(nR/2+1)*3,Lje={draw(t,e){const n=Uc(e/Rje),r=n/2,i=n*nR,s=r,o=n*nR+n,l=-s,c=o;t.moveTo(r,i),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(kl*r-Nl*i,Nl*r+kl*i),t.lineTo(kl*s-Nl*o,Nl*s+kl*o),t.lineTo(kl*l-Nl*c,Nl*l+kl*c),t.lineTo(kl*r+Nl*i,kl*i-Nl*r),t.lineTo(kl*s+Nl*o,kl*o-Nl*s),t.lineTo(kl*l+Nl*c,kl*c-Nl*l),t.closePath()}};function Oje(t,e){let n=null,r=JO(i);t=typeof t=="function"?t:ia(t||tI),e=typeof e=="function"?e:ia(e===void 0?64:+e);function i(){let s;if(n||(n=s=r()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),s)return n=null,s+""||null}return i.type=function(s){return arguments.length?(t=typeof s=="function"?s:ia(s),i):t},i.size=function(s){return arguments.length?(e=typeof s=="function"?s:ia(+s),i):e},i.context=function(s){return arguments.length?(n=s??null,i):n},i}function _N(){}function kN(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 vJ(t){this._context=t}vJ.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:kN(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:kN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Ije(t){return new vJ(t)}function wJ(t){this._context=t}wJ.prototype={areaStart:_N,areaEnd:_N,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:kN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function zje(t){return new wJ(t)}function SJ(t){this._context=t}SJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:kN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Uje(t){return new SJ(t)}function _J(t){this._context=t}_J.prototype={areaStart:_N,areaEnd:_N,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 Bje(t){return new _J(t)}function N$(t){return t<0?-1:1}function C$(t,e,n){var r=t._x1-t._x0,i=e-t._x1,s=(t._y1-t._y0)/(r||i<0&&-0),o=(n-t._y1)/(i||r<0&&-0),l=(s*i+o*r)/(r+i);return(N$(s)+N$(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function P$(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function RE(t,e,n){var r=t._x0,i=t._y0,s=t._x1,o=t._y1,l=(s-r)/3;t._context.bezierCurveTo(r+l,i+l*e,s-l,o-l*n,s,o)}function NN(t){this._context=t}NN.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:RE(this,this._t0,P$(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,RE(this,P$(this,n=C$(this,t,e)),n);break;default:RE(this,this._t0,n=C$(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function kJ(t){this._context=new NJ(t)}(kJ.prototype=Object.create(NN.prototype)).point=function(t,e){NN.prototype.point.call(this,e,t)};function NJ(t){this._context=t}NJ.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,i,s){this._context.bezierCurveTo(e,t,r,n,s,i)}};function Hje(t){return new NN(t)}function qje(t){return new kJ(t)}function CJ(t){this._context=t}CJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),n===2)this._context.lineTo(t[1],e[1]);else for(var r=T$(t),i=T$(e),s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(r[0][s],i[0][s],r[1][s],i[1][s],t[o],e[o]);(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}};function T$(t){var e,n=t.length-1,r,i=new Array(n),s=new Array(n),o=new Array(n);for(i[0]=0,s[0]=2,o[0]=t[0]+2*t[1],e=1;e<n-1;++e)i[e]=1,s[e]=4,o[e]=4*t[e]+2*t[e+1];for(i[n-1]=2,s[n-1]=7,o[n-1]=8*t[n-1]+t[n],e=1;e<n;++e)r=i[e]/s[e-1],s[e]-=r,o[e]-=r*o[e-1];for(i[n-1]=o[n-1]/s[n-1],e=n-2;e>=0;--e)i[e]=(o[e]-i[e+1])/s[e];for(s[n-1]=(t[n]+i[n-1])/2,e=0;e<n-1;++e)s[e]=2*t[e+1]-i[e+1];return[i,s]}function $je(t){return new CJ(t)}function HP(t,e){this._context=t,this._t=e}HP.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 Vje(t){return new HP(t,.5)}function Gje(t){return new HP(t,0)}function Wje(t){return new HP(t,1)}function Kf(t,e){if((o=t.length)>1)for(var n=1,r,i,s=t[e[0]],o,l=s.length;n<o;++n)for(i=s,s=t[e[n]],r=0;r<l;++r)s[r][1]+=s[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function rR(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function Kje(t,e){return t[e]}function Yje(t){const e=[];return e.key=t,e}function Xje(){var t=ia([]),e=rR,n=Kf,r=Kje;function i(s){var o=Array.from(t.apply(this,arguments),Yje),l,c=o.length,d=-1,u;for(const m of s)for(l=0,++d;l<c;++l)(o[l][d]=[0,+r(m,o[l].key,d,s)]).data=m;for(l=0,u=eI(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:ia(Array.from(s)),i):t},i.value=function(s){return arguments.length?(r=typeof s=="function"?s:ia(+s),i):r},i.order=function(s){return arguments.length?(e=s==null?rR:typeof s=="function"?s:ia(Array.from(s)),i):e},i.offset=function(s){return arguments.length?(n=s??Kf,i):n},i}function Qje(t,e){if((r=t.length)>0){for(var n,r,i=0,s=t[0].length,o;i<s;++i){for(o=n=0;n<r;++n)o+=t[n][i][1]||0;if(o)for(n=0;n<r;++n)t[n][i][1]/=o}Kf(t,e)}}function Zje(t,e){if((i=t.length)>0){for(var n=0,r=t[e[0]],i,s=r.length;n<s;++n){for(var o=0,l=0;o<i;++o)l+=t[o][n][1]||0;r[n][1]+=r[n][0]=-l/2}Kf(t,e)}}function Jje(t,e){if(!(!((o=t.length)>0)||!((s=(i=t[e[0]]).length)>0))){for(var n=0,r=1,i,s,o;r<s;++r){for(var l=0,c=0,d=0;l<o;++l){for(var u=t[e[l]],m=u[r][1]||0,p=u[r-1][1]||0,f=(m-p)/2,y=0;y<l;++y){var v=t[e[y]],b=v[r][1]||0,g=v[r-1][1]||0;f+=b-g}c+=m,d+=f*m}i[r-1][1]+=i[r-1][0]=n,c&&(n-=d/c)}i[r-1][1]+=i[r-1][0]=n,Kf(t,e)}}var LE={},OE={},A$;function eEe(){return A$||(A$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==="__proto__"}t.isUnsafeProperty=e})(OE)),OE}var IE={},M$;function PJ(){return M$||(M$=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})(IE)),IE}var zE={},j$;function nI(){return j$||(j$=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})(zE)),zE}var UE={},BE={},E$;function tEe(){return E$||(E$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(n==null)return"";if(typeof n=="string")return n;if(Array.isArray(n))return n.map(e).join(",");const r=String(n);return r==="0"&&Object.is(Number(n),-0)?"-0":r}t.toString=e})(BE)),BE}var D$;function rI(){return D$||(D$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=tEe(),n=nI();function r(i){if(Array.isArray(i))return i.map(n.toKey);if(typeof i=="symbol")return[i];i=e.toString(i);const s=[],o=i.length;if(o===0)return s;let l=0,c="",d="",u=!1;for(i.charCodeAt(0)===46&&(s.push(""),l++);l<o;){const m=i[l];d?m==="\\"&&l+1<o?(l++,c+=i[l]):m===d?d="":c+=m:u?m==='"'||m==="'"?d=m:m==="]"?(u=!1,s.push(c),c=""):c+=m:m==="["?(u=!0,c&&(s.push(c),c="")):m==="."?c&&(s.push(c),c=""):c+=m,l++}return c&&s.push(c),s}t.toPath=r})(UE)),UE}var F$;function aI(){return F$||(F$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=eEe(),n=PJ(),r=nI(),i=rI();function s(l,c,d){if(l==null)return d;switch(typeof c){case"string":{if(e.isUnsafeProperty(c))return d;const u=l[c];return u===void 0?n.isDeepKey(c)?s(l,i.toPath(c),d):d:u}case"number":case"symbol":{typeof c=="number"&&(c=r.toKey(c));const u=l[c];return u===void 0?d:u}default:{if(Array.isArray(c))return o(l,c,d);if(Object.is(c?.valueOf(),-0)?c="-0":c=String(c),e.isUnsafeProperty(c))return d;const u=l[c];return u===void 0?d:u}}}function o(l,c,d){if(c.length===0)return d;let u=l;for(let m=0;m<c.length;m++){if(u==null||e.isUnsafeProperty(c[m]))return d;u=u[c[m]]}return u===void 0?d:u}t.get=s})(LE)),LE}var HE,R$;function nEe(){return R$||(R$=1,HE=aI().get),HE}var rEe=nEe();const Yf=rc(rEe);var aEe=4;function Sh(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:aEe,n=10**e,r=Math.round(t*n)/n;return Object.is(r,-0)?0:r}function Oa(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return t.reduce((i,s,o)=>{var l=n[o-1];return typeof l=="string"?i+l+s:l!==void 0?i+Sh(l)+s:i+s},"")}var Li=t=>t===0?0:t>0?1:-1,Rc=t=>typeof t=="number"&&t!=+t,Xf=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,on=t=>(typeof t=="number"||t instanceof Number)&&!Rc(t),Jl=t=>on(t)||typeof t=="string",iEe=0,K0=t=>{var e=++iEe;return"".concat(t||"").concat(e)},Es=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!on(e)&&typeof e!="string")return r;var s;if(Xf(e)){if(n==null)return r;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return Rc(s)&&(s=r),i&&n!=null&&s>n&&(s=n),s},TJ=t=>{if(!Array.isArray(t))return!1;for(var e=t.length,n={},r=0;r<e;r++)if(!n[String(t[r])])n[String(t[r])]=!0;else return!0;return!1};function Er(t,e,n){return on(t)&&on(e)?Sh(t+n*(e-t)):e}function AJ(t,e,n){if(!(!t||!t.length))return t.find(r=>r&&(typeof e=="function"?e(r):Yf(r,e))===n)}var Sa=t=>t===null||typeof t>"u",Hw=t=>Sa(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function ko(t){return t!=null}function tp(){}var sEe=["type","size","sizeType"];function aR(){return aR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},aR.apply(null,arguments)}function L$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function O$(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?L$(Object(n),!0).forEach(function(r){oEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):L$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function oEe(t,e,n){return(e=lEe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function lEe(t){var e=cEe(t,"string");return typeof e=="symbol"?e:e+""}function cEe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function dEe(t,e){if(t==null)return{};var n,r,i=uEe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function uEe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var MJ={symbolCircle:tI,symbolCross:Cje,symbolDiamond:Tje,symbolSquare:Aje,symbolStar:Dje,symbolTriangle:Fje,symbolWye:Lje},mEe=Math.PI/180,hEe=t=>{var e="symbol".concat(Hw(t));return MJ[e]||tI},pEe=(t,e,n)=>{if(e==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var r=18*mEe;return 1.25*t*t*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},fEe=(t,e)=>{MJ["symbol".concat(Hw(t))]=e},iI=t=>{var{type:e="circle",size:n=64,sizeType:r="area"}=t,i=dEe(t,sEe),s=O$(O$({},i),{},{type:e,size:n,sizeType:r}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var p=hEe(o),f=Oje().type(p).size(pEe(n,r,o)),y=f();if(y!==null)return y},{className:c,cx:d,cy:u}=s,m=ms(s);return on(d)&&on(u)&&on(n)?w.createElement("path",aR({},m,{className:wr("recharts-symbols",c),transform:"translate(".concat(d,", ").concat(u,")"),d:l()})):null};iI.registerSymbol=fEe;var jJ=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,sI=(t,e)=>{if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(w.isValidElement(t)&&(n=t.props),typeof n!="object"&&typeof n!="function")return null;var r={};return Object.keys(n).forEach(i=>{QO(i)&&(r[i]=(s=>n[i](n,s)))}),r},gEe=(t,e,n)=>r=>(t(e,n,r),null),qw=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var r=null;return Object.keys(t).forEach(i=>{var s=t[i];QO(i)&&typeof s=="function"&&(r||(r={}),r[i]=gEe(s,e,n))}),r};function I$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function bEe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?I$(Object(n),!0).forEach(function(r){xEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):I$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function xEe(t,e,n){return(e=yEe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yEe(t){var e=vEe(t,"string");return typeof e=="symbol"?e:e+""}function vEe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ta(t,e){var n=bEe({},t),r=e,i=Object.keys(e),s=i.reduce((o,l)=>(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return s}function CN(){return CN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},CN.apply(null,arguments)}function z$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function wEe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?z$(Object(n),!0).forEach(function(r){SEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):z$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function SEe(t,e,n){return(e=_Ee(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _Ee(t){var e=kEe(t,"string");return typeof e=="symbol"?e:e+""}function kEe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Al=32,NEe={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle"};function CEe(t){var{data:e,iconType:n,inactiveColor:r}=t,i=Al/2,s=Al/6,o=Al/3,l=e.inactive?r:e.color,c=n??e.type;if(c==="none")return null;if(c==="plainline"){var d;return w.createElement("line",{strokeWidth:4,fill:"none",stroke:l,strokeDasharray:(d=e.payload)===null||d===void 0?void 0:d.strokeDasharray,x1:0,y1:i,x2:Al,y2:i,className:"recharts-legend-icon"})}if(c==="line")return w.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(i,"h").concat(o,`
  8089. A`).concat(s,",").concat(s,",0,1,1,").concat(2*o,",").concat(i,`
  8090. H`).concat(Al,"M").concat(2*o,",").concat(i,`
  8091. A`).concat(s,",").concat(s,",0,1,1,").concat(o,",").concat(i),className:"recharts-legend-icon"});if(c==="rect")return w.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Al/8,"h").concat(Al,"v").concat(Al*3/4,"h").concat(-Al,"z"),className:"recharts-legend-icon"});if(w.isValidElement(e.legendIcon)){var u=wEe({},e);return delete u.legendIcon,w.cloneElement(e.legendIcon,u)}return w.createElement(iI,{fill:l,cx:i,cy:i,size:Al,sizeType:"diameter",type:c})}function PEe(t){var{payload:e,iconSize:n,layout:r,formatter:i,inactiveColor:s,iconType:o}=t,l={x:0,y:0,width:Al,height:Al},c={display:r==="horizontal"?"inline-block":"block",marginRight:10},d={display:"inline-block",verticalAlign:"middle",marginRight:4};return e.map((u,m)=>{var p=u.formatter||i,f=wr({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:u.inactive});if(u.type==="none")return null;var y=u.inactive?s:u.color,v=p?p(u.value,u,m):u.value;return w.createElement("li",CN({className:f,style:c,key:"legend-item-".concat(m)},qw(t,u,m)),w.createElement(ZO,{width:n,height:n,viewBox:l,style:d,"aria-label":"".concat(v," legend icon")},w.createElement(CEe,{data:u,iconType:o,inactiveColor:s})),w.createElement("span",{className:"recharts-legend-item-text",style:{color:y}},v))})}var TEe=t=>{var e=Ta(t,NEe),{payload:n,layout:r,align:i}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?i:"left"};return w.createElement("ul",{className:"recharts-default-legend",style:s},w.createElement(PEe,CN({},e,{payload:n})))},qE={},$E={},U$;function AEe(){return U$||(U$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){const i=new Map;for(let s=0;s<n.length;s++){const o=n[s],l=r(o,s,n);i.has(l)||i.set(l,o)}return Array.from(i.values())}t.uniqBy=e})($E)),$E}var VE={},B$;function MEe(){return B$||(B$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return function(...i){return n.apply(this,i.slice(0,r))}}t.ary=e})(VE)),VE}var GE={},H$;function EJ(){return H$||(H$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n}t.identity=e})(GE)),GE}var WE={},KE={},YE={},q$;function jEe(){return q$||(q$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Number.isSafeInteger(n)&&n>=0}t.isLength=e})(YE)),YE}var $$;function oI(){return $$||($$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=jEe();function n(r){return r!=null&&typeof r!="function"&&e.isLength(r.length)}t.isArrayLike=n})(KE)),KE}var XE={},V$;function EEe(){return V$||(V$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(XE)),XE}var G$;function DEe(){return G$||(G$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=oI(),n=EEe();function r(i){return n.isObjectLike(i)&&e.isArrayLike(i)}t.isArrayLikeObject=r})(WE)),WE}var QE={},ZE={},W$;function FEe(){return W$||(W$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aI();function n(r){return function(i){return e.get(i,r)}}t.property=n})(ZE)),ZE}var JE={},e2={},t2={},n2={},K$;function DJ(){return K$||(K$=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})(n2)),n2}var r2={},Y$;function FJ(){return Y$||(Y$=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})(r2)),r2}var a2={},X$;function RJ(){return X$||(X$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}t.isEqualsSameValueZero=e})(a2)),a2}var Q$;function REe(){return Q$||(Q$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=DJ(),n=FJ(),r=RJ();function i(u,m,p){return typeof p!="function"?i(u,m,()=>{}):s(u,m,function f(y,v,b,g,_,k){const P=p(y,v,b,g,_,k);return P!==void 0?!!P:s(y,v,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):r.isEqualsSameValueZero(u,m);default:return e.isObject(u)?typeof m=="string"?m==="":!0:r.isEqualsSameValueZero(u,m)}}function o(u,m,p,f){if(m==null)return!0;if(Array.isArray(m))return c(u,m,p,f);if(m instanceof Map)return l(u,m,p,f);if(m instanceof Set)return d(u,m,p,f);const y=Object.keys(m);if(u==null||n.isPrimitive(u))return y.length===0;if(y.length===0)return!0;if(f?.has(m))return f.get(m)===u;f?.set(m,u);try{for(let v=0;v<y.length;v++){const b=y[v];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[y,v]of m.entries()){const b=u.get(y);if(p(b,v,y,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 y=new Set;for(let v=0;v<m.length;v++){const b=m[v];let g=!1;for(let _=0;_<u.length;_++){if(y.has(_))continue;const k=u[_];let P=!1;if(p(k,b,v,u,m,f)&&(P=!0),P){y.add(_),g=!0;break}}if(!g)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})(t2)),t2}var Z$;function LJ(){return Z$||(Z$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=REe();function n(r,i){return e.isMatchWith(r,i,()=>{})}t.isMatch=n})(e2)),e2}var i2={},s2={},o2={},J$;function LEe(){return J$||(J$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Object.getOwnPropertySymbols(n).filter(r=>Object.prototype.propertyIsEnumerable.call(n,r))}t.getSymbols=e})(o2)),o2}var l2={},eV;function lI(){return eV||(eV=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})(l2)),l2}var c2={},tV;function OJ(){return tV||(tV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",r="[object Number]",i="[object Boolean]",s="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",d="[object Set]",u="[object Array]",m="[object Function]",p="[object ArrayBuffer]",f="[object Object]",y="[object Error]",v="[object DataView]",b="[object Uint8Array]",g="[object Uint8ClampedArray]",_="[object Uint16Array]",k="[object Uint32Array]",P="[object BigUint64Array]",N="[object Int8Array]",M="[object Int16Array]",A="[object Int32Array]",T="[object BigInt64Array]",C="[object Float32Array]",F="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=p,t.arrayTag=u,t.bigInt64ArrayTag=T,t.bigUint64ArrayTag=P,t.booleanTag=i,t.dataViewTag=v,t.dateTag=l,t.errorTag=y,t.float32ArrayTag=C,t.float64ArrayTag=F,t.functionTag=m,t.int16ArrayTag=M,t.int32ArrayTag=A,t.int8ArrayTag=N,t.mapTag=c,t.numberTag=r,t.objectTag=f,t.regexpTag=e,t.setTag=d,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=_,t.uint32ArrayTag=k,t.uint8ArrayTag=b,t.uint8ClampedArrayTag=g})(c2)),c2}var d2={},nV;function OEe(){return nV||(nV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(d2)),d2}var rV;function IJ(){return rV||(rV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=LEe(),n=lI(),r=OJ(),i=FJ(),s=OEe();function o(u,m){return l(u,void 0,u,new Map,m)}function l(u,m,p,f=new Map,y=void 0){const v=y?.(u,m,p,f);if(v!==void 0)return v;if(i.isPrimitive(u))return u;if(f.has(u))return f.get(u);if(Array.isArray(u)){const b=new Array(u.length);f.set(u,b);for(let g=0;g<u.length;g++)b[g]=l(u[g],g,p,f,y);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[g,_]of u)b.set(g,l(_,g,p,f,y));return b}if(u instanceof Set){const b=new Set;f.set(u,b);for(const g of u)b.add(l(g,void 0,p,f,y));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 g=0;g<u.length;g++)b[g]=l(u[g],g,p,f,y);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,y),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,y),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,y),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,y),b}if(u instanceof Boolean){const b=new Boolean(u.valueOf());return f.set(u,b),c(b,u,p,f,y),b}if(u instanceof Number){const b=new Number(u.valueOf());return f.set(u,b),c(b,u,p,f,y),b}if(u instanceof String){const b=new String(u.valueOf());return f.set(u,b),c(b,u,p,f,y),b}if(typeof u=="object"&&d(u)){const b=Object.create(Object.getPrototypeOf(u));return f.set(u,b),c(b,u,p,f,y),b}return u}function c(u,m,p=u,f,y){const v=[...Object.keys(m),...e.getSymbols(m)];for(let b=0;b<v.length;b++){const g=v[b],_=Object.getOwnPropertyDescriptor(u,g);(_==null||_.writable)&&(u[g]=l(m[g],g,p,f,y))}}function d(u){switch(n.getTag(u)){case r.argumentsTag:case r.arrayTag:case r.arrayBufferTag:case r.dataViewTag:case r.booleanTag:case r.dateTag:case r.float32ArrayTag:case r.float64ArrayTag:case r.int8ArrayTag:case r.int16ArrayTag:case r.int32ArrayTag:case r.mapTag:case r.numberTag:case r.objectTag:case r.regexpTag:case r.setTag:case r.stringTag:case r.symbolTag:case r.uint8ArrayTag:case r.uint8ClampedArrayTag:case r.uint16ArrayTag:case r.uint32ArrayTag:return!0;default:return!1}}t.cloneDeepWith=o,t.cloneDeepWithImpl=l,t.copyProperties=c})(s2)),s2}var aV;function IEe(){return aV||(aV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=IJ();function n(r){return e.cloneDeepWithImpl(r,void 0,r,new Map,void 0)}t.cloneDeep=n})(i2)),i2}var iV;function zEe(){return iV||(iV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=LJ(),n=IEe();function r(i){return i=n.cloneDeep(i),s=>e.isMatch(s,i)}t.matches=r})(JE)),JE}var u2={},m2={},h2={},sV;function UEe(){return sV||(sV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=IJ(),n=lI(),r=OJ();function i(s,o){return e.cloneDeepWith(s,(l,c,d,u)=>{const m=o?.(l,c,d,u);if(m!==void 0)return m;if(typeof s=="object"){if(n.getTag(s)===r.objectTag&&typeof s.constructor!="function"){const p={};return u.set(s,p),e.copyProperties(p,s,d,u),p}switch(Object.prototype.toString.call(s)){case r.numberTag:case r.stringTag:case r.booleanTag:{const p=new s.constructor(s?.valueOf());return e.copyProperties(p,s),p}case r.argumentsTag:{const p={};return e.copyProperties(p,s),p.length=s.length,p[Symbol.iterator]=s[Symbol.iterator],p}default:return}}})}t.cloneDeepWith=i})(h2)),h2}var oV;function BEe(){return oV||(oV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=UEe();function n(r){return e.cloneDeepWith(r)}t.cloneDeep=n})(m2)),m2}var p2={},f2={},lV;function zJ(){return lV||(lV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(r,i=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&r<i;case"symbol":return!1;case"string":return e.test(r)}}t.isIndex=n})(f2)),f2}var g2={},cV;function HEe(){return cV||(cV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=lI();function n(r){return r!==null&&typeof r=="object"&&e.getTag(r)==="[object Arguments]"}t.isArguments=n})(g2)),g2}var dV;function qEe(){return dV||(dV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=PJ(),n=zJ(),r=HEe(),i=rI();function s(o,l){let c;if(Array.isArray(l)?c=l:typeof l=="string"&&e.isDeepKey(l)&&o?.[l]==null?c=i.toPath(l):c=[l],c.length===0)return!1;let d=o;for(let u=0;u<c.length;u++){const m=c[u];if((d==null||!Object.hasOwn(d,m))&&!((Array.isArray(d)||r.isArguments(d))&&n.isIndex(m)&&m<d.length))return!1;d=d[m]}return!0}t.has=s})(p2)),p2}var uV;function $Ee(){return uV||(uV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=LJ(),n=nI(),r=BEe(),i=aI(),s=qEe();function o(l,c){switch(typeof l){case"object":{Object.is(l?.valueOf(),-0)&&(l="-0");break}case"number":{l=n.toKey(l);break}}return c=r.cloneDeep(c),function(d){const u=i.get(d,l);return u===void 0?s.has(d,l):c===void 0?u===void 0:e.isMatch(u,c)}}t.matchesProperty=o})(u2)),u2}var mV;function VEe(){return mV||(mV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=EJ(),n=FEe(),r=zEe(),i=$Ee();function s(o){if(o==null)return e.identity;switch(typeof o){case"function":return o;case"object":return Array.isArray(o)&&o.length===2?i.matchesProperty(o[0],o[1]):r.matches(o);case"string":case"symbol":case"number":return n.property(o)}}t.iteratee=s})(QE)),QE}var hV;function GEe(){return hV||(hV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=AEe(),n=MEe(),r=EJ(),i=DEe(),s=VEe();function o(l,c=r.identity){return i.isArrayLikeObject(l)?e.uniqBy(Array.from(l),n.ary(s.iteratee(c),1)):[]}t.uniqBy=o})(qE)),qE}var b2,pV;function WEe(){return pV||(pV=1,b2=GEe().uniqBy),b2}var KEe=WEe();const fV=rc(KEe);function UJ(t,e,n){return e===!0?fV(t,n):typeof e=="function"?fV(t,e):t}var x2={exports:{}},y2={};var gV;function YEe(){if(gV)return y2;gV=1;var t=og(),e=NX();function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,i=e.useSyncExternalStore,s=t.useRef,o=t.useEffect,l=t.useMemo,c=t.useDebugValue;return y2.useSyncExternalStoreWithSelector=function(d,u,m,p,f){var y=s(null);if(y.current===null){var v={hasValue:!1,value:null};y.current=v}else v=y.current;y=l(function(){function g(M){if(!_){if(_=!0,k=M,M=p(M),f!==void 0&&v.hasValue){var A=v.value;if(f(A,M))return P=A}return P=M}if(A=P,r(k,M))return A;var T=p(M);return f!==void 0&&f(A,T)?(k=M,A):(k=M,P=T)}var _=!1,k,P,N=m===void 0?null:m;return[function(){return g(u())},N===null?void 0:function(){return g(N())}]},[u,m,p,f]);var b=i(d,y[0],y[1]);return o(function(){v.hasValue=!0,v.value=b},[b]),c(b),b},y2}var bV;function XEe(){return bV||(bV=1,x2.exports=YEe()),x2.exports}var BJ=XEe(),cI=w.createContext(null),QEe=t=>t,ta=()=>{var t=w.useContext(cI);return t?t.store.dispatch:QEe},Ak=()=>{},ZEe=()=>Ak,JEe=(t,e)=>t===e;function dn(t){var e=w.useContext(cI),n=w.useMemo(()=>e?r=>{if(r!=null)return t(r)}:Ak,[e,t]);return BJ.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:ZEe,e?e.store.getState:Ak,e?e.store.getState:Ak,n,JEe)}function e2e(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function t2e(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function n2e(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(n=>typeof n=="function")){const n=t.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${e}[${n}]`)}}var xV=t=>Array.isArray(t)?t:[t];function r2e(t){const e=Array.isArray(t[0])?t[0]:t;return n2e(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function a2e(t,e){const n=[],{length:r}=t;for(let i=0;i<r;i++)n.push(t[i].apply(null,e));return n}var i2e=class{constructor(t){this.value=t}deref(){return this.value}},s2e=typeof WeakRef<"u"?WeakRef:i2e,o2e=0,yV=1;function j1(){return{s:o2e,v:void 0,o:null,p:null}}function HJ(t,e={}){let n=j1();const{resultEqualityCheck:r}=e;let i,s=0;function o(){let l=n;const{length:c}=arguments;for(let m=0,p=c;m<p;m++){const f=arguments[m];if(typeof f=="function"||typeof f=="object"&&f!==null){let y=l.o;y===null&&(l.o=y=new WeakMap);const v=y.get(f);v===void 0?(l=j1(),y.set(f,l)):l=v}else{let y=l.p;y===null&&(l.p=y=new Map);const v=y.get(f);v===void 0?(l=j1(),y.set(f,l)):l=v}}const d=l;let u;if(l.s===yV)u=l.v;else if(u=t.apply(null,arguments),s++,r){const m=i?.deref?.()??i;m!=null&&r(m,u)&&(u=m,s!==0&&s--),i=typeof u=="object"&&u!==null||typeof u=="function"?new s2e(u):u}return d.s=yV,d.v=u,u}return o.clearCache=()=>{n=j1(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function l2e(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,r=(...i)=>{let s=0,o=0,l,c={},d=i.pop();typeof d=="object"&&(c=d,d=i.pop()),e2e(d,`createSelector expects an output function after the inputs, but received: [${typeof d}]`);const u={...n,...c},{memoize:m,memoizeOptions:p=[],argsMemoize:f=HJ,argsMemoizeOptions:y=[]}=u,v=xV(p),b=xV(y),g=r2e(i),_=m(function(){return s++,d.apply(null,arguments)},...v),k=f(function(){o++;const N=a2e(g,arguments);return l=_.apply(null,N),l},...b);return Object.assign(k,{resultFunc:d,memoizedResultFunc:_,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:m,argsMemoize:f})};return Object.assign(r,{withTypes:()=>r}),r}var yt=l2e(HJ),c2e=Object.assign((t,e=yt)=>{t2e(t,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof t}`);const n=Object.keys(t),r=n.map(s=>t[s]);return e(r,(...s)=>s.reduce((o,l,c)=>(o[n[c]]=l,o),{}))},{withTypes:()=>c2e}),v2={},w2={},S2={},vV;function d2e(){return vV||(vV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(r){return typeof r=="symbol"?1:r===null?2:r===void 0?3:r!==r?4:0}const n=(r,i,s)=>{if(r!==i){const o=e(r),l=e(i);if(o===l&&o===0){if(r<i)return s==="desc"?1:-1;if(r>i)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(S2)),S2}var _2={},k2={},wV;function qJ(){return wV||(wV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(k2)),k2}var SV;function u2e(){return SV||(SV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=qJ(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function i(s,o){return Array.isArray(s)?!1:typeof s=="number"||typeof s=="boolean"||s==null||e.isSymbol(s)?!0:typeof s=="string"&&(r.test(s)||!n.test(s))||o!=null&&Object.hasOwn(o,s)}t.isKey=i})(_2)),_2}var _V;function m2e(){return _V||(_V=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=d2e(),n=u2e(),r=rI();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,y)=>{let v=f;for(let b=0;b<y.length&&v!=null;++b)v=v[y[b]];return v},u=(f,y)=>y==null||f==null?y:typeof f=="object"&&"key"in f?Object.hasOwn(y,f.key)?y[f.key]:d(y,f.path):typeof f=="function"?f(y):Array.isArray(f)?d(y,f):typeof y=="object"?y[f]:y,m=o.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==null||typeof f=="function"||Array.isArray(f)||n.isKey(f)?f:{key:f,path:r.toPath(f)}));return s.map(f=>({original:f,criteria:m.map(y=>u(y,f))})).slice().sort((f,y)=>{for(let v=0;v<m.length;v++){const b=e.compareValues(f.criteria[v],y.criteria[v],l[v]);if(b!==0)return b}return 0}).map(f=>f.original)}t.orderBy=i})(w2)),w2}var N2={},kV;function h2e(){return kV||(kV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r=1){const i=[],s=Math.floor(r),o=(l,c)=>{for(let d=0;d<l.length;d++){const u=l[d];Array.isArray(u)&&c<s?o(u,c+1):i.push(u)}};return o(n,0),i}t.flatten=e})(N2)),N2}var C2={},NV;function $J(){return NV||(NV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=zJ(),n=oI(),r=DJ(),i=RJ();function s(o,l,c){return r.isObject(c)&&(typeof l=="number"&&n.isArrayLike(c)&&e.isIndex(l)&&l<c.length||typeof l=="string"&&l in c)?i.isEqualsSameValueZero(c[l],o):!1}t.isIterateeCall=s})(C2)),C2}var CV;function p2e(){return CV||(CV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=m2e(),n=h2e(),r=$J();function i(s,...o){const l=o.length;return l>1&&r.isIterateeCall(s,o[0],o[1])?o=[]:l>2&&r.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),e.orderBy(s,n.flatten(o),["asc"])}t.sortBy=i})(v2)),v2}var P2,PV;function f2e(){return PV||(PV=1,P2=p2e().sortBy),P2}var g2e=f2e();const qP=rc(g2e);var VJ=t=>t.legend.settings,b2e=t=>t.legend.size,x2e=t=>t.legend.payload,y2e=yt([x2e,VJ],(t,e)=>{var{itemSorter:n}=e,r=t.flat(1);return n?qP(r,n):r});function v2e(){return dn(y2e)}var E1=1;function GJ(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[e,n]=w.useState({height:0,left:0,top:0,width:0}),r=w.useCallback(i=>{if(i!=null){var s=i.getBoundingClientRect(),o={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(o.height-e.height)>E1||Math.abs(o.left-e.left)>E1||Math.abs(o.top-e.top)>E1||Math.abs(o.width-e.width)>E1)&&n({height:o.height,left:o.left,top:o.top,width:o.width})}},[e.width,e.height,e.top,e.left,...t]);return[e,r]}function Ji(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 w2e=typeof Symbol=="function"&&Symbol.observable||"@@observable",TV=w2e,T2=()=>Math.random().toString(36).substring(7).split("").join("."),S2e={INIT:`@@redux/INIT${T2()}`,REPLACE:`@@redux/REPLACE${T2()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${T2()}`},PN=S2e;function dI(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 WJ(t,e,n){if(typeof t!="function")throw new Error(Ji(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Ji(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Ji(1));return n(WJ)(t,e)}let r=t,i=e,s=new Map,o=s,l=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((b,g)=>{o.set(g,b)}))}function u(){if(c)throw new Error(Ji(3));return i}function m(b){if(typeof b!="function")throw new Error(Ji(4));if(c)throw new Error(Ji(5));let g=!0;d();const _=l++;return o.set(_,b),function(){if(g){if(c)throw new Error(Ji(6));g=!1,d(),o.delete(_),s=null}}}function p(b){if(!dI(b))throw new Error(Ji(7));if(typeof b.type>"u")throw new Error(Ji(8));if(typeof b.type!="string")throw new Error(Ji(17));if(c)throw new Error(Ji(9));try{c=!0,i=r(i,b)}finally{c=!1}return(s=o).forEach(_=>{_()}),b}function f(b){if(typeof b!="function")throw new Error(Ji(10));r=b,p({type:PN.REPLACE})}function y(){const b=m;return{subscribe(g){if(typeof g!="object"||g===null)throw new Error(Ji(11));function _(){const P=g;P.next&&P.next(u())}return _(),{unsubscribe:b(_)}},[TV](){return this}}}return p({type:PN.INIT}),{dispatch:p,subscribe:m,getState:u,replaceReducer:f,[TV]:y}}function _2e(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:PN.INIT})>"u")throw new Error(Ji(12));if(typeof n(void 0,{type:PN.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Ji(13))})}function KJ(t){const e=Object.keys(t),n={};for(let s=0;s<e.length;s++){const o=e[s];typeof t[o]=="function"&&(n[o]=t[o])}const r=Object.keys(n);let i;try{_2e(n)}catch(s){i=s}return function(o={},l){if(i)throw i;let c=!1;const d={};for(let u=0;u<r.length;u++){const m=r[u],p=n[m],f=o[m],y=p(f,l);if(typeof y>"u")throw l&&l.type,new Error(Ji(14));d[m]=y,c=c||y!==f}return c=c||r.length!==Object.keys(o).length,c?d:o}}function TN(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...r)=>e(n(...r)))}function k2e(...t){return e=>(n,r)=>{const i=e(n,r);let s=()=>{throw new Error(Ji(15))};const o={getState:i.getState,dispatch:(c,...d)=>s(c,...d)},l=t.map(c=>c(o));return s=TN(...l)(i.dispatch),{...i,dispatch:s}}}function YJ(t){return dI(t)&&"type"in t&&typeof t.type=="string"}var XJ=Symbol.for("immer-nothing"),AV=Symbol.for("immer-draftable"),no=Symbol.for("immer-state");function Sc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var tl=Object,Ex=tl.getPrototypeOf,AN="constructor",$P="prototype",iR="configurable",MN="enumerable",Mk="writable",Y0="value",Zu=t=>!!t&&!!t[no];function Lc(t){return t?QJ(t)||GP(t)||!!t[AV]||!!t[AN]?.[AV]||WP(t)||KP(t):!1}var N2e=tl[$P][AN].toString(),MV=new WeakMap;function QJ(t){if(!t||!uI(t))return!1;const e=Ex(t);if(e===null||e===tl[$P])return!0;const n=tl.hasOwnProperty.call(e,AN)&&e[AN];if(n===Object)return!0;if(!Bb(n))return!1;let r=MV.get(n);return r===void 0&&(r=Function.toString.call(n),MV.set(n,r)),r===N2e}function VP(t,e,n=!0){$w(t)===0?(n?Reflect.ownKeys(t):tl.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((r,i)=>e(i,r,t))}function $w(t){const e=t[no];return e?e.type_:GP(t)?1:WP(t)?2:KP(t)?3:0}var jV=(t,e,n=$w(t))=>n===2?t.has(e):tl[$P].hasOwnProperty.call(t,e),sR=(t,e,n=$w(t))=>n===2?t.get(e):t[e],jN=(t,e,n,r=$w(t))=>{r===2?t.set(e,n):r===3?t.add(n):t[e]=n};function C2e(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var GP=Array.isArray,WP=t=>t instanceof Map,KP=t=>t instanceof Set,uI=t=>typeof t=="object",Bb=t=>typeof t=="function",A2=t=>typeof t=="boolean";function P2e(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var wu=t=>t.copy_||t.base_,mI=t=>t.modified_?t.copy_:t.base_;function oR(t,e){if(WP(t))return new Map(t);if(KP(t))return new Set(t);if(GP(t))return Array[$P].slice.call(t);const n=QJ(t);if(e===!0||e==="class_only"&&!n){const r=tl.getOwnPropertyDescriptors(t);delete r[no];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const o=i[s],l=r[o];l[Mk]===!1&&(l[Mk]=!0,l[iR]=!0),(l.get||l.set)&&(r[o]={[iR]:!0,[Mk]:!0,[MN]:l[MN],[Y0]:t[o]})}return tl.create(Ex(t),r)}else{const r=Ex(t);if(r!==null&&n)return{...t};const i=tl.create(r);return tl.assign(i,t)}}function hI(t,e=!1){return YP(t)||Zu(t)||!Lc(t)||($w(t)>1&&tl.defineProperties(t,{set:D1,add:D1,clear:D1,delete:D1}),tl.freeze(t),e&&VP(t,(n,r)=>{hI(r,!0)},!1)),t}function T2e(){Sc(2)}var D1={[Y0]:T2e};function YP(t){return t===null||!uI(t)?!0:tl.isFrozen(t)}var EN="MapSet",lR="Patches",EV="ArrayMethods",ZJ={};function Qf(t){const e=ZJ[t];return e||Sc(0,t),e}var DV=t=>!!ZJ[t],X0,JJ=()=>X0,A2e=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:DV(EN)?Qf(EN):void 0,arrayMethodsPlugin_:DV(EV)?Qf(EV):void 0});function FV(t,e){e&&(t.patchPlugin_=Qf(lR),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function cR(t){dR(t),t.drafts_.forEach(M2e),t.drafts_=null}function dR(t){t===X0&&(X0=t.parent_)}var RV=t=>X0=A2e(X0,t);function M2e(t){const e=t[no];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function LV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[no].modified_&&(cR(e),Sc(4)),Lc(t)&&(t=OV(e,t));const{patchPlugin_:i}=e;i&&i.generateReplacementPatches_(n[no].base_,t,e)}else t=OV(e,n);return j2e(e,t,!0),cR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==XJ?t:void 0}function OV(t,e){if(YP(e))return e;const n=e[no];if(!n)return DN(e,t.handledSet_,t);if(!XP(n,t))return e;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:r}=n;if(r)for(;r.length>0;)r.pop()(t);nee(n,t)}return n.copy_}function j2e(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&hI(e,n)}function eee(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var XP=(t,e)=>t.scope_===e,E2e=[];function tee(t,e,n,r){const i=wu(t),s=t.type_;if(r!==void 0&&sR(i,r,s)===e){jN(i,r,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;VP(i,(c,d)=>{if(Zu(d)){const u=l.get(d)||[];u.push(c),l.set(d,u)}})}const o=t.draftLocations_.get(e)??E2e;for(const l of o)jN(i,l,n,s)}function D2e(t,e,n){t.callbacks_.push(function(i){const s=e;if(!s||!XP(s,i))return;i.mapSetPlugin_?.fixSetContents(s);const o=mI(s);tee(t,s.draft_??s,o,n),nee(s,i)})}function nee(t,e){if(t.modified_&&!t.finalized_&&(t.type_===3||t.type_===1&&t.allIndicesReassigned_||(t.assigned_?.size??0)>0)){const{patchPlugin_:r}=e;if(r){const i=r.getPath(t);i&&r.generatePatches_(t,i,e)}eee(t)}}function F2e(t,e,n){const{scope_:r}=t;if(Zu(n)){const i=n[no];XP(i,r)&&i.callbacks_.push(function(){jk(t);const o=mI(i);tee(t,n,o,e)})}else Lc(n)&&t.callbacks_.push(function(){const s=wu(t);t.type_===3?s.has(n)&&DN(n,r.handledSet_,r):sR(s,e,t.type_)===n&&r.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&DN(sR(t.copy_,e,t.type_),r.handledSet_,r)})}function DN(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Zu(t)||e.has(t)||!Lc(t)||YP(t)||(e.add(t),VP(t,(r,i)=>{if(Zu(i)){const s=i[no];if(XP(s,n)){const o=mI(s);jN(t,r,o,t.type_),eee(s)}}else Lc(i)&&DN(i,e,n)})),t}function R2e(t,e){const n=GP(t),r={type_:n?1:0,scope_:e?e.scope_:JJ(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=r,s=FN;n&&(i=[r],s=Q0);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return r.draft_=l,r.revoke_=o,[l,r]}var FN={get(t,e){if(e===no)return t;let n=t.scope_.arrayMethodsPlugin_;const r=t.type_===1&&typeof e=="string";if(r&&n?.isArrayOperationMethod(e))return n.createMethodInterceptor(t,e);const i=wu(t);if(!jV(i,e,t.type_))return L2e(t,i,e);const s=i[e];if(t.finalized_||!Lc(s)||r&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&P2e(e))return s;if(s===M2(t.base_,e)){jk(t);const o=t.type_===1?+e:e,l=mR(t.scope_,s,t,o);return t.copy_[o]=l}return s},has(t,e){return e in wu(t)},ownKeys(t){return Reflect.ownKeys(wu(t))},set(t,e,n){const r=ree(wu(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const i=M2(wu(t),e),s=i?.[no];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(C2e(n,i)&&(n!==void 0||jV(t.base_,e,t.type_)))return!0;jk(t),uR(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),F2e(t,e,n)),!0},deleteProperty(t,e){return jk(t),M2(t.base_,e)!==void 0||e in t.base_?(t.assigned_.set(e,!1),uR(t)):t.assigned_.delete(e),t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=wu(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{[Mk]:!0,[iR]:t.type_!==1||e!=="length",[MN]:r[MN],[Y0]:n[e]}},defineProperty(){Sc(11)},getPrototypeOf(t){return Ex(t.base_)},setPrototypeOf(){Sc(12)}},Q0={};for(let t in FN){let e=FN[t];Q0[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}Q0.deleteProperty=function(t,e){return Q0.set.call(this,t,e,void 0)};Q0.set=function(t,e,n){return FN.set.call(this,t[0],e,n,t[0])};function M2(t,e){const n=t[no];return(n?wu(n):t)[e]}function L2e(t,e,n){const r=ree(e,n);return r?Y0 in r?r[Y0]:r.get?.call(t.draft_):void 0}function ree(t,e){if(!(e in t))return;let n=Ex(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=Ex(n)}}function uR(t){t.modified_||(t.modified_=!0,t.parent_&&uR(t.parent_))}function jk(t){t.copy_||(t.assigned_=new Map,t.copy_=oR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var O2e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,r,i)=>{if(Bb(n)&&!Bb(r)){const o=r;r=n;const l=this;return function(d=o,...u){return l.produce(d,m=>r.call(this,m,...u))}}Bb(r)||Sc(6),i!==void 0&&!Bb(i)&&Sc(7);let s;if(Lc(n)){const o=RV(this),l=mR(o,n,void 0);let c=!0;try{s=r(l),c=!1}finally{c?cR(o):dR(o)}return FV(o,i),LV(s,o)}else if(!n||!uI(n)){if(s=r(n),s===void 0&&(s=n),s===XJ&&(s=void 0),this.autoFreeze_&&hI(s,!0),i){const o=[],l=[];Qf(lR).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),i(o,l)}return s}else Sc(1,n)},this.produceWithPatches=(n,r)=>{if(Bb(n))return(l,...c)=>this.produceWithPatches(l,d=>n(d,...c));let i,s;return[this.produce(n,r,(l,c)=>{i=l,s=c}),i,s]},A2(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),A2(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),A2(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Lc(e)||Sc(8),Zu(e)&&(e=jc(e));const n=RV(this),r=mR(n,e,void 0);return r[no].isManual_=!0,dR(n),r}finishDraft(e,n){const r=e&&e[no];(!r||!r.isManual_)&&Sc(9);const{scope_:i}=r;return FV(i,n),LV(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,n){let r;for(r=n.length-1;r>=0;r--){const s=n[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(n=n.slice(r+1));const i=Qf(lR).applyPatches_;return Zu(e)?i(e,n):this.produce(e,s=>i(s,n))}};function mR(t,e,n,r){const[i,s]=WP(e)?Qf(EN).proxyMap_(e,n):KP(e)?Qf(EN).proxySet_(e,n):R2e(e,n);return(n?.scope_??JJ()).drafts_.push(i),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&r!==void 0?D2e(n,s,r):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:d}=c;s.modified_&&d&&d.generatePatches_(s,[],c)}),i}function jc(t){return Zu(t)||Sc(10,t),aee(t)}function aee(t){if(!Lc(t)||YP(t))return t;const e=t[no];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=oR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=oR(t,!0);return VP(n,(i,s)=>{jN(n,i,aee(s))},r),e&&(e.finalized_=!1),n}var I2e=new O2e,iee=I2e.produce;function see(t){return({dispatch:n,getState:r})=>i=>s=>typeof s=="function"?s(n,r,t):i(s)}var z2e=see(),U2e=see,B2e=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?TN:TN.apply(null,arguments)};function ec(t,e){function n(...r){if(e){let i=e(...r);if(!i)throw new Error(il(0));return{type:t,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:t,payload:r[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=r=>YJ(r)&&r.type===t,n}var oee=class Wv extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,Wv.prototype)}static get[Symbol.species](){return Wv}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new Wv(...e[0].concat(this)):new Wv(...e.concat(this))}};function IV(t){return Lc(t)?iee(t,()=>{}):t}function F1(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function H2e(t){return typeof t=="boolean"}var q2e=()=>function(e){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:s=!0}=e??{};let o=new oee;return n&&(H2e(n)?o.push(z2e):o.push(U2e(n.extraArgument))),o},lee="RTK_autoBatch",ba=()=>t=>({payload:t,meta:{[lee]:!0}}),zV=t=>e=>{setTimeout(e,t)},cee=(t={type:"raf"})=>e=>(...n)=>{const r=e(...n);let i=!0,s=!1,o=!1;const l=new Set,c=t.type==="tick"?queueMicrotask:t.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:zV(10):t.type==="callback"?t.queueNotification:zV(t.timeout),d=()=>{o=!1,s&&(s=!1,l.forEach(u=>u()))};return Object.assign({},r,{subscribe(u){const m=()=>i&&u(),p=r.subscribe(m);return l.add(u),()=>{p(),l.delete(u)}},dispatch(u){try{return i=!u?.meta?.[lee],s=!i,s&&(o||(o=!0,c(d))),r.dispatch(u)}finally{i=!0}}})},$2e=t=>function(n){const{autoBatch:r=!0}=n??{};let i=new oee(t);return r&&i.push(cee(typeof r=="object"?r:void 0)),i};function V2e(t){const e=q2e(),{reducer:n=void 0,middleware:r,devTools:i=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(dI(n))l=KJ(n);else throw new Error(il(1));let c;typeof r=="function"?c=r(e):c=e();let d=TN;i&&(d=B2e({trace:!1,...typeof i=="object"&&i}));const u=k2e(...c),m=$2e(u);let p=typeof o=="function"?o(m):m();const f=d(...p);return WJ(l,s,f)}function dee(t){const e={},n=[];let r;const i={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(il(28));if(l in e)throw new Error(il(29));return e[l]=o,i},addAsyncThunk(s,o){return o.pending&&(e[s.pending.type]=o.pending),o.rejected&&(e[s.rejected.type]=o.rejected),o.fulfilled&&(e[s.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:s.settled,reducer:o.settled}),i},addMatcher(s,o){return n.push({matcher:s,reducer:o}),i},addDefaultCase(s){return r=s,i}};return t(i),[e,n,r]}function G2e(t){return typeof t=="function"}function W2e(t,e){let[n,r,i]=dee(e),s;if(G2e(t))s=()=>IV(t());else{const l=IV(t);s=()=>l}function o(l=s(),c){let d=[n[c.type],...r.filter(({matcher:u})=>u(c)).map(({reducer:u})=>u)];return d.filter(u=>!!u).length===0&&(d=[i]),d.reduce((u,m)=>{if(m)if(Zu(u)){const f=m(u,c);return f===void 0?u:f}else{if(Lc(u))return iee(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 K2e="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",Y2e=(t=21)=>{let e="",n=t;for(;n--;)e+=K2e[Math.random()*64|0];return e},X2e=Symbol.for("rtk-slice-createasyncthunk");function Q2e(t,e){return`${t}/${e}`}function Z2e({creators:t}={}){const e=t?.asyncThunk?.[X2e];return function(r){const{name:i,reducerPath:s=i}=r;if(!i)throw new Error(il(11));const o=(typeof r.reducers=="function"?r.reducers(eDe()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(k,P){const N=typeof k=="string"?k:k.type;if(!N)throw new Error(il(12));if(N in c.sliceCaseReducersByType)throw new Error(il(13));return c.sliceCaseReducersByType[N]=P,d},addMatcher(k,P){return c.sliceMatchers.push({matcher:k,reducer:P}),d},exposeAction(k,P){return c.actionCreators[k]=P,d},exposeCaseReducer(k,P){return c.sliceCaseReducersByName[k]=P,d}};l.forEach(k=>{const P=o[k],N={reducerName:k,type:Q2e(i,k),createNotation:typeof r.reducers=="function"};nDe(P)?aDe(N,P,d,e):tDe(N,P,d)});function u(){const[k={},P=[],N=void 0]=typeof r.extraReducers=="function"?dee(r.extraReducers):[r.extraReducers],M={...k,...c.sliceCaseReducersByType};return W2e(r.initialState,A=>{for(let T in M)A.addCase(T,M[T]);for(let T of c.sliceMatchers)A.addMatcher(T.matcher,T.reducer);for(let T of P)A.addMatcher(T.matcher,T.reducer);N&&A.addDefaultCase(N)})}const m=k=>k,p=new Map,f=new WeakMap;let y;function v(k,P){return y||(y=u()),y(k,P)}function b(){return y||(y=u()),y.getInitialState()}function g(k,P=!1){function N(A){let T=A[k];return typeof T>"u"&&P&&(T=F1(f,N,b)),T}function M(A=m){const T=F1(p,P,()=>new WeakMap);return F1(T,A,()=>{const C={};for(const[F,$]of Object.entries(r.selectors??{}))C[F]=J2e($,A,()=>F1(f,A,b),P);return C})}return{reducerPath:k,getSelectors:M,get selectors(){return M(N)},selectSlice:N}}const _={name:i,reducer:v,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:b,...g(s),injectInto(k,{reducerPath:P,...N}={}){const M=P??s;return k.inject({reducerPath:M,reducer:v},N),{..._,...g(M,!0)}}};return _}}function J2e(t,e,n,r){function i(s,...o){let l=e(s);return typeof l>"u"&&r&&(l=n()),t(l,...o)}return i.unwrapped=t,i}var Do=Z2e();function eDe(){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 tDe({type:t,reducerName:e,createNotation:n},r,i){let s,o;if("reducer"in r){if(n&&!rDe(r))throw new Error(il(17));s=r.reducer,o=r.prepare}else s=r;i.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?ec(t,o):ec(t))}function nDe(t){return t._reducerDefinitionType==="asyncThunk"}function rDe(t){return t._reducerDefinitionType==="reducerWithPrepare"}function aDe({type:t,reducerName:e},n,r,i){if(!i)throw new Error(il(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:d,options:u}=n,m=i(t,s,u);r.exposeAction(e,m),o&&r.addCase(m.fulfilled,o),l&&r.addCase(m.pending,l),c&&r.addCase(m.rejected,c),d&&r.addMatcher(m.settled,d),r.exposeCaseReducer(e,{fulfilled:o||R1,pending:l||R1,rejected:c||R1,settled:d||R1})}function R1(){}var iDe="task",uee="listener",mee="completed",pI="cancelled",sDe=`task-${pI}`,oDe=`task-${mee}`,hR=`${uee}-${pI}`,lDe=`${uee}-${mee}`,QP=class{constructor(t){this.code=t,this.message=`${iDe} ${pI} (reason: ${t})`}name="TaskAbortError";message},fI=(t,e)=>{if(typeof t!="function")throw new TypeError(il(32))},RN=()=>{},hee=(t,e=RN)=>(t.catch(e),t),pee=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),kf=t=>{if(t.aborted)throw new QP(t.reason)};function fee(t,e){let n=RN;return new Promise((r,i)=>{const s=()=>i(new QP(t.reason));if(t.aborted){s();return}n=pee(t,s),e.finally(()=>n()).then(r,i)}).finally(()=>{n=RN})}var cDe=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof QP?"cancelled":"rejected",error:n}}finally{e?.()}},LN=t=>e=>hee(fee(t,e).then(n=>(kf(t),n))),gee=t=>{const e=LN(t);return n=>e(new Promise(r=>setTimeout(r,n)))},{assign:cx}=Object,UV={},ZP="listenerMiddleware",dDe=(t,e)=>{const n=r=>pee(t,()=>r.abort(t.reason));return(r,i)=>{fI(r);const s=new AbortController;n(s);const o=cDe(async()=>{kf(t),kf(s.signal);const l=await r({pause:LN(s.signal),delay:gee(s.signal),signal:s.signal});return kf(s.signal),l},()=>s.abort(oDe));return i?.autoJoin&&e.push(o.catch(RN)),{result:LN(t)(o),cancel(){s.abort(sDe)}}}},uDe=(t,e)=>{const n=async(r,i)=>{kf(e);let s=()=>{};const l=[new Promise((c,d)=>{let u=t({predicate:r,effect:(m,p)=>{p.unsubscribe(),c([m,p.getState(),p.getOriginalState()])}});s=()=>{u(),d()}})];i!=null&&l.push(new Promise(c=>setTimeout(c,i,null)));try{const c=await fee(e,Promise.race(l));return kf(e),c}finally{s()}};return(r,i)=>hee(n(r,i))},bee=t=>{let{type:e,actionCreator:n,matcher:r,predicate:i,effect:s}=t;if(e)i=ec(e).match;else if(n)e=n.type,i=n.match;else if(r)i=r;else if(!i)throw new Error(il(21));return fI(s),{predicate:i,type:e,effect:s}},xee=cx(t=>{const{type:e,predicate:n,effect:r}=bee(t);return{id:Y2e(),effect:r,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(il(22))}}},{withTypes:()=>xee}),BV=(t,e)=>{const{type:n,effect:r,predicate:i}=bee(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===i)&&s.effect===r)},pR=t=>{t.pending.forEach(e=>{e.abort(hR)})},mDe=(t,e)=>()=>{for(const n of e.keys())pR(n);t.clear()},HV=(t,e,n)=>{try{t(e,n)}catch(r){setTimeout(()=>{throw r},0)}},yee=cx(ec(`${ZP}/add`),{withTypes:()=>yee}),hDe=ec(`${ZP}/removeAll`),vee=cx(ec(`${ZP}/remove`),{withTypes:()=>vee}),pDe=(...t)=>{console.error(`${ZP}/error`,...t)},Vw=(t={})=>{const e=new Map,n=new Map,r=f=>{const y=n.get(f)??0;n.set(f,y+1)},i=f=>{const y=n.get(f)??1;y===1?n.delete(f):n.set(f,y-1)},{extra:s,onError:o=pDe}=t;fI(o);const l=f=>(f.unsubscribe=()=>e.delete(f.id),e.set(f.id,f),y=>{f.unsubscribe(),y?.cancelActive&&pR(f)}),c=f=>{const y=BV(e,f)??xee(f);return l(y)};cx(c,{withTypes:()=>c});const d=f=>{const y=BV(e,f);return y&&(y.unsubscribe(),f.cancelActive&&pR(y)),!!y};cx(d,{withTypes:()=>d});const u=async(f,y,v,b)=>{const g=new AbortController,_=uDe(c,g.signal),k=[];try{f.pending.add(g),r(f),await Promise.resolve(f.effect(y,cx({},v,{getOriginalState:b,condition:(P,N)=>_(P,N).then(Boolean),take:_,delay:gee(g.signal),pause:LN(g.signal),extra:s,signal:g.signal,fork:dDe(g.signal,k),unsubscribe:f.unsubscribe,subscribe:()=>{e.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((P,N,M)=>{P!==g&&(P.abort(hR),M.delete(P))})},cancel:()=>{g.abort(hR),f.pending.delete(g)},throwIfCancelled:()=>{kf(g.signal)}})))}catch(P){P instanceof QP||HV(o,P,{raisedBy:"effect"})}finally{await Promise.all(k),g.abort(lDe),i(f),f.pending.delete(g)}},m=mDe(e,n);return{middleware:f=>y=>v=>{if(!YJ(v))return y(v);if(yee.match(v))return c(v.payload);if(hDe.match(v)){m();return}if(vee.match(v))return d(v.payload);let b=f.getState();const g=()=>{if(b===UV)throw new Error(il(23));return b};let _;try{if(_=y(v),e.size>0){const k=f.getState(),P=Array.from(e.values());for(const N of P){let M=!1;try{M=N.predicate(v,k,b)}catch(A){M=!1,HV(o,A,{raisedBy:"predicate"})}M&&u(N,v,f,g)}}}finally{b=UV}return _},startListening:c,stopListening:d,clearListeners:m}};function il(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 fDe={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},wee=Do({name:"chartLayout",initialState:fDe,reducers:{setLayout(t,e){t.layoutType=e.payload},setChartSize(t,e){t.width=e.payload.width,t.height=e.payload.height},setMargin(t,e){var n,r,i,s;t.margin.top=(n=e.payload.top)!==null&&n!==void 0?n:0,t.margin.right=(r=e.payload.right)!==null&&r!==void 0?r:0,t.margin.bottom=(i=e.payload.bottom)!==null&&i!==void 0?i:0,t.margin.left=(s=e.payload.left)!==null&&s!==void 0?s:0},setScale(t,e){t.scale=e.payload}}}),{setMargin:gDe,setLayout:bDe,setChartSize:xDe,setScale:yDe}=wee.actions,vDe=wee.reducer;function See(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function qn(t){return Number.isFinite(t)}function Pd(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function qV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Qb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?qV(Object(n),!0).forEach(function(r){wDe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):qV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function wDe(t,e,n){return(e=SDe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function SDe(t){var e=_De(t,"string");return typeof e=="symbol"?e:e+""}function _De(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Dr(t,e,n){return Sa(t)||Sa(e)?n:Jl(e)?Yf(t,e,n):typeof e=="function"?e(t):n}var kDe=(t,e,n)=>{if(e&&n){var{width:r,height:i}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&on(t[s]))return Qb(Qb({},t),{},{[s]:t[s]+(r||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&on(t[o]))return Qb(Qb({},t),{},{[o]:t[o]+(i||0)})}return t},Bc=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",_ee=(t,e,n,r)=>{if(r)return t.map(l=>l.coordinate);var i,s,o=t.map(l=>(l.coordinate===e&&(i=!0),l.coordinate===n&&(s=!0),l.coordinate));return i||o.push(e),s||o.push(n),o},kee=(t,e,n)=>{if(!t)return null;var{duplicateDomain:r,type:i,range:s,scale:o,realScaleType:l,isCategorical:c,categoricalDomain:d,tickCount:u,ticks:m,niceTicks:p,axisType:f}=t;if(!o)return null;var y=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,v=i==="category"&&o.bandwidth?o.bandwidth()/y:0;if(v=f==="angleAxis"&&s&&s.length>=2?Li(s[0]-s[1])*2*v:v,m||p){var b=(m||p||[]).map((g,_)=>{var k=r?r.indexOf(g):g,P=o.map(k);return qn(P)?{coordinate:P+v,value:g,offset:v,index:_}:null}).filter(ko);return b}return c&&d?d.map((g,_)=>{var k=o.map(g);return qn(k)?{coordinate:k+v,value:g,index:_,offset:v}:null}).filter(ko):o.ticks&&u!=null?o.ticks(u).map((g,_)=>{var k=o.map(g);return qn(k)?{coordinate:k+v,value:g,index:_,offset:v}:null}).filter(ko):o.domain().map((g,_)=>{var k=o.map(g);return qn(k)?{coordinate:k+v,value:r?r[g]:g,index:_,offset:v}:null}).filter(ko)},NDe=(t,e)=>{if(!e||e.length!==2||!on(e[0])||!on(e[1]))return t;var n=Math.min(e[0],e[1]),r=Math.max(e[0],e[1]),i=[t[0],t[1]];return(!on(t[0])||t[0]<n)&&(i[0]=n),(!on(t[1])||t[1]>r)&&(i[1]=r),i[0]>r&&(i[0]=r),i[1]<n&&(i[1]=n),i},CDe=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var i=0;i<r;++i)for(var s=0,o=0,l=0;l<n;++l){var c=t[l],d=c?.[i];if(d!=null){var u=d[1],m=d[0],p=Rc(u)?m:u;p>=0?(d[0]=s,s+=p,d[1]=s):(d[0]=o,o+=p,d[1]=o)}}}},PDe=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var i=0;i<r;++i)for(var s=0,o=0;o<n;++o){var l=t[o],c=l?.[i];if(c!=null){var d=Rc(c[1])?c[0]:c[1];d>=0?(c[0]=s,s+=d,c[1]=s):(c[0]=0,c[1]=0)}}}},TDe={sign:CDe,expand:Qje,none:Kf,silhouette:Zje,wiggle:Jje,positive:PDe},ADe=(t,e,n)=>{var r,i=(r=TDe[n])!==null&&r!==void 0?r:Kf,s=Xje().keys(e).value((l,c)=>Number(Dr(l,c,0))).order(rR).offset(i),o=s(t);return o.forEach((l,c)=>{l.forEach((d,u)=>{var m=Dr(t[u],e[c],0);Array.isArray(m)&&m.length===2&&on(m[0])&&on(m[1])&&(d[0]=m[0],d[1]=m[1])})}),o};function Nee(t){return t==null?void 0:String(t)}function ON(t){var{axis:e,ticks:n,bandSize:r,entry:i,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!Sa(i[e.dataKey])){var l=AJ(n,"value",i[e.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[s]?n[s].coordinate+r/2:null}var c=Dr(i,Sa(o)?e.dataKey:o),d=e.scale.map(c);return on(d)?d:null}var $V=t=>{var{axis:e,ticks:n,offset:r,bandSize:i,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+r:null;var l=Dr(s,e.dataKey,e.scale.domain()[o]);if(Sa(l))return null;var c=e.scale.map(l);return on(c)?c-i/2+r:null},MDe=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var r=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return r<=0&&i>=0?0:i<0?i:r}return n[0]},jDe=t=>{var e=t.flat(2).filter(on);return[Math.min(...e),Math.max(...e)]},EDe=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],DDe=(t,e,n)=>{if(t!=null)return EDe(Object.keys(t).reduce((r,i)=>{var s=t[i];if(!s)return r;var{stackedData:o}=s,l=o.reduce((c,d)=>{var u=See(d,e,n),m=jDe(u);return!qn(m[0])||!qn(m[1])?c:[Math.min(c[0],m[0]),Math.max(c[1],m[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},VV=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,GV=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Kh=(t,e,n)=>{if(t&&t.scale&&t.scale.bandwidth){var r=t.scale.bandwidth();if(!n||r>0)return r}if(t&&e&&e.length>=2){for(var i=qP(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 WV(t){var{tooltipEntrySettings:e,dataKey:n,payload:r,value:i,name:s}=t;return Qb(Qb({},e),{},{dataKey:n,payload:r,value:i,name:s})}function np(t,e){if(t)return String(t);if(typeof e=="string")return e}var FDe=(t,e)=>{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},RDe=(t,e)=>e==="centric"?t.angle:t.radius,sm=t=>t.layout.width,om=t=>t.layout.height,LDe=t=>t.layout.scale,Cee=t=>t.layout.margin,JP=yt(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),eT=yt(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),Pee="data-recharts-item-index",Tee="data-recharts-item-id",Gw=60;function KV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function L1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?KV(Object(n),!0).forEach(function(r){ODe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):KV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function ODe(t,e,n){return(e=IDe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function IDe(t){var e=zDe(t,"string");return typeof e=="symbol"?e:e+""}function zDe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var UDe=t=>t.brush.height;function BDe(t){var e=eT(t);return e.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var i=typeof r.width=="number"?r.width:Gw;return n+i}return n},0)}function HDe(t){var e=eT(t);return e.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var i=typeof r.width=="number"?r.width:Gw;return n+i}return n},0)}function qDe(t){var e=JP(t);return e.reduce((n,r)=>r.orientation==="top"&&!r.mirror&&!r.hide?n+r.height:n,0)}function $De(t){var e=JP(t);return e.reduce((n,r)=>r.orientation==="bottom"&&!r.mirror&&!r.hide?n+r.height:n,0)}var wi=yt([sm,om,Cee,UDe,BDe,HDe,qDe,$De,VJ,b2e],(t,e,n,r,i,s,o,l,c,d)=>{var u={left:(n.left||0)+i,right:(n.right||0)+s},m={top:(n.top||0)+o,bottom:(n.bottom||0)+l},p=L1(L1({},m),u),f=p.bottom;p.bottom+=r,p=kDe(p,c,d);var y=t-p.left-p.right,v=e-p.top-p.bottom;return L1(L1({brushBottom:f},p),{},{width:Math.max(y,0),height:Math.max(v,0)})}),VDe=yt(wi,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),gI=yt(sm,om,(t,e)=>({x:0,y:0,width:t,height:e})),GDe=w.createContext(null),Si=()=>w.useContext(GDe)!=null,tT=t=>t.brush,nT=yt([tT,wi,Cee],(t,e,n)=>({height:t.height,x:on(t.x)?t.x:e.left,y:on(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:on(t.width)?t.width:e.width})),j2={},E2={},D2={},YV;function WDe(){return YV||(YV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r,{signal:i,edges:s}={}){let o,l=null;const c=s!=null&&s.includes("leading"),d=s==null||s.includes("trailing"),u=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},m=()=>{d&&u(),v()};let p=null;const f=()=>{p!=null&&clearTimeout(p),p=setTimeout(()=>{p=null,m()},r)},y=()=>{p!==null&&(clearTimeout(p),p=null)},v=()=>{y(),o=void 0,l=null},b=()=>{u()},g=function(..._){if(i?.aborted)return;o=this,l=_;const k=p==null;f(),c&&k&&u()};return g.schedule=f,g.cancel=v,g.flush=b,i?.addEventListener("abort",v,{once:!0}),g}t.debounce=e})(D2)),D2}var XV;function KDe(){return XV||(XV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=WDe();function n(r,i=0,s={}){typeof s!="object"&&(s={});const{leading:o=!1,trailing:l=!0,maxWait:c}=s,d=Array(2);o&&(d[0]="leading"),l&&(d[1]="trailing");let u,m=null;const p=e.debounce(function(...v){u=r.apply(this,v),m=null},i,{edges:d}),f=function(...v){return c!=null&&(m===null&&(m=Date.now()),Date.now()-m>=c)?(u=r.apply(this,v),m=Date.now(),p.cancel(),p.schedule(),u):(p.apply(this,v),u)},y=()=>(p.flush(),u);return f.cancel=p.cancel,f.flush=y,f}t.debounce=n})(E2)),E2}var QV;function YDe(){return QV||(QV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=KDe();function n(r,i=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(r,i,{leading:o,maxWait:i,trailing:l})}t.throttle=n})(j2)),j2}var F2,ZV;function XDe(){return ZV||(ZV=1,F2=YDe().throttle),F2}var QDe=XDe();const ZDe=rc(QDe);var IN=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];if(typeof console<"u"&&console.warn&&(n===void 0&&console.warn("LogUtils requires an error message argument"),!e))if(n===void 0)console.warn("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var o=0;console.warn(n.replace(/%s/g,()=>i[o++]))}},gd={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},Aee=(t,e,n)=>{var{width:r=gd.width,height:i=gd.height,aspect:s,maxHeight:o}=n,l=Xf(r)?t:Number(r),c=Xf(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}},JDe={width:0,height:0,overflow:"visible"},e3e={width:0,overflowX:"visible"},t3e={height:0,overflowY:"visible"},n3e={},r3e=t=>{var{width:e,height:n}=t,r=Xf(e),i=Xf(n);return r&&i?JDe:r?e3e:i?t3e:n3e};function a3e(t){var{width:e,height:n,aspect:r}=t,i=e,s=n;return i===void 0&&s===void 0?(i=gd.width,s=gd.height):i===void 0?i=r&&r>0?void 0:gd.width:s===void 0&&(s=r&&r>0?void 0:gd.height),{width:i,height:s}}function fR(){return fR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},fR.apply(null,arguments)}function JV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function eG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?JV(Object(n),!0).forEach(function(r){i3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):JV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function i3e(t,e,n){return(e=s3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function s3e(t){var e=o3e(t,"string");return typeof e=="symbol"?e:e+""}function o3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Mee=w.createContext(gd.initialDimension);function l3e(t){return Pd(t.width)&&Pd(t.height)}function jee(t){var{children:e,width:n,height:r}=t,i=w.useMemo(()=>({width:n,height:r}),[n,r]);return l3e(i)?w.createElement(Mee.Provider,{value:i},e):null}var bI=()=>w.useContext(Mee),c3e=w.forwardRef((t,e)=>{var{aspect:n,initialDimension:r=gd.initialDimension,width:i,height:s,minWidth:o=gd.minWidth,minHeight:l,maxHeight:c,children:d,debounce:u=gd.debounce,id:m,className:p,onResize:f,style:y={}}=t,v=w.useRef(null),b=w.useRef();b.current=f,w.useImperativeHandle(e,()=>v.current);var[g,_]=w.useState({containerWidth:r.width,containerHeight:r.height}),k=w.useCallback((T,C)=>{_(F=>{var $=Math.round(T),I=Math.round(C);return F.containerWidth===$&&F.containerHeight===I?F:{containerWidth:$,containerHeight:I}})},[]);w.useEffect(()=>{if(v.current==null||typeof ResizeObserver>"u")return tp;var T=I=>{var X,L=I[0];if(L!=null){var{width:te,height:ae}=L.contentRect;k(te,ae),(X=b.current)===null||X===void 0||X.call(b,te,ae)}};u>0&&(T=ZDe(T,u,{trailing:!0,leading:!1}));var C=new ResizeObserver(T),{width:F,height:$}=v.current.getBoundingClientRect();return k(F,$),C.observe(v.current),()=>{C.disconnect()}},[k,u]);var{containerWidth:P,containerHeight:N}=g;IN(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:M,calculatedHeight:A}=Aee(P,N,{width:i,height:s,aspect:n,maxHeight:c});return IN(M!=null&&M>0||A!=null&&A>0,`The width(%s) and height(%s) of chart should be greater than 0,
  8092. please check the style of container, or the props width(%s) and height(%s),
  8093. or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
  8094. height and width.`,M,A,i,s,o,l,n),w.createElement("div",{id:m?"".concat(m):void 0,className:wr("recharts-responsive-container",p),style:eG(eG({},y),{},{width:i,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:v},w.createElement("div",{style:r3e({width:i,height:s})},w.createElement(jee,{width:M,height:A},d)))}),_h=w.forwardRef((t,e)=>{var n=bI();if(Pd(n.width)&&Pd(n.height))return t.children;var{width:r,height:i}=a3e({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=Aee(void 0,void 0,{width:r,height:i,aspect:t.aspect,maxHeight:t.maxHeight});return on(s)&&on(o)?w.createElement(jee,{width:s,height:o},t.children):w.createElement(c3e,fR({},t,{width:r,height:i,ref:e}))});function xI(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 Ww=()=>{var t,e=Si(),n=dn(VDe),r=dn(nT),i=(t=dn(tT))===null||t===void 0?void 0:t.padding;return!e||!r||!i?n:{width:r.width-i.left-i.right,height:r.height-i.top-i.bottom,x:i.left,y:i.top}},d3e={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},Eee=()=>{var t;return(t=dn(wi))!==null&&t!==void 0?t:d3e},yI=()=>dn(sm),vI=()=>dn(om),u3e=()=>dn(t=>t.layout.margin),yr=t=>t.layout.layoutType,rp=()=>dn(yr),wI=()=>{var t=rp();if(t==="horizontal"||t==="vertical")return t},Dee=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},m3e=()=>{var t=rp();return t!==void 0},Kw=t=>{var e=ta(),n=Si(),{width:r,height:i}=t,s=bI(),o=r,l=i;return s&&(o=s.width>0?s.width:r,l=s.height>0?s.height:i),w.useEffect(()=>{!n&&Pd(o)&&Pd(l)&&e(xDe({width:o,height:l}))},[e,n,o,l]),null},Fee=Symbol.for("immer-nothing"),tG=Symbol.for("immer-draftable"),cl=Symbol.for("immer-state");function _c(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Z0=Object.getPrototypeOf;function Dx(t){return!!t&&!!t[cl]}function Zf(t){return t?Ree(t)||Array.isArray(t)||!!t[tG]||!!t.constructor?.[tG]||Yw(t)||aT(t):!1}var h3e=Object.prototype.constructor.toString(),nG=new WeakMap;function Ree(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;const n=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=nG.get(n);return r===void 0&&(r=Function.toString.call(n),nG.set(n,r)),r===h3e}function zN(t,e,n=!0){rT(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((r,i)=>e(i,r,t))}function rT(t){const e=t[cl];return e?e.type_:Array.isArray(t)?1:Yw(t)?2:aT(t)?3:0}function gR(t,e){return rT(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Lee(t,e,n){const r=rT(t);r===2?t.set(e,n):r===3?t.add(n):t[e]=n}function p3e(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Yw(t){return t instanceof Map}function aT(t){return t instanceof Set}function Yp(t){return t.copy_||t.base_}function bR(t,e){if(Yw(t))return new Map(t);if(aT(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=Ree(t);if(e===!0||e==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(t);delete r[cl];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const o=i[s],l=r[o];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[o]={configurable:!0,writable:!0,enumerable:l.enumerable,value:t[o]})}return Object.create(Z0(t),r)}else{const r=Z0(t);if(r!==null&&n)return{...t};const i=Object.create(r);return Object.assign(i,t)}}function SI(t,e=!1){return iT(t)||Dx(t)||!Zf(t)||(rT(t)>1&&Object.defineProperties(t,{set:O1,add:O1,clear:O1,delete:O1}),Object.freeze(t),e&&Object.values(t).forEach(n=>SI(n,!0))),t}function f3e(){_c(2)}var O1={value:f3e};function iT(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var g3e={};function Jf(t){const e=g3e[t];return e||_c(0,t),e}var J0;function Oee(){return J0}function b3e(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function rG(t,e){e&&(Jf("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function xR(t){yR(t),t.drafts_.forEach(x3e),t.drafts_=null}function yR(t){t===J0&&(J0=t.parent_)}function aG(t){return J0=b3e(J0,t)}function x3e(t){const e=t[cl];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function iG(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[cl].modified_&&(xR(e),_c(4)),Zf(t)&&(t=UN(e,t),e.parent_||BN(e,t)),e.patches_&&Jf("Patches").generateReplacementPatches_(n[cl].base_,t,e.patches_,e.inversePatches_)):t=UN(e,n,[]),xR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==Fee?t:void 0}function UN(t,e,n){if(iT(e))return e;const r=t.immer_.shouldUseStrictIteration(),i=e[cl];if(!i)return zN(e,(s,o)=>sG(t,i,e,s,o,n),r),e;if(i.scope_!==t)return e;if(!i.modified_)return BN(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),zN(o,(c,d)=>sG(t,i,s,c,d,n,l),r),BN(t,s,!1),n&&t.patches_&&Jf("Patches").generatePatches_(i,n,t.patches_,t.inversePatches_)}return i.copy_}function sG(t,e,n,r,i,s,o){if(i==null||typeof i!="object"&&!o)return;const l=iT(i);if(!(l&&!o)){if(Dx(i)){const c=s&&e&&e.type_!==3&&!gR(e.assigned_,r)?s.concat(r):void 0,d=UN(t,i,c);if(Lee(n,r,d),Dx(d))t.canAutoFreeze_=!1;else return}else o&&n.add(i);if(Zf(i)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[r]===i&&l)return;UN(t,i),(!e||!e.scope_.parent_)&&typeof r!="symbol"&&(Yw(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&BN(t,i)}}}function BN(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&SI(e,n)}function y3e(t,e){const n=Array.isArray(t),r={type_:n?1:0,scope_:e?e.scope_:Oee(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,s=_I;n&&(i=[r],s=ew);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return r.draft_=l,r.revoke_=o,l}var _I={get(t,e){if(e===cl)return t;const n=Yp(t);if(!gR(n,e))return v3e(t,n,e);const r=n[e];return t.finalized_||!Zf(r)?r:r===R2(t.base_,e)?(L2(t),t.copy_[e]=wR(r,t)):r},has(t,e){return e in Yp(t)},ownKeys(t){return Reflect.ownKeys(Yp(t))},set(t,e,n){const r=Iee(Yp(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const i=R2(Yp(t),e),s=i?.[cl];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if(p3e(n,i)&&(n!==void 0||gR(t.base_,e)))return!0;L2(t),vR(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 R2(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,L2(t),vR(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Yp(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},defineProperty(){_c(11)},getPrototypeOf(t){return Z0(t.base_)},setPrototypeOf(){_c(12)}},ew={};zN(_I,(t,e)=>{ew[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});ew.deleteProperty=function(t,e){return ew.set.call(this,t,e,void 0)};ew.set=function(t,e,n){return _I.set.call(this,t[0],e,n,t[0])};function R2(t,e){const n=t[cl];return(n?Yp(n):t)[e]}function v3e(t,e,n){const r=Iee(e,n);return r?"value"in r?r.value:r.get?.call(t.draft_):void 0}function Iee(t,e){if(!(e in t))return;let n=Z0(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=Z0(n)}}function vR(t){t.modified_||(t.modified_=!0,t.parent_&&vR(t.parent_))}function L2(t){t.copy_||(t.copy_=bR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var w3e=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,n,r)=>{if(typeof e=="function"&&typeof n!="function"){const s=n;n=e;const o=this;return function(c=s,...d){return o.produce(c,u=>n.call(this,u,...d))}}typeof n!="function"&&_c(6),r!==void 0&&typeof r!="function"&&_c(7);let i;if(Zf(e)){const s=aG(this),o=wR(e,void 0);let l=!0;try{i=n(o),l=!1}finally{l?xR(s):yR(s)}return rG(s,r),iG(i,s)}else if(!e||typeof e!="object"){if(i=n(e),i===void 0&&(i=e),i===Fee&&(i=void 0),this.autoFreeze_&&SI(i,!0),r){const s=[],o=[];Jf("Patches").generateReplacementPatches_(e,i,s,o),r(s,o)}return i}else _c(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let r,i;return[this.produce(e,n,(o,l)=>{r=o,i=l}),r,i]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),typeof t?.useStrictIteration=="boolean"&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){Zf(t)||_c(8),Dx(t)&&(t=S3e(t));const e=aG(this),n=wR(t,void 0);return n[cl].isManual_=!0,yR(e),n}finishDraft(t,e){const n=t&&t[cl];(!n||!n.isManual_)&&_c(9);const{scope_:r}=n;return rG(r,e),iG(void 0,r)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let n;for(n=e.length-1;n>=0;n--){const i=e[n];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}n>-1&&(e=e.slice(n+1));const r=Jf("Patches").applyPatches_;return Dx(t)?r(t,e):this.produce(t,i=>r(i,e))}};function wR(t,e){const n=Yw(t)?Jf("MapSet").proxyMap_(t,e):aT(t)?Jf("MapSet").proxySet_(t,e):y3e(t,e);return(e?e.scope_:Oee()).drafts_.push(n),n}function S3e(t){return Dx(t)||_c(10,t),zee(t)}function zee(t){if(!Zf(t)||iT(t))return t;const e=t[cl];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=bR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=bR(t,!0);return zN(n,(i,s)=>{Lee(n,i,zee(s))},r),e&&(e.finalized_=!1),n}var _3e=new w3e;_3e.produce;var k3e={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},Uee=Do({name:"legend",initialState:k3e,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:ba()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:r}=e.payload,i=jc(t).payload.indexOf(n);i>-1&&(t.payload[i]=r)},prepare:ba()},removeLegendPayload:{reducer(t,e){var n=jc(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:ba()}}}),{setLegendSize:oG,setLegendSettings:N3e,addLegendPayload:Bee,replaceLegendPayload:Hee,removeLegendPayload:qee}=Uee.actions,C3e=Uee.reducer,P3e=["contextPayload"];function SR(){return SR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},SR.apply(null,arguments)}function lG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Fx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?lG(Object(n),!0).forEach(function(r){T3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function T3e(t,e,n){return(e=A3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function A3e(t){var e=M3e(t,"string");return typeof e=="symbol"?e:e+""}function M3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function j3e(t,e){if(t==null)return{};var n,r,i=E3e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function E3e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function D3e(t){return t.value}function F3e(t){var{contextPayload:e}=t,n=j3e(t,P3e),r=UJ(e,t.payloadUniqBy,D3e),i=Fx(Fx({},n),{},{payload:r});return w.isValidElement(t.content)?w.cloneElement(t.content,i):typeof t.content=="function"?w.createElement(t.content,i):w.createElement(TEe,i)}function R3e(t,e,n,r,i,s){var{layout:o,align:l,verticalAlign:c}=e,d,u;return(!t||(t.left===void 0||t.left===null)&&(t.right===void 0||t.right===null))&&(l==="center"&&o==="vertical"?d={left:((r||0)-s.width)/2}:d=l==="right"?{right:n&&n.right||0}:{left:n&&n.left||0}),(!t||(t.top===void 0||t.top===null)&&(t.bottom===void 0||t.bottom===null))&&(c==="middle"?u={top:((i||0)-s.height)/2}:u=c==="bottom"?{bottom:n&&n.bottom||0}:{top:n&&n.top||0}),Fx(Fx({},d),u)}function L3e(t){var e=ta();return w.useEffect(()=>{e(N3e(t))},[e,t]),null}function O3e(t){var e=ta();return w.useEffect(()=>(e(oG(t)),()=>{e(oG({width:0,height:0}))}),[e,t]),null}function I3e(t,e,n,r){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||r}:null}var z3e={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function $ee(t){var e=Ta(t,z3e),n=v2e(),r=vje(),i=u3e(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[d,u]=GJ([n]),m=yI(),p=vI();if(m==null||p==null)return null;var f=m-(i?.left||0)-(i?.right||0),y=I3e(e.layout,o,s,f),v=c?l:Fx(Fx({position:"absolute",width:y?.width||s||"auto",height:y?.height||o||"auto"},R3e(l,e,i,m,p,d)),l),b=c??r;if(b==null||n==null)return null;var g=w.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:u},w.createElement(L3e,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&w.createElement(O3e,{width:d.width,height:d.height}),w.createElement(F3e,SR({},e,y,{margin:i,chartWidth:m,chartHeight:p,contextPayload:n})));return Cu.createPortal(g,b)}$ee.displayName="Legend";function _R(){return _R=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_R.apply(null,arguments)}function cG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Nv(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cG(Object(n),!0).forEach(function(r){U3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function U3e(t,e,n){return(e=B3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function B3e(t){var e=H3e(t,"string");return typeof e=="symbol"?e:e+""}function H3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function q3e(t){return Array.isArray(t)&&Jl(t[0])&&Jl(t[1])?t.join(" ~ "):t}var Mb={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},$3e=t=>{var{separator:e=Mb.separator,contentStyle:n,itemStyle:r,labelStyle:i=Mb.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:d,label:u,labelFormatter:m,accessibilityLayer:p=Mb.accessibilityLayer}=t,f=()=>{if(s&&s.length){var N={padding:0,margin:0},M=(l?qP(s,l):s).map((A,T)=>{if(A.type==="none")return null;var C=A.formatter||o||q3e,{value:F,name:$}=A,I=F,X=$;if(C){var L=C(F,$,A,T,s);if(Array.isArray(L))[I,X]=L;else if(L!=null)I=L;else return null}var te=Nv(Nv({},Mb.itemStyle),{},{color:A.color||Mb.itemStyle.color},r);return w.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(T),style:te},Jl(X)?w.createElement("span",{className:"recharts-tooltip-item-name"},X):null,Jl(X)?w.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,w.createElement("span",{className:"recharts-tooltip-item-value"},I),w.createElement("span",{className:"recharts-tooltip-item-unit"},A.unit||""))});return w.createElement("ul",{className:"recharts-tooltip-item-list",style:N},M)}return null},y=Nv(Nv({},Mb.contentStyle),n),v=Nv({margin:0},i),b=!Sa(u),g=b?u:"",_=wr("recharts-default-tooltip",c),k=wr("recharts-tooltip-label",d);b&&m&&s!==void 0&&s!==null&&(g=m(u,s));var P=p?{role:"status","aria-live":"assertive"}:{};return w.createElement("div",_R({className:_,style:y},P),w.createElement("p",{className:k,style:v},w.isValidElement(g)?g:"".concat(g)),f())},Cv="recharts-tooltip-wrapper",V3e={visibility:"hidden"};function G3e(t){var{coordinate:e,translateX:n,translateY:r}=t;return wr(Cv,{["".concat(Cv,"-right")]:on(n)&&e&&on(e.x)&&n>=e.x,["".concat(Cv,"-left")]:on(n)&&e&&on(e.x)&&n<e.x,["".concat(Cv,"-bottom")]:on(r)&&e&&on(e.y)&&r>=e.y,["".concat(Cv,"-top")]:on(r)&&e&&on(e.y)&&r<e.y})}function dG(t){var{allowEscapeViewBox:e,coordinate:n,key:r,offset:i,position:s,reverseDirection:o,tooltipDimension:l,viewBox:c,viewBoxDimension:d}=t;if(s&&on(s[r]))return s[r];var u=n[r]-l-(i>0?i:0),m=n[r]+i;if(e[r])return o[r]?u:m;var p=c[r];if(p==null)return 0;if(o[r]){var f=u,y=p;return f<y?Math.max(m,p):Math.max(u,p)}if(d==null)return 0;var v=m+l,b=p+d;return v>b?Math.max(u,p):Math.max(m,p)}function W3e(t){var{translateX:e,translateY:n,useTranslate3d:r}=t;return{transform:r?"translate3d(".concat(e,"px, ").concat(n,"px, 0)"):"translate(".concat(e,"px, ").concat(n,"px)")}}function K3e(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:r,offsetLeft:i,position:s,reverseDirection:o,tooltipBox:l,useTranslate3d:c,viewBox:d}=t,u,m,p;return l.height>0&&l.width>0&&n?(m=dG({allowEscapeViewBox:e,coordinate:n,key:"x",offset:i,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:d,viewBoxDimension:d.width}),p=dG({allowEscapeViewBox:e,coordinate:n,key:"y",offset:r,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:d,viewBoxDimension:d.height}),u=W3e({translateX:m,translateY:p,useTranslate3d:c})):u=V3e,{cssProperties:u,cssClasses:G3e({translateX:m,translateY:p,coordinate:n})}}function uG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function I1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?uG(Object(n),!0).forEach(function(r){kR(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):uG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function kR(t,e,n){return(e=Y3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Y3e(t){var e=X3e(t,"string");return typeof e=="symbol"?e:e+""}function X3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class Q3e extends w.PureComponent{constructor(){super(...arguments),kR(this,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0}}),kR(this,"handleKeyDown",e=>{if(e.key==="Escape"){var n,r,i,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(n=(r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==null&&n!==void 0?n:0,y:(i=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0}})}})}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}componentDidUpdate(){var e,n;this.state.dismissed&&(((e=this.props.coordinate)===null||e===void 0?void 0:e.x)!==this.state.dismissedAtCoordinate.x||((n=this.props.coordinate)===null||n===void 0?void 0:n.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}render(){var{active:e,allowEscapeViewBox:n,animationDuration:r,animationEasing:i,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:d,position:u,reverseDirection:m,useTranslate3d:p,viewBox:f,wrapperStyle:y,lastBoundingBox:v,innerRef:b,hasPortalFromProps:g}=this.props,_=typeof d=="number"?d:d.x,k=typeof d=="number"?d:d.y,{cssClasses:P,cssProperties:N}=K3e({allowEscapeViewBox:n,coordinate:o,offsetLeft:_,offsetTop:k,position:u,reverseDirection:m,tooltipBox:{height:v.height,width:v.width},useTranslate3d:p,viewBox:f}),M=g?{}:I1(I1({transition:c&&e?"transform ".concat(r,"ms ").concat(i):void 0},N),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),A=I1(I1({},M),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},y);return w.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:P,style:A,ref:b},s)}}var Vee=()=>{var t;return(t=dn(e=>e.rootProps.accessibilityLayer))!==null&&t!==void 0?t:!0};function NR(){return NR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},NR.apply(null,arguments)}function mG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function hG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?mG(Object(n),!0).forEach(function(r){Z3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):mG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Z3e(t,e,n){return(e=J3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function J3e(t){var e=eFe(t,"string");return typeof e=="symbol"?e:e+""}function eFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var pG={curveBasisClosed:zje,curveBasisOpen:Uje,curveBasis:Ije,curveBumpX:kje,curveBumpY:Nje,curveLinearClosed:Bje,curveLinear:BP,curveMonotoneX:Hje,curveMonotoneY:qje,curveNatural:$je,curveStep:Vje,curveStepAfter:Wje,curveStepBefore:Gje},HN=t=>qn(t.x)&&qn(t.y),fG=t=>t.base!=null&&HN(t.base)&&HN(t),Pv=t=>t.x,Tv=t=>t.y,tFe=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(Hw(t));if((n==="curveMonotone"||n==="curveBump")&&e){var r=pG["".concat(n).concat(e==="vertical"?"Y":"X")];if(r)return r}return pG[n]||BP},gG={connectNulls:!1,type:"linear"},nFe=t=>{var{type:e=gG.type,points:n=[],baseLine:r,layout:i,connectNulls:s=gG.connectNulls}=t,o=tFe(e,i),l=s?n.filter(HN):n;if(Array.isArray(r)){var c,d=n.map((y,v)=>hG(hG({},y),{},{base:r[v]}));i==="vertical"?c=M1().y(Tv).x1(Pv).x0(y=>y.base.x):c=M1().x(Pv).y1(Tv).y0(y=>y.base.y);var u=c.defined(fG).curve(o),m=s?d.filter(fG):d;return u(m)}var p;i==="vertical"&&on(r)?p=M1().y(Tv).x1(Pv).x0(r):on(r)?p=M1().x(Pv).y1(Tv).y0(r):p=gJ().x(Pv).y(Tv);var f=p.defined(HN).curve(o);return f(l)},dx=t=>{var{className:e,points:n,path:r,pathRef:i}=t,s=rp();if((!n||!n.length)&&!r)return null;var o={type:t.type,points:t.points,baseLine:t.baseLine,layout:t.layout||s,connectNulls:t.connectNulls},l=n&&n.length?nFe(o):r;return w.createElement("path",NR({},to(t),sI(t),{className:wr("recharts-curve",e),d:l===null?void 0:l,ref:i}))},rFe=["x","y","top","left","width","height","className"];function CR(){return CR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},CR.apply(null,arguments)}function bG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function aFe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?bG(Object(n),!0).forEach(function(r){iFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):bG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function iFe(t,e,n){return(e=sFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function sFe(t){var e=oFe(t,"string");return typeof e=="symbol"?e:e+""}function oFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function lFe(t,e){if(t==null)return{};var n,r,i=cFe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function cFe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var dFe=(t,e,n,r,i,s)=>"M".concat(t,",").concat(i,"v").concat(r,"M").concat(s,",").concat(e,"h").concat(n),uFe=t=>{var{x:e=0,y:n=0,top:r=0,left:i=0,width:s=0,height:o=0,className:l}=t,c=lFe(t,rFe),d=aFe({x:e,y:n,top:r,left:i,width:s,height:o},c);return!on(e)||!on(n)||!on(s)||!on(o)||!on(r)||!on(i)?null:w.createElement("path",CR({},ms(d),{className:wr("recharts-cross",l),d:dFe(e,n,s,o,r,i)}))};function mFe(t,e,n,r){var i=r/2;return{stroke:"none",fill:"#ccc",x:t==="horizontal"?e.x-i:n.left+.5,y:t==="horizontal"?n.top+.5:e.y-i,width:t==="horizontal"?r:n.width-1,height:t==="horizontal"?n.height-1:r}}function xG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function yG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?xG(Object(n),!0).forEach(function(r){hFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):xG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function hFe(t,e,n){return(e=pFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function pFe(t){var e=fFe(t,"string");return typeof e=="symbol"?e:e+""}function fFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var gFe=t=>t.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),Gee=(t,e,n)=>t.map(r=>"".concat(gFe(r)," ").concat(e,"ms ").concat(n)).join(","),bFe=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,r)=>n.filter(i=>r.includes(i))),tw=(t,e)=>Object.keys(e).reduce((n,r)=>yG(yG({},n),{},{[r]:t(r,e[r])}),{});function vG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function fi(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?vG(Object(n),!0).forEach(function(r){xFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):vG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function xFe(t,e,n){return(e=yFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yFe(t){var e=vFe(t,"string");return typeof e=="symbol"?e:e+""}function vFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var qN=(t,e,n)=>t+(e-t)*n,PR=t=>{var{from:e,to:n}=t;return e!==n},Wee=(t,e,n)=>{var r=tw((i,s)=>{if(PR(s)){var[o,l]=t(s.from,s.to,s.velocity);return fi(fi({},s),{},{from:o,velocity:l})}return s},e);return n<1?tw((i,s)=>PR(s)&&r[i]!=null?fi(fi({},s),{},{velocity:qN(s.velocity,r[i].velocity,n),from:qN(s.from,r[i].from,n)}):s,e):Wee(t,r,n-1)};function wFe(t,e,n,r,i,s){var o,l=r.reduce((p,f)=>fi(fi({},p),{},{[f]:{from:t[f],velocity:0,to:e[f]}}),{}),c=()=>tw((p,f)=>f.from,l),d=()=>!Object.values(l).filter(PR).length,u=null,m=p=>{o||(o=p);var f=p-o,y=f/n.dt;l=Wee(n,l,y),i(fi(fi(fi({},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 SFe(t,e,n,r,i,s,o){var l=null,c=i.reduce((m,p)=>{var f=t[p],y=e[p];return f==null||y==null?m:fi(fi({},m),{},{[p]:[f,y]})},{}),d,u=m=>{d||(d=m);var p=(m-d)/r,f=tw((v,b)=>qN(...b,n(p)),c);if(s(fi(fi(fi({},t),e),f)),p<1)l=o.setTimeout(u);else{var y=tw((v,b)=>qN(...b,n(1)),c);s(fi(fi(fi({},t),e),y))}};return()=>(l=o.setTimeout(u),()=>{var m;(m=l)===null||m===void 0||m()})}const _Fe=(t,e,n,r,i,s)=>{var o=bFe(t,e);return n==null?()=>(i(fi(fi({},t),e)),()=>{}):n.isStepper===!0?wFe(t,e,n,o,i,s):SFe(t,e,n,r,o,i,s)};var $N=1e-4,Kee=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],Yee=(t,e)=>t.map((n,r)=>n*e**r).reduce((n,r)=>n+r),wG=(t,e)=>n=>{var r=Kee(t,e);return Yee(r,n)},kFe=(t,e)=>n=>{var r=Kee(t,e),i=[...r.map((s,o)=>s*o).slice(1),0];return Yee(i,n)},NFe=t=>{var e,n=t.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var r=(e=n[1])===null||e===void 0||(e=e.split(")")[0])===null||e===void 0?void 0:e.split(",");if(r==null||r.length!==4)return null;var i=r.map(s=>parseFloat(s));return[i[0],i[1],i[2],i[3]]},CFe=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];if(n.length===1)switch(n[0]){case"linear":return[0,0,1,1];case"ease":return[.25,.1,.25,1];case"ease-in":return[.42,0,1,1];case"ease-out":return[.42,0,.58,1];case"ease-in-out":return[0,0,.58,1];default:{var i=NFe(n[0]);if(i)return i}}return n.length===4?n:[0,0,1,1]},PFe=(t,e,n,r)=>{var i=wG(t,n),s=wG(e,r),o=kFe(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,y=o(m);if(Math.abs(f-u)<$N||y<$N)return s(m);m=l(m-f/y)}return s(m)};return c.isStepper=!1,c},SG=function(){return PFe(...CFe(...arguments))},TFe=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:r=8,dt:i=17}=e,s=(o,l,c)=>{var d=-(o-l)*n,u=c*r,m=c+(d-u)*i/1e3,p=c*i/1e3+o;return Math.abs(p-l)<$N&&Math.abs(m)<$N?[l,0]:[p,m]};return s.isStepper=!0,s.dt=i,s},AFe=t=>{if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return SG(t);case"spring":return TFe();default:if(t.split("(")[0]==="cubic-bezier")return SG(t)}return typeof t=="function"?t:null};function MFe(t){var e,n=()=>null,r=!1,i=null,s=o=>{if(!r){if(Array.isArray(o)){if(!o.length)return;var l=o,[c,...d]=l;if(typeof c=="number"){i=t.setTimeout(s.bind(null,d),c);return}s(c),i=t.setTimeout(s.bind(null,d));return}typeof o=="string"&&(e=o,n(e)),typeof o=="object"&&(e=o,n(e)),typeof o=="function"&&o()}};return{stop:()=>{r=!0},start:o=>{r=!1,i&&(i(),i=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class jFe{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),i=null,s=o=>{o-r>=n?e(o):typeof requestAnimationFrame=="function"&&(i=requestAnimationFrame(s))};return i=requestAnimationFrame(s),()=>{i!=null&&cancelAnimationFrame(i)}}}function EFe(){return MFe(new jFe)}var DFe=w.createContext(EFe);function FFe(t,e){var n=w.useContext(DFe);return w.useMemo(()=>e??n(t),[t,e,n])}var RFe=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Xw={isSsr:RFe()},LFe={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},_G={t:0},O2={t:1};function ly(t){var e=Ta(t,LFe),{isActive:n,canBegin:r,duration:i,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:d}=e,u=n==="auto"?!Xw.isSsr:n,m=FFe(e.animationId,e.animationManager),[p,f]=w.useState(u?_G:O2),y=w.useRef(null);return w.useEffect(()=>{u||f(O2)},[u]),w.useEffect(()=>{if(!u||!r)return tp;var v=_Fe(_G,O2,AFe(s),i,f,m.getTimeoutController()),b=()=>{y.current=v()};return m.start([c,o,b,i,l]),()=>{m.stop(),y.current&&y.current(),l()}},[u,r,i,s,o,c,l,m]),d(p.t)}function cy(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=w.useRef(K0(e)),r=w.useRef(t);return r.current!==t&&(n.current=K0(e),r.current=t),n.current}var OFe=["radius"],IFe=["radius"],kG,NG,CG,PG,TG,AG,MG,jG,EG,DG;function FG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function RG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?FG(Object(n),!0).forEach(function(r){zFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):FG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function zFe(t,e,n){return(e=UFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function UFe(t){var e=BFe(t,"string");return typeof e=="symbol"?e:e+""}function BFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function VN(){return VN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},VN.apply(null,arguments)}function LG(t,e){if(t==null)return{};var n,r,i=HFe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function HFe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function td(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var OG=(t,e,n,r,i)=>{var s=Sh(n),o=Sh(r),l=Math.min(Math.abs(s)/2,Math.abs(o)/2),c=o>=0?1:-1,d=s>=0?1:-1,u=o>=0&&s>=0||o<0&&s<0?1:0,m;if(l>0&&Array.isArray(i)){for(var p=[0,0,0,0],f=0,y=4;f<y;f++){var v,b=(v=i[f])!==null&&v!==void 0?v:0;p[f]=b>l?l:b}m=Oa(kG||(kG=td(["M",",",""])),t,e+c*p[0]),p[0]>0&&(m+=Oa(NG||(NG=td(["A ",",",",0,0,",",",",",""])),p[0],p[0],u,t+d*p[0],e)),m+=Oa(CG||(CG=td(["L ",",",""])),t+n-d*p[1],e),p[1]>0&&(m+=Oa(PG||(PG=td(["A ",",",",0,0,",`,
  8095. `,",",""])),p[1],p[1],u,t+n,e+c*p[1])),m+=Oa(TG||(TG=td(["L ",",",""])),t+n,e+r-c*p[2]),p[2]>0&&(m+=Oa(AG||(AG=td(["A ",",",",0,0,",`,
  8096. `,",",""])),p[2],p[2],u,t+n-d*p[2],e+r)),m+=Oa(MG||(MG=td(["L ",",",""])),t+d*p[3],e+r),p[3]>0&&(m+=Oa(jG||(jG=td(["A ",",",",0,0,",`,
  8097. `,",",""])),p[3],p[3],u,t,e+r-c*p[3])),m+="Z"}else if(l>0&&i===+i&&i>0){var g=Math.min(l,i);m=Oa(EG||(EG=td(["M ",",",`
  8098. A `,",",",0,0,",",",",",`
  8099. L `,",",`
  8100. A `,",",",0,0,",",",",",`
  8101. L `,",",`
  8102. A `,",",",0,0,",",",",",`
  8103. L `,",",`
  8104. A `,",",",0,0,",",",","," Z"])),t,e+c*g,g,g,u,t+d*g,e,t+n-d*g,e,g,g,u,t+n,e+c*g,t+n,e+r-c*g,g,g,u,t+n-d*g,e+r,t+d*g,e+r,g,g,u,t,e+r-c*g)}else m=Oa(DG||(DG=td(["M ",","," h "," v "," h "," Z"])),t,e,n,r,-n);return m},IG={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Xee=t=>{var e=Ta(t,IG),n=w.useRef(null),[r,i]=w.useState(-1);w.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var ee=n.current.getTotalLength();ee&&i(ee)}catch{}},[]);var{x:s,y:o,width:l,height:c,radius:d,className:u}=e,{animationEasing:m,animationDuration:p,animationBegin:f,isAnimationActive:y,isUpdateAnimationActive:v}=e,b=w.useRef(l),g=w.useRef(c),_=w.useRef(s),k=w.useRef(o),P=w.useMemo(()=>({x:s,y:o,width:l,height:c,radius:d}),[s,o,l,c,d]),N=cy(P,"rectangle-");if(s!==+s||o!==+o||l!==+l||c!==+c||l===0||c===0)return null;var M=wr("recharts-rectangle",u);if(!v){var A=ms(e),{radius:T}=A,C=LG(A,OFe);return w.createElement("path",VN({},C,{x:Sh(s),y:Sh(o),width:Sh(l),height:Sh(c),radius:typeof d=="number"?d:void 0,className:M,d:OG(s,o,l,c,d)}))}var F=b.current,$=g.current,I=_.current,X=k.current,L="0px ".concat(r===-1?1:r,"px"),te="".concat(r,"px 0px"),ae=Gee(["strokeDasharray"],p,typeof m=="string"?m:IG.animationEasing);return w.createElement(ly,{animationId:N,key:N,canBegin:r>0,duration:p,easing:m,isActive:v,begin:f},ee=>{var me=Er(F,l,ee),le=Er($,c,ee),ue=Er(I,s,ee),K=Er(X,o,ee);n.current&&(b.current=me,g.current=le,_.current=ue,k.current=K);var ne;y?ee>0?ne={transition:ae,strokeDasharray:te}:ne={strokeDasharray:L}:ne={strokeDasharray:te};var oe=ms(e),{radius:be}=oe,_e=LG(oe,IFe);return w.createElement("path",VN({},_e,{radius:typeof d=="number"?d:void 0,className:M,d:OG(ue,K,me,le,d),ref:n,style:RG(RG({},ne),e.style)}))})};function zG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function UG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?zG(Object(n),!0).forEach(function(r){qFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):zG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qFe(t,e,n){return(e=$Fe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $Fe(t){var e=VFe(t,"string");return typeof e=="symbol"?e:e+""}function VFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var GN=Math.PI/180,GFe=t=>t*180/Math.PI,oi=(t,e,n,r)=>({x:t+Math.cos(-GN*r)*n,y:e+Math.sin(-GN*r)*n}),Qee=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},WFe=(t,e)=>{var{x:n,y:r}=t,{x:i,y:s}=e;return Math.sqrt((n-i)**2+(r-s)**2)},KFe=(t,e)=>{var{x:n,y:r}=t,{cx:i,cy:s}=e,o=WFe({x:n,y:r},{x:i,y:s});if(o<=0)return{radius:o,angle:0};var l=(n-i)/o,c=Math.acos(l);return r>s&&(c=2*Math.PI-c),{radius:o,angle:GFe(c),angleInRadian:c}},YFe=t=>{var{startAngle:e,endAngle:n}=t,r=Math.floor(e/360),i=Math.floor(n/360),s=Math.min(r,i);return{startAngle:e-s*360,endAngle:n-s*360}},XFe=(t,e)=>{var{startAngle:n,endAngle:r}=e,i=Math.floor(n/360),s=Math.floor(r/360),o=Math.min(i,s);return t+o*360},QFe=(t,e)=>{var{chartX:n,chartY:r}=t,{radius:i,angle:s}=KFe({x:n,y:r},e),{innerRadius:o,outerRadius:l}=e;if(i<o||i>l||i===0)return null;var{startAngle:c,endAngle:d}=YFe(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?UG(UG({},e),{},{radius:i,angle:XFe(u,e)}):null};function Zee(t){var{cx:e,cy:n,radius:r,startAngle:i,endAngle:s}=t,o=oi(e,n,r,i),l=oi(e,n,r,s);return{points:[o,l],cx:e,cy:n,radius:r,startAngle:i,endAngle:s}}var BG,HG,qG,$G,VG,GG,WG;function TR(){return TR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},TR.apply(null,arguments)}function of(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var ZFe=(t,e)=>{var n=Li(e-t),r=Math.min(Math.abs(e-t),359.999);return n*r},z1=t=>{var{cx:e,cy:n,radius:r,angle:i,sign:s,isExternal:o,cornerRadius:l,cornerIsExternal:c}=t,d=l*(o?1:-1)+r,u=Math.asin(l/d)/GN,m=c?i:i+s*u,p=oi(e,n,d,m),f=oi(e,n,r,m),y=c?i-s*u:i,v=oi(e,n,d*Math.cos(u*GN),y);return{center:p,circleTangency:f,lineTangency:v,theta:u}},Jee=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:i,startAngle:s,endAngle:o}=t,l=ZFe(s,o),c=s+l,d=oi(e,n,i,s),u=oi(e,n,i,c),m=Oa(BG||(BG=of(["M ",",",`
  8105. A `,",",`,0,
  8106. `,",",`,
  8107. `,",",`
  8108. `])),d.x,d.y,i,i,+(Math.abs(l)>180),+(s>c),u.x,u.y);if(r>0){var p=oi(e,n,r,s),f=oi(e,n,r,c);m+=Oa(HG||(HG=of(["L ",",",`
  8109. A `,",",`,0,
  8110. `,",",`,
  8111. `,","," Z"])),f.x,f.y,r,r,+(Math.abs(l)>180),+(s<=c),p.x,p.y)}else m+=Oa(qG||(qG=of(["L ",","," Z"])),e,n);return m},JFe=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:i,cornerRadius:s,forceCornerRadius:o,cornerIsExternal:l,startAngle:c,endAngle:d}=t,u=Li(d-c),{circleTangency:m,lineTangency:p,theta:f}=z1({cx:e,cy:n,radius:i,angle:c,sign:u,cornerRadius:s,cornerIsExternal:l}),{circleTangency:y,lineTangency:v,theta:b}=z1({cx:e,cy:n,radius:i,angle:d,sign:-u,cornerRadius:s,cornerIsExternal:l}),g=l?Math.abs(c-d):Math.abs(c-d)-f-b;if(g<0)return o?Oa($G||($G=of(["M ",",",`
  8112. a`,",",",0,0,1,",`,0
  8113. a`,",",",0,0,1,",`,0
  8114. `])),p.x,p.y,s,s,s*2,s,s,-s*2):Jee({cx:e,cy:n,innerRadius:r,outerRadius:i,startAngle:c,endAngle:d});var _=Oa(VG||(VG=of(["M ",",",`
  8115. A`,",",",0,0,",",",",",`
  8116. A`,",",",0,",",",",",",",`
  8117. A`,",",",0,0,",",",",",`
  8118. `])),p.x,p.y,s,s,+(u<0),m.x,m.y,i,i,+(g>180),+(u<0),y.x,y.y,s,s,+(u<0),v.x,v.y);if(r>0){var{circleTangency:k,lineTangency:P,theta:N}=z1({cx:e,cy:n,radius:r,angle:c,sign:u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:M,lineTangency:A,theta:T}=z1({cx:e,cy:n,radius:r,angle:d,sign:-u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),C=l?Math.abs(c-d):Math.abs(c-d)-N-T;if(C<0&&s===0)return"".concat(_,"L").concat(e,",").concat(n,"Z");_+=Oa(GG||(GG=of(["L",",",`
  8119. A`,",",",0,0,",",",",",`
  8120. A`,",",",0,",",",",",",",`
  8121. A`,",",",0,0,",",",",","Z"])),A.x,A.y,s,s,+(u<0),M.x,M.y,r,r,+(C>180),+(u>0),k.x,k.y,s,s,+(u<0),P.x,P.y)}else _+=Oa(WG||(WG=of(["L",",","Z"])),e,n);return _},eRe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},ete=t=>{var e=Ta(t,eRe),{cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:d,endAngle:u,className:m}=e;if(s<i||d===u)return null;var p=wr("recharts-sector",m),f=s-i,y=Es(o,f,0,!0),v;return y>0&&Math.abs(d-u)<360?v=JFe({cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:Math.min(y,f/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:d,endAngle:u}):v=Jee({cx:n,cy:r,innerRadius:i,outerRadius:s,startAngle:d,endAngle:u}),w.createElement("path",TR({},ms(e),{className:p,d:v}))};function tRe(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(jJ(e)){if(t==="centric"){var{cx:r,cy:i,innerRadius:s,outerRadius:o,angle:l}=e,c=oi(r,i,s,l),d=oi(r,i,o,l);return[{x:c.x,y:c.y},{x:d.x,y:d.y}]}return Zee(e)}}var I2={},z2={},U2={},KG;function nRe(){return KG||(KG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=qJ();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(U2)),U2}var YG;function rRe(){return YG||(YG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=nRe();function n(r){return r?(r=e.toNumber(r),r===1/0||r===-1/0?(r<0?-1:1)*Number.MAX_VALUE:r===r?r:0):r===0?r:0}t.toFinite=n})(z2)),z2}var XG;function aRe(){return XG||(XG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=$J(),n=rRe();function r(i,s,o){o&&typeof o!="number"&&e.isIterateeCall(i,s,o)&&(s=o=void 0),i=n.toFinite(i),s===void 0?(s=i,i=0):s=n.toFinite(s),o=o===void 0?i<s?1:-1:n.toFinite(o);const l=Math.max(Math.ceil((s-i)/(o||1)),0),c=new Array(l);for(let d=0;d<l;d++)c[d]=i,i+=o;return c}t.range=r})(I2)),I2}var B2,QG;function iRe(){return QG||(QG=1,B2=aRe().range),B2}var sRe=iRe();const tte=rc(sRe);function Ih(t,e){return t==null||e==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function oRe(t,e){return t==null||e==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function kI(t){let e,n,r;t.length!==2?(e=Ih,n=(l,c)=>Ih(t(l),c),r=(l,c)=>t(l)-c):(e=t===Ih||t===oRe?t:lRe,n=t,r=t);function i(l,c,d=0,u=l.length){if(d<u){if(e(c,c)!==0)return u;do{const m=d+u>>>1;n(l[m],c)<0?d=m+1:u=m}while(d<u)}return d}function s(l,c,d=0,u=l.length){if(d<u){if(e(c,c)!==0)return u;do{const m=d+u>>>1;n(l[m],c)<=0?d=m+1:u=m}while(d<u)}return d}function o(l,c,d=0,u=l.length){const m=i(l,c,d,u-1);return m>d&&r(l[m-1],c)>-r(l[m],c)?m-1:m}return{left:i,center:o,right:s}}function lRe(){return 0}function nte(t){return t===null?NaN:+t}function*cRe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const dRe=kI(Ih),Qw=dRe.right;kI(nte).center;class ZG extends Map{constructor(e,n=hRe){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,i]of e)this.set(r,i)}get(e){return super.get(JG(this,e))}has(e){return super.has(JG(this,e))}set(e,n){return super.set(uRe(this,e),n)}delete(e){return super.delete(mRe(this,e))}}function JG({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function uRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function mRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function hRe(t){return t!==null&&typeof t=="object"?t.valueOf():t}function pRe(t=Ih){if(t===Ih)return rte;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||r===0?r:(t(n,n)===0)-(t(e,e)===0)}}function rte(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(t<e?-1:t>e?1:0)}const fRe=Math.sqrt(50),gRe=Math.sqrt(10),bRe=Math.sqrt(2);function WN(t,e,n){const r=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=fRe?10:s>=gRe?5:s>=bRe?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?WN(t,e,n*2):[l,c,d]}function AR(t,e,n){if(e=+e,t=+t,n=+n,!(n>0))return[];if(t===e)return[t];const r=e<t,[i,s,o]=r?WN(e,t,n):WN(t,e,n);if(!(s>=i))return[];const l=s-i+1,c=new Array(l);if(r)if(o<0)for(let d=0;d<l;++d)c[d]=(s-d)/-o;else for(let d=0;d<l;++d)c[d]=(s-d)*o;else if(o<0)for(let d=0;d<l;++d)c[d]=(i+d)/-o;else for(let d=0;d<l;++d)c[d]=(i+d)*o;return c}function MR(t,e,n){return e=+e,t=+t,n=+n,WN(t,e,n)[2]}function jR(t,e,n){e=+e,t=+t,n=+n;const r=e<t,i=r?MR(e,t,n):MR(t,e,n);return(r?-1:1)*(i<0?1/-i:i)}function e7(t,e){let n;for(const r of t)r!=null&&(n<r||n===void 0&&r>=r)&&(n=r);return n}function t7(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function ate(t,e,n=0,r=1/0,i){if(e=Math.floor(e),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(t.length-1,r)),!(n<=e&&e<=r))return t;for(i=i===void 0?rte:pRe(i);r>n;){if(r-n>600){const c=r-n+1,d=e-n+1,u=Math.log(c),m=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*m*(c-m)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(e-d*m/c+p)),y=Math.min(r,Math.floor(e+(c-d)*m/c+p));ate(t,e,f,y,i)}const s=t[e];let o=n,l=r;for(Av(t,n,e),i(t[r],s)>0&&Av(t,n,r);o<l;){for(Av(t,o,l),++o,--l;i(t[o],s)<0;)++o;for(;i(t[l],s)>0;)--l}i(t[n],s)===0?Av(t,n,l):(++l,Av(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function Av(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function xRe(t,e,n){if(t=Float64Array.from(cRe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return t7(t);if(e>=1)return e7(t);var r,i=(r-1)*e,s=Math.floor(i),o=e7(ate(t,s).subarray(0,s+1)),l=t7(t.subarray(s+1));return o+(l-o)*(i-s)}}function yRe(t,e,n=nte){if(!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,i=(r-1)*e,s=Math.floor(i),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(i-s)}}function vRe(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(i);++r<i;)s[r]=t+r*n;return s}function ic(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}function lm(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 ER=Symbol("implicit");function NI(){var t=new ZG,e=[],n=[],r=ER;function i(s){let o=t.get(s);if(o===void 0){if(r!==ER)return r;t.set(s,o=e.push(s)-1)}return n[o%n.length]}return i.domain=function(s){if(!arguments.length)return e.slice();e=[],t=new ZG;for(const o of s)t.has(o)||t.set(o,e.push(o)-1);return i},i.range=function(s){return arguments.length?(n=Array.from(s),i):n.slice()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return NI(e,n).unknown(r)},ic.apply(i,arguments),i}function CI(){var t=NI().unknown(void 0),e=t.domain,n=t.range,r=0,i=1,s,o,l=!1,c=0,d=0,u=.5;delete t.unknown;function m(){var p=e().length,f=i<r,y=f?i:r,v=f?r:i;s=(v-y)/Math.max(1,p-c+d*2),l&&(s=Math.floor(s)),y+=(v-y-s*(p-c))*u,o=s*(1-c),l&&(y=Math.round(y),o=Math.round(o));var b=vRe(p).map(function(g){return y+s*g});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?([r,i]=p,r=+r,i=+i,m()):[r,i]},t.rangeRound=function(p){return[r,i]=p,r=+r,i=+i,l=!0,m()},t.bandwidth=function(){return o},t.step=function(){return s},t.round=function(p){return arguments.length?(l=!!p,m()):l},t.padding=function(p){return arguments.length?(c=Math.min(1,d=+p),m()):c},t.paddingInner=function(p){return arguments.length?(c=Math.min(1,p),m()):c},t.paddingOuter=function(p){return arguments.length?(d=+p,m()):d},t.align=function(p){return arguments.length?(u=Math.max(0,Math.min(1,p)),m()):u},t.copy=function(){return CI(e(),[r,i]).round(l).paddingInner(c).paddingOuter(d).align(u)},ic.apply(m(),arguments)}function ite(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return ite(e())},t}function wRe(){return ite(CI.apply(null,arguments).paddingInner(1))}function PI(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function ste(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}function Zw(){}var nw=.7,KN=1/nw,ux="\\s*([+-]?\\d+)\\s*",rw="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Sd="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",SRe=/^#([0-9a-f]{3,8})$/,_Re=new RegExp(`^rgb\\(${ux},${ux},${ux}\\)$`),kRe=new RegExp(`^rgb\\(${Sd},${Sd},${Sd}\\)$`),NRe=new RegExp(`^rgba\\(${ux},${ux},${ux},${rw}\\)$`),CRe=new RegExp(`^rgba\\(${Sd},${Sd},${Sd},${rw}\\)$`),PRe=new RegExp(`^hsl\\(${rw},${Sd},${Sd}\\)$`),TRe=new RegExp(`^hsla\\(${rw},${Sd},${Sd},${rw}\\)$`),n7={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};PI(Zw,aw,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:r7,formatHex:r7,formatHex8:ARe,formatHsl:MRe,formatRgb:a7,toString:a7});function r7(){return this.rgb().formatHex()}function ARe(){return this.rgb().formatHex8()}function MRe(){return ote(this).formatHsl()}function a7(){return this.rgb().formatRgb()}function aw(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=SRe.exec(t))?(n=e[1].length,e=parseInt(e[1],16),n===6?i7(e):n===3?new No(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?U1(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?U1(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=_Re.exec(t))?new No(e[1],e[2],e[3],1):(e=kRe.exec(t))?new No(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=NRe.exec(t))?U1(e[1],e[2],e[3],e[4]):(e=CRe.exec(t))?U1(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=PRe.exec(t))?l7(e[1],e[2]/100,e[3]/100,1):(e=TRe.exec(t))?l7(e[1],e[2]/100,e[3]/100,e[4]):n7.hasOwnProperty(t)?i7(n7[t]):t==="transparent"?new No(NaN,NaN,NaN,0):null}function i7(t){return new No(t>>16&255,t>>8&255,t&255,1)}function U1(t,e,n,r){return r<=0&&(t=e=n=NaN),new No(t,e,n,r)}function jRe(t){return t instanceof Zw||(t=aw(t)),t?(t=t.rgb(),new No(t.r,t.g,t.b,t.opacity)):new No}function DR(t,e,n,r){return arguments.length===1?jRe(t):new No(t,e,n,r??1)}function No(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}PI(No,DR,ste(Zw,{brighter(t){return t=t==null?KN:Math.pow(KN,t),new No(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?nw:Math.pow(nw,t),new No(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new No(Nf(this.r),Nf(this.g),Nf(this.b),YN(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:s7,formatHex:s7,formatHex8:ERe,formatRgb:o7,toString:o7}));function s7(){return`#${lf(this.r)}${lf(this.g)}${lf(this.b)}`}function ERe(){return`#${lf(this.r)}${lf(this.g)}${lf(this.b)}${lf((isNaN(this.opacity)?1:this.opacity)*255)}`}function o7(){const t=YN(this.opacity);return`${t===1?"rgb(":"rgba("}${Nf(this.r)}, ${Nf(this.g)}, ${Nf(this.b)}${t===1?")":`, ${t})`}`}function YN(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Nf(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function lf(t){return t=Nf(t),(t<16?"0":"")+t.toString(16)}function l7(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new kc(t,e,n,r)}function ote(t){if(t instanceof kc)return new kc(t.h,t.s,t.l,t.opacity);if(t instanceof Zw||(t=aw(t)),!t)return new kc;if(t instanceof kc)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-i,c=(s+i)/2;return l?(e===s?o=(n-r)/l+(n<r)*6:n===s?o=(r-e)/l+2:o=(e-n)/l+4,l/=c<.5?s+i:2-s-i,o*=60):l=c>0&&c<1?0:o,new kc(o,l,c,t.opacity)}function DRe(t,e,n,r){return arguments.length===1?ote(t):new kc(t,e,n,r??1)}function kc(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}PI(kc,DRe,ste(Zw,{brighter(t){return t=t==null?KN:Math.pow(KN,t),new kc(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?nw:Math.pow(nw,t),new kc(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new No(H2(t>=240?t-240:t+120,i,r),H2(t,i,r),H2(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new kc(c7(this.h),B1(this.s),B1(this.l),YN(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=YN(this.opacity);return`${t===1?"hsl(":"hsla("}${c7(this.h)}, ${B1(this.s)*100}%, ${B1(this.l)*100}%${t===1?")":`, ${t})`}`}}));function c7(t){return t=(t||0)%360,t<0?t+360:t}function B1(t){return Math.max(0,Math.min(1,t||0))}function H2(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 TI=t=>()=>t;function FRe(t,e){return function(n){return t+n*e}}function RRe(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}function LRe(t){return(t=+t)==1?lte:function(e,n){return n-e?RRe(e,n,t):TI(isNaN(e)?n:e)}}function lte(t,e){var n=e-t;return n?FRe(t,n):TI(isNaN(t)?e:t)}const d7=(function t(e){var n=LRe(e);function r(i,s){var o=n((i=DR(i)).r,(s=DR(s)).r),l=n(i.g,s.g),c=n(i.b,s.b),d=lte(i.opacity,s.opacity);return function(u){return i.r=o(u),i.g=l(u),i.b=c(u),i.opacity=d(u),i+""}}return r.gamma=t,r})(1);function ORe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),i;return function(s){for(i=0;i<n;++i)r[i]=t[i]*(1-s)+e[i]*s;return r}}function IRe(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function zRe(t,e){var n=e?e.length:0,r=t?Math.min(n,t.length):0,i=new Array(r),s=new Array(n),o;for(o=0;o<r;++o)i[o]=dy(t[o],e[o]);for(;o<n;++o)s[o]=e[o];return function(l){for(o=0;o<r;++o)s[o]=i[o](l);return s}}function URe(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}function XN(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}function BRe(t,e){var n={},r={},i;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(i in e)i in t?n[i]=dy(t[i],e[i]):r[i]=e[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var FR=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,q2=new RegExp(FR.source,"g");function HRe(t){return function(){return t}}function qRe(t){return function(e){return t(e)+""}}function $Re(t,e){var n=FR.lastIndex=q2.lastIndex=0,r,i,s,o=-1,l=[],c=[];for(t=t+"",e=e+"";(r=FR.exec(t))&&(i=q2.exec(e));)(s=i.index)>n&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(i=i[0])?l[o]?l[o]+=i:l[++o]=i:(l[++o]=null,c.push({i:o,x:XN(r,i)})),n=q2.lastIndex;return n<e.length&&(s=e.slice(n),l[o]?l[o]+=s:l[++o]=s),l.length<2?c[0]?qRe(c[0].x):HRe(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 dy(t,e){var n=typeof e,r;return e==null||n==="boolean"?TI(e):(n==="number"?XN:n==="string"?(r=aw(e))?(e=r,d7):$Re:e instanceof aw?d7:e instanceof Date?URe:IRe(e)?ORe:Array.isArray(e)?zRe:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?BRe:XN)(t,e)}function AI(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}function VRe(t,e){e===void 0&&(e=t,t=dy);for(var n=0,r=e.length-1,i=e[0],s=new Array(r<0?0:r);n<r;)s[n]=t(i,i=e[++n]);return function(o){var l=Math.max(0,Math.min(r-1,Math.floor(o*=r)));return s[l](o-l)}}function GRe(t){return function(){return t}}function QN(t){return+t}var u7=[0,1];function Ys(t){return t}function RR(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:GRe(isNaN(e)?NaN:.5)}function WRe(t,e){var n;return t>e&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function KRe(t,e,n){var r=t[0],i=t[1],s=e[0],o=e[1];return i<r?(r=RR(i,r),s=n(o,s)):(r=RR(r,i),s=n(s,o)),function(l){return s(r(l))}}function YRe(t,e,n){var r=Math.min(t.length,e.length)-1,i=new Array(r),s=new Array(r),o=-1;for(t[r]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<r;)i[o]=RR(t[o],t[o+1]),s[o]=n(e[o],e[o+1]);return function(l){var c=Qw(t,l,1,r)-1;return s[c](i[c](l))}}function Jw(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function sT(){var t=u7,e=u7,n=dy,r,i,s,o=Ys,l,c,d;function u(){var p=Math.min(t.length,e.length);return o!==Ys&&(o=WRe(t[0],t[p-1])),l=p>2?YRe:KRe,c=d=null,m}function m(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return m.invert=function(p){return o(i((d||(d=l(e,t.map(r),XN)))(p)))},m.domain=function(p){return arguments.length?(t=Array.from(p,QN),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=AI,u()},m.clamp=function(p){return arguments.length?(o=p?!0:Ys,u()):o!==Ys},m.interpolate=function(p){return arguments.length?(n=p,u()):n},m.unknown=function(p){return arguments.length?(s=p,m):s},function(p,f){return r=p,i=f,u()}}function MI(){return sT()(Ys,Ys)}function XRe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function ZN(t,e){if(!isFinite(t)||t===0)return null;var n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function Rx(t){return t=ZN(Math.abs(t)),t?t[1]:NaN}function QRe(t,e){return function(n,r){for(var i=n.length,s=[],o=0,l=t[0],c=0;i>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(i-=l,i+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function ZRe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var JRe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function iw(t){if(!(e=JRe.exec(t)))throw new Error("invalid format: "+t);var e;return new jI({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]})}iw.prototype=jI.prototype;function jI(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+""}jI.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 eLe(t){e:for(var e=t.length,n=1,r=-1,i;n<e;++n)switch(t[n]){case".":r=i=n;break;case"0":r===0&&(r=n),i=n;break;default:if(!+t[n])break e;r>0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(i+1):t}var JN;function tLe(t,e){var n=ZN(t,e);if(!n)return JN=void 0,t.toPrecision(e);var r=n[0],i=n[1],s=i-(JN=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=r.length;return s===o?r:s>o?r+new Array(s-o+1).join("0"):s>0?r.slice(0,s)+"."+r.slice(s):"0."+new Array(1-s).join("0")+ZN(t,Math.max(0,e+s-1))[0]}function m7(t,e){var n=ZN(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}const h7={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:XRe,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)=>m7(t*100,e),r:m7,s:tLe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function p7(t){return t}var f7=Array.prototype.map,g7=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function nLe(t){var e=t.grouping===void 0||t.thousands===void 0?p7:QRe(f7.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?p7:ZRe(f7.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=iw(m);var f=m.fill,y=m.align,v=m.sign,b=m.symbol,g=m.zero,_=m.width,k=m.comma,P=m.precision,N=m.trim,M=m.type;M==="n"?(k=!0,M="g"):h7[M]||(P===void 0&&(P=12),N=!0,M="g"),(g||f==="0"&&y==="=")&&(g=!0,f="0",y="=");var A=(p&&p.prefix!==void 0?p.prefix:"")+(b==="$"?n:b==="#"&&/[boxX]/.test(M)?"0"+M.toLowerCase():""),T=(b==="$"?r:/[%p]/.test(M)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),C=h7[M],F=/[defgprs%]/.test(M);P=P===void 0?6:/[gprs]/.test(M)?Math.max(1,Math.min(21,P)):Math.max(0,Math.min(20,P));function $(I){var X=A,L=T,te,ae,ee;if(M==="c")L=C(I)+L,I="";else{I=+I;var me=I<0||1/I<0;if(I=isNaN(I)?c:C(Math.abs(I),P),N&&(I=eLe(I)),me&&+I==0&&v!=="+"&&(me=!1),X=(me?v==="("?v:l:v==="-"||v==="("?"":v)+X,L=(M==="s"&&!isNaN(I)&&JN!==void 0?g7[8+JN/3]:"")+L+(me&&v==="("?")":""),F){for(te=-1,ae=I.length;++te<ae;)if(ee=I.charCodeAt(te),48>ee||ee>57){L=(ee===46?i+I.slice(te+1):I.slice(te))+L,I=I.slice(0,te);break}}}k&&!g&&(I=e(I,1/0));var le=X.length+I.length+L.length,ue=le<_?new Array(_-le+1).join(f):"";switch(k&&g&&(I=e(ue+I,ue.length?_-L.length:1/0),ue=""),y){case"<":I=X+I+L+ue;break;case"=":I=X+ue+I+L;break;case"^":I=ue.slice(0,le=ue.length>>1)+X+I+L+ue.slice(le);break;default:I=ue+X+I+L;break}return s(I)}return $.toString=function(){return m+""},$}function u(m,p){var f=Math.max(-8,Math.min(8,Math.floor(Rx(p)/3)))*3,y=Math.pow(10,-f),v=d((m=iw(m),m.type="f",m),{suffix:g7[8+f/3]});return function(b){return v(y*b)}}return{format:d,formatPrefix:u}}var H1,EI,cte;rLe({thousands:",",grouping:[3],currency:["$",""]});function rLe(t){return H1=nLe(t),EI=H1.format,cte=H1.formatPrefix,H1}function aLe(t){return Math.max(0,-Rx(Math.abs(t)))}function iLe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Rx(e)/3)))*3-Rx(Math.abs(t)))}function sLe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Rx(e)-Rx(t))+1}function dte(t,e,n,r){var i=jR(t,e,n),s;switch(r=iw(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=iLe(i,o))&&(r.precision=s),cte(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=sLe(i,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=aLe(i))&&(r.precision=s-(r.type==="%")*2);break}}return EI(r)}function ap(t){var e=t.domain;return t.ticks=function(n){var r=e();return AR(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var i=e();return dte(i[0],i[i.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),i=0,s=r.length-1,o=r[i],l=r[s],c,d,u=10;for(l<o&&(d=o,o=l,l=d,d=i,i=s,s=d);u-- >0;){if(d=MR(o,l,n),d===c)return r[i]=o,r[s]=l,e(r);if(d>0)o=Math.floor(o/d)*d,l=Math.ceil(l/d)*d;else if(d<0)o=Math.ceil(o*d)/d,l=Math.floor(l*d)/d;else break;c=d}return t},t}function ute(){var t=MI();return t.copy=function(){return Jw(t,ute())},ic.apply(t,arguments),ap(t)}function mte(t){var e;function n(r){return r==null||isNaN(r=+r)?e:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(t=Array.from(r,QN),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return mte(t).unknown(e)},t=arguments.length?Array.from(t,QN):[0,1],ap(n)}function hte(t,e){t=t.slice();var n=0,r=t.length-1,i=t[n],s=t[r],o;return s<i&&(o=n,n=r,r=o,o=i,i=s,s=o),t[n]=e.floor(i),t[r]=e.ceil(s),t}function b7(t){return Math.log(t)}function x7(t){return Math.exp(t)}function oLe(t){return-Math.log(-t)}function lLe(t){return-Math.exp(-t)}function cLe(t){return isFinite(t)?+("1e"+t):t<0?0:t}function dLe(t){return t===10?cLe:t===Math.E?Math.exp:e=>Math.pow(t,e)}function uLe(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 y7(t){return(e,n)=>-t(-e,n)}function DI(t){const e=t(b7,x7),n=e.domain;let r=10,i,s;function o(){return i=uLe(r),s=dLe(r),n()[0]<0?(i=y7(i),s=y7(s),t(oLe,lLe)):t(b7,x7),e}return e.base=function(l){return arguments.length?(r=+l,o()):r},e.domain=function(l){return arguments.length?(n(l),o()):n()},e.ticks=l=>{const c=n();let d=c[0],u=c[c.length-1];const m=u<d;m&&([d,u]=[u,d]);let p=i(d),f=i(u),y,v;const b=l==null?10:+l;let g=[];if(!(r%1)&&f-p<b){if(p=Math.floor(p),f=Math.ceil(f),d>0){for(;p<=f;++p)for(y=1;y<r;++y)if(v=p<0?y/s(-p):y*s(p),!(v<d)){if(v>u)break;g.push(v)}}else for(;p<=f;++p)for(y=r-1;y>=1;--y)if(v=p>0?y/s(-p):y*s(p),!(v<d)){if(v>u)break;g.push(v)}g.length*2<b&&(g=AR(d,u,b))}else g=AR(p,f,Math.min(f-p,b)).map(s);return m?g.reverse():g},e.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=iw(c)).precision==null&&(c.trim=!0),c=EI(c)),l===1/0)return c;const d=Math.max(1,r*l/e.ticks().length);return u=>{let m=u/s(Math.round(i(u)));return m*r<r-.5&&(m*=r),m<=d?c(u):""}},e.nice=()=>n(hte(n(),{floor:l=>s(Math.floor(i(l))),ceil:l=>s(Math.ceil(i(l)))})),e}function pte(){const t=DI(sT()).domain([1,10]);return t.copy=()=>Jw(t,pte()).base(t.base()),ic.apply(t,arguments),t}function v7(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function w7(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function FI(t){var e=1,n=t(v7(e),w7(e));return n.constant=function(r){return arguments.length?t(v7(e=+r),w7(e)):e},ap(n)}function fte(){var t=FI(sT());return t.copy=function(){return Jw(t,fte()).constant(t.constant())},ic.apply(t,arguments)}function S7(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function mLe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function hLe(t){return t<0?-t*t:t*t}function RI(t){var e=t(Ys,Ys),n=1;function r(){return n===1?t(Ys,Ys):n===.5?t(mLe,hLe):t(S7(n),S7(1/n))}return e.exponent=function(i){return arguments.length?(n=+i,r()):n},ap(e)}function LI(){var t=RI(sT());return t.copy=function(){return Jw(t,LI()).exponent(t.exponent())},ic.apply(t,arguments),t}function pLe(){return LI.apply(null,arguments).exponent(.5)}function _7(t){return Math.sign(t)*t*t}function fLe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function gte(){var t=MI(),e=[0,1],n=!1,r;function i(s){var o=fLe(t(s));return isNaN(o)?r:n?Math.round(o):o}return i.invert=function(s){return t.invert(_7(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,QN)).map(_7)),i):e.slice()},i.rangeRound=function(s){return i.range(s).round(!0)},i.round=function(s){return arguments.length?(n=!!s,i):n},i.clamp=function(s){return arguments.length?(t.clamp(s),i):t.clamp()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return gte(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},ic.apply(i,arguments),ap(i)}function bte(){var t=[],e=[],n=[],r;function i(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o<l;)n[o-1]=yRe(t,o/l);return s}function s(o){return o==null||isNaN(o=+o)?r:e[Qw(n,o)]}return s.invertExtent=function(o){var l=e.indexOf(o);return l<0?[NaN,NaN]:[l>0?n[l-1]:t[0],l<n.length?n[l]:t[t.length-1]]},s.domain=function(o){if(!arguments.length)return t.slice();t=[];for(let l of o)l!=null&&!isNaN(l=+l)&&t.push(l);return t.sort(Ih),i()},s.range=function(o){return arguments.length?(e=Array.from(o),i()):e.slice()},s.unknown=function(o){return arguments.length?(r=o,s):r},s.quantiles=function(){return n.slice()},s.copy=function(){return bte().domain(t).range(e).unknown(r)},ic.apply(s,arguments)}function xte(){var t=0,e=1,n=1,r=[.5],i=[0,1],s;function o(c){return c!=null&&c<=c?i[Qw(r,c,0,n)]:s}function l(){var c=-1;for(r=new Array(n);++c<n;)r[c]=((c+1)*e-(c-n)*t)/(n+1);return o}return o.domain=function(c){return arguments.length?([t,e]=c,t=+t,e=+e,l()):[t,e]},o.range=function(c){return arguments.length?(n=(i=Array.from(c)).length-1,l()):i.slice()},o.invertExtent=function(c){var d=i.indexOf(c);return d<0?[NaN,NaN]:d<1?[t,r[0]]:d>=n?[r[n-1],e]:[r[d-1],r[d]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return xte().domain([t,e]).range(i).unknown(s)},ic.apply(ap(o),arguments)}function yte(){var t=[.5],e=[0,1],n,r=1;function i(s){return s!=null&&s<=s?e[Qw(t,s,0,r)]:n}return i.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},i.unknown=function(s){return arguments.length?(n=s,i):n},i.copy=function(){return yte().domain(t).range(e).unknown(n)},ic.apply(i,arguments)}const $2=new Date,V2=new Date;function _i(t,e,n,r){function i(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return i.floor=s=>(t(s=new Date(+s)),s),i.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),i.round=s=>{const o=i(s),l=i.ceil(s);return s-o<l-s?o:l},i.offset=(s,o)=>(e(s=new Date(+s),o==null?1:Math.floor(o)),s),i.range=(s,o,l)=>{const c=[];if(s=i.ceil(s),l=l==null?1:Math.floor(l),!(s<o)||!(l>0))return c;let d;do c.push(d=new Date(+s)),e(s,l),t(s);while(d<s&&s<o);return c},i.filter=s=>_i(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)=>($2.setTime(+s),V2.setTime(+o),t($2),t(V2),Math.floor(n($2,V2))),i.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?i.filter(r?o=>r(o)%s===0:o=>i.count(0,o)%s===0):i)),i}const eC=_i(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);eC.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?_i(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):eC);eC.range;const Eu=1e3,Hl=Eu*60,Du=Hl*60,Ju=Du*24,OI=Ju*7,k7=Ju*30,G2=Ju*365,cf=_i(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Eu)},(t,e)=>(e-t)/Eu,t=>t.getUTCSeconds());cf.range;const II=_i(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Eu)},(t,e)=>{t.setTime(+t+e*Hl)},(t,e)=>(e-t)/Hl,t=>t.getMinutes());II.range;const zI=_i(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*Hl)},(t,e)=>(e-t)/Hl,t=>t.getUTCMinutes());zI.range;const UI=_i(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Eu-t.getMinutes()*Hl)},(t,e)=>{t.setTime(+t+e*Du)},(t,e)=>(e-t)/Du,t=>t.getHours());UI.range;const BI=_i(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Du)},(t,e)=>(e-t)/Du,t=>t.getUTCHours());BI.range;const eS=_i(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Hl)/Ju,t=>t.getDate()-1);eS.range;const oT=_i(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ju,t=>t.getUTCDate()-1);oT.range;const vte=_i(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ju,t=>Math.floor(t/Ju));vte.range;function mg(t){return _i(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())*Hl)/OI)}const lT=mg(0),tC=mg(1),gLe=mg(2),bLe=mg(3),Lx=mg(4),xLe=mg(5),yLe=mg(6);lT.range;tC.range;gLe.range;bLe.range;Lx.range;xLe.range;yLe.range;function hg(t){return _i(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)/OI)}const cT=hg(0),nC=hg(1),vLe=hg(2),wLe=hg(3),Ox=hg(4),SLe=hg(5),_Le=hg(6);cT.range;nC.range;vLe.range;wLe.range;Ox.range;SLe.range;_Le.range;const HI=_i(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());HI.range;const qI=_i(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());qI.range;const em=_i(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());em.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:_i(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)});em.range;const tm=_i(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());tm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:_i(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)});tm.range;function wte(t,e,n,r,i,s){const o=[[cf,1,Eu],[cf,5,5*Eu],[cf,15,15*Eu],[cf,30,30*Eu],[s,1,Hl],[s,5,5*Hl],[s,15,15*Hl],[s,30,30*Hl],[i,1,Du],[i,3,3*Du],[i,6,6*Du],[i,12,12*Du],[r,1,Ju],[r,2,2*Ju],[n,1,OI],[e,1,k7],[e,3,3*k7],[t,1,G2]];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),y=f?f.range(d,+u+1):[];return p?y.reverse():y}function c(d,u,m){const p=Math.abs(u-d)/m,f=kI(([,,b])=>b).right(o,p);if(f===o.length)return t.every(jR(d/G2,u/G2,m));if(f===0)return eC.every(Math.max(jR(d,u,m),1));const[y,v]=o[p/o[f-1][2]<o[f][2]/p?f-1:f];return y.every(v)}return[l,c]}const[kLe,NLe]=wte(tm,qI,cT,vte,BI,zI),[CLe,PLe]=wte(em,HI,lT,eS,UI,II);function W2(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 K2(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 Mv(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function TLe(t){var e=t.dateTime,n=t.date,r=t.time,i=t.periods,s=t.days,o=t.shortDays,l=t.months,c=t.shortMonths,d=jv(i),u=Ev(i),m=jv(s),p=Ev(s),f=jv(o),y=Ev(o),v=jv(l),b=Ev(l),g=jv(c),_=Ev(c),k={a:ee,A:me,b:le,B:ue,c:null,d:M7,e:M7,f:QLe,g:oOe,G:cOe,H:KLe,I:YLe,j:XLe,L:Ste,m:ZLe,M:JLe,p:K,q:ne,Q:D7,s:F7,S:eOe,u:tOe,U:nOe,V:rOe,w:aOe,W:iOe,x:null,X:null,y:sOe,Y:lOe,Z:dOe,"%":E7},P={a:oe,A:be,b:_e,B,c:null,d:j7,e:j7,f:pOe,g:kOe,G:COe,H:uOe,I:mOe,j:hOe,L:kte,m:fOe,M:gOe,p:Y,q:D,Q:D7,s:F7,S:bOe,u:xOe,U:yOe,V:vOe,w:wOe,W:SOe,x:null,X:null,y:_Oe,Y:NOe,Z:POe,"%":E7},N={a:F,A:$,b:I,B:X,c:L,d:T7,e:T7,f:$Le,g:P7,G:C7,H:A7,I:A7,j:ULe,L:qLe,m:zLe,M:BLe,p:C,q:ILe,Q:GLe,s:WLe,S:HLe,u:DLe,U:FLe,V:RLe,w:ELe,W:LLe,x:te,X:ae,y:P7,Y:C7,Z:OLe,"%":VLe};k.x=M(n,k),k.X=M(r,k),k.c=M(e,k),P.x=M(n,P),P.X=M(r,P),P.c=M(e,P);function M(j,z){return function(W){var q=[],de=-1,O=0,G=j.length,Q,V,J;for(W instanceof Date||(W=new Date(+W));++de<G;)j.charCodeAt(de)===37&&(q.push(j.slice(O,de)),(V=N7[Q=j.charAt(++de)])!=null?Q=j.charAt(++de):V=Q==="e"?" ":"0",(J=z[Q])&&(Q=J(W,V)),q.push(Q),O=de+1);return q.push(j.slice(O,de)),q.join("")}}function A(j,z){return function(W){var q=Mv(1900,void 0,1),de=T(q,j,W+="",0),O,G;if(de!=W.length)return null;if("Q"in q)return new Date(q.Q);if("s"in q)return new Date(q.s*1e3+("L"in q?q.L:0));if(z&&!("Z"in q)&&(q.Z=0),"p"in q&&(q.H=q.H%12+q.p*12),q.m===void 0&&(q.m="q"in q?q.q:0),"V"in q){if(q.V<1||q.V>53)return null;"w"in q||(q.w=1),"Z"in q?(O=K2(Mv(q.y,0,1)),G=O.getUTCDay(),O=G>4||G===0?nC.ceil(O):nC(O),O=oT.offset(O,(q.V-1)*7),q.y=O.getUTCFullYear(),q.m=O.getUTCMonth(),q.d=O.getUTCDate()+(q.w+6)%7):(O=W2(Mv(q.y,0,1)),G=O.getDay(),O=G>4||G===0?tC.ceil(O):tC(O),O=eS.offset(O,(q.V-1)*7),q.y=O.getFullYear(),q.m=O.getMonth(),q.d=O.getDate()+(q.w+6)%7)}else("W"in q||"U"in q)&&("w"in q||(q.w="u"in q?q.u%7:"W"in q?1:0),G="Z"in q?K2(Mv(q.y,0,1)).getUTCDay():W2(Mv(q.y,0,1)).getDay(),q.m=0,q.d="W"in q?(q.w+6)%7+q.W*7-(G+5)%7:q.w+q.U*7-(G+6)%7);return"Z"in q?(q.H+=q.Z/100|0,q.M+=q.Z%100,K2(q)):W2(q)}}function T(j,z,W,q){for(var de=0,O=z.length,G=W.length,Q,V;de<O;){if(q>=G)return-1;if(Q=z.charCodeAt(de++),Q===37){if(Q=z.charAt(de++),V=N[Q in N7?z.charAt(de++):Q],!V||(q=V(j,W,q))<0)return-1}else if(Q!=W.charCodeAt(q++))return-1}return q}function C(j,z,W){var q=d.exec(z.slice(W));return q?(j.p=u.get(q[0].toLowerCase()),W+q[0].length):-1}function F(j,z,W){var q=f.exec(z.slice(W));return q?(j.w=y.get(q[0].toLowerCase()),W+q[0].length):-1}function $(j,z,W){var q=m.exec(z.slice(W));return q?(j.w=p.get(q[0].toLowerCase()),W+q[0].length):-1}function I(j,z,W){var q=g.exec(z.slice(W));return q?(j.m=_.get(q[0].toLowerCase()),W+q[0].length):-1}function X(j,z,W){var q=v.exec(z.slice(W));return q?(j.m=b.get(q[0].toLowerCase()),W+q[0].length):-1}function L(j,z,W){return T(j,e,z,W)}function te(j,z,W){return T(j,n,z,W)}function ae(j,z,W){return T(j,r,z,W)}function ee(j){return o[j.getDay()]}function me(j){return s[j.getDay()]}function le(j){return c[j.getMonth()]}function ue(j){return l[j.getMonth()]}function K(j){return i[+(j.getHours()>=12)]}function ne(j){return 1+~~(j.getMonth()/3)}function oe(j){return o[j.getUTCDay()]}function be(j){return s[j.getUTCDay()]}function _e(j){return c[j.getUTCMonth()]}function B(j){return l[j.getUTCMonth()]}function Y(j){return i[+(j.getUTCHours()>=12)]}function D(j){return 1+~~(j.getUTCMonth()/3)}return{format:function(j){var z=M(j+="",k);return z.toString=function(){return j},z},parse:function(j){var z=A(j+="",!1);return z.toString=function(){return j},z},utcFormat:function(j){var z=M(j+="",P);return z.toString=function(){return j},z},utcParse:function(j){var z=A(j+="",!0);return z.toString=function(){return j},z}}}var N7={"-":"",_:" ",0:"0"},zi=/^\s*\d+/,ALe=/^%/,MLe=/[\\^$*+?|[\]().{}]/g;function Tr(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",s=i.length;return r+(s<n?new Array(n-s+1).join(e)+i:i)}function jLe(t){return t.replace(MLe,"\\$&")}function jv(t){return new RegExp("^(?:"+t.map(jLe).join("|")+")","i")}function Ev(t){return new Map(t.map((e,n)=>[e.toLowerCase(),n]))}function ELe(t,e,n){var r=zi.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function DLe(t,e,n){var r=zi.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function FLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function RLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function LLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function C7(t,e,n){var r=zi.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function P7(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function OLe(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function ILe(t,e,n){var r=zi.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function zLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function T7(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function ULe(t,e,n){var r=zi.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function A7(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function BLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function HLe(t,e,n){var r=zi.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function qLe(t,e,n){var r=zi.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function $Le(t,e,n){var r=zi.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function VLe(t,e,n){var r=ALe.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function GLe(t,e,n){var r=zi.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function WLe(t,e,n){var r=zi.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function M7(t,e){return Tr(t.getDate(),e,2)}function KLe(t,e){return Tr(t.getHours(),e,2)}function YLe(t,e){return Tr(t.getHours()%12||12,e,2)}function XLe(t,e){return Tr(1+eS.count(em(t),t),e,3)}function Ste(t,e){return Tr(t.getMilliseconds(),e,3)}function QLe(t,e){return Ste(t,e)+"000"}function ZLe(t,e){return Tr(t.getMonth()+1,e,2)}function JLe(t,e){return Tr(t.getMinutes(),e,2)}function eOe(t,e){return Tr(t.getSeconds(),e,2)}function tOe(t){var e=t.getDay();return e===0?7:e}function nOe(t,e){return Tr(lT.count(em(t)-1,t),e,2)}function _te(t){var e=t.getDay();return e>=4||e===0?Lx(t):Lx.ceil(t)}function rOe(t,e){return t=_te(t),Tr(Lx.count(em(t),t)+(em(t).getDay()===4),e,2)}function aOe(t){return t.getDay()}function iOe(t,e){return Tr(tC.count(em(t)-1,t),e,2)}function sOe(t,e){return Tr(t.getFullYear()%100,e,2)}function oOe(t,e){return t=_te(t),Tr(t.getFullYear()%100,e,2)}function lOe(t,e){return Tr(t.getFullYear()%1e4,e,4)}function cOe(t,e){var n=t.getDay();return t=n>=4||n===0?Lx(t):Lx.ceil(t),Tr(t.getFullYear()%1e4,e,4)}function dOe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Tr(e/60|0,"0",2)+Tr(e%60,"0",2)}function j7(t,e){return Tr(t.getUTCDate(),e,2)}function uOe(t,e){return Tr(t.getUTCHours(),e,2)}function mOe(t,e){return Tr(t.getUTCHours()%12||12,e,2)}function hOe(t,e){return Tr(1+oT.count(tm(t),t),e,3)}function kte(t,e){return Tr(t.getUTCMilliseconds(),e,3)}function pOe(t,e){return kte(t,e)+"000"}function fOe(t,e){return Tr(t.getUTCMonth()+1,e,2)}function gOe(t,e){return Tr(t.getUTCMinutes(),e,2)}function bOe(t,e){return Tr(t.getUTCSeconds(),e,2)}function xOe(t){var e=t.getUTCDay();return e===0?7:e}function yOe(t,e){return Tr(cT.count(tm(t)-1,t),e,2)}function Nte(t){var e=t.getUTCDay();return e>=4||e===0?Ox(t):Ox.ceil(t)}function vOe(t,e){return t=Nte(t),Tr(Ox.count(tm(t),t)+(tm(t).getUTCDay()===4),e,2)}function wOe(t){return t.getUTCDay()}function SOe(t,e){return Tr(nC.count(tm(t)-1,t),e,2)}function _Oe(t,e){return Tr(t.getUTCFullYear()%100,e,2)}function kOe(t,e){return t=Nte(t),Tr(t.getUTCFullYear()%100,e,2)}function NOe(t,e){return Tr(t.getUTCFullYear()%1e4,e,4)}function COe(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Ox(t):Ox.ceil(t),Tr(t.getUTCFullYear()%1e4,e,4)}function POe(){return"+0000"}function E7(){return"%"}function D7(t){return+t}function F7(t){return Math.floor(+t/1e3)}var jb,Cte,Pte;TOe({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 TOe(t){return jb=TLe(t),Cte=jb.format,jb.parse,Pte=jb.utcFormat,jb.utcParse,jb}function AOe(t){return new Date(t)}function MOe(t){return t instanceof Date?+t:+new Date(+t)}function $I(t,e,n,r,i,s,o,l,c,d){var u=MI(),m=u.invert,p=u.domain,f=d(".%L"),y=d(":%S"),v=d("%I:%M"),b=d("%I %p"),g=d("%a %d"),_=d("%b %d"),k=d("%B"),P=d("%Y");function N(M){return(c(M)<M?f:l(M)<M?y:o(M)<M?v:s(M)<M?b:r(M)<M?i(M)<M?g:_:n(M)<M?k:P)(M)}return u.invert=function(M){return new Date(m(M))},u.domain=function(M){return arguments.length?p(Array.from(M,MOe)):p().map(AOe)},u.ticks=function(M){var A=p();return t(A[0],A[A.length-1],M??10)},u.tickFormat=function(M,A){return A==null?N:d(A)},u.nice=function(M){var A=p();return(!M||typeof M.range!="function")&&(M=e(A[0],A[A.length-1],M??10)),M?p(hte(A,M)):u},u.copy=function(){return Jw(u,$I(t,e,n,r,i,s,o,l,c,d))},u}function jOe(){return ic.apply($I(CLe,PLe,em,HI,lT,eS,UI,II,cf,Cte).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function EOe(){return ic.apply($I(kLe,NLe,tm,qI,cT,oT,BI,zI,cf,Pte).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function dT(){var t=0,e=1,n,r,i,s,o=Ys,l=!1,c;function d(m){return m==null||isNaN(m=+m)?c:o(i===0?.5:(m=(s(m)-n)*i,l?Math.max(0,Math.min(1,m)):m))}d.domain=function(m){return arguments.length?([t,e]=m,n=s(t=+t),r=s(e=+e),i=n===r?0:1/(r-n),d):[t,e]},d.clamp=function(m){return arguments.length?(l=!!m,d):l},d.interpolator=function(m){return arguments.length?(o=m,d):o};function u(m){return function(p){var f,y;return arguments.length?([f,y]=p,o=m(f,y),d):[o(0),o(1)]}}return d.range=u(dy),d.rangeRound=u(AI),d.unknown=function(m){return arguments.length?(c=m,d):c},function(m){return s=m,n=m(t),r=m(e),i=n===r?0:1/(r-n),d}}function ip(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function Tte(){var t=ap(dT()(Ys));return t.copy=function(){return ip(t,Tte())},lm.apply(t,arguments)}function Ate(){var t=DI(dT()).domain([1,10]);return t.copy=function(){return ip(t,Ate()).base(t.base())},lm.apply(t,arguments)}function Mte(){var t=FI(dT());return t.copy=function(){return ip(t,Mte()).constant(t.constant())},lm.apply(t,arguments)}function VI(){var t=RI(dT());return t.copy=function(){return ip(t,VI()).exponent(t.exponent())},lm.apply(t,arguments)}function DOe(){return VI.apply(null,arguments).exponent(.5)}function jte(){var t=[],e=Ys;function n(r){if(r!=null&&!isNaN(r=+r))return e((Qw(t,r,1)-1)/(t.length-1))}return n.domain=function(r){if(!arguments.length)return t.slice();t=[];for(let i of r)i!=null&&!isNaN(i=+i)&&t.push(i);return t.sort(Ih),n},n.interpolator=function(r){return arguments.length?(e=r,n):e},n.range=function(){return t.map((r,i)=>e(i/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(i,s)=>xRe(t,s/r))},n.copy=function(){return jte(e).domain(t)},lm.apply(n,arguments)}function uT(){var t=0,e=.5,n=1,r=1,i,s,o,l,c,d=Ys,u,m=!1,p;function f(v){return isNaN(v=+v)?p:(v=.5+((v=+u(v))-s)*(r*v<r*s?l:c),d(m?Math.max(0,Math.min(1,v)):v))}f.domain=function(v){return arguments.length?([t,e,n]=v,i=u(t=+t),s=u(e=+e),o=u(n=+n),l=i===s?0:.5/(s-i),c=s===o?0:.5/(o-s),r=s<i?-1:1,f):[t,e,n]},f.clamp=function(v){return arguments.length?(m=!!v,f):m},f.interpolator=function(v){return arguments.length?(d=v,f):d};function y(v){return function(b){var g,_,k;return arguments.length?([g,_,k]=b,d=VRe(v,[g,_,k]),f):[d(0),d(.5),d(1)]}}return f.range=y(dy),f.rangeRound=y(AI),f.unknown=function(v){return arguments.length?(p=v,f):p},function(v){return u=v,i=v(t),s=v(e),o=v(n),l=i===s?0:.5/(s-i),c=s===o?0:.5/(o-s),r=s<i?-1:1,f}}function Ete(){var t=ap(uT()(Ys));return t.copy=function(){return ip(t,Ete())},lm.apply(t,arguments)}function Dte(){var t=DI(uT()).domain([.1,1,10]);return t.copy=function(){return ip(t,Dte()).base(t.base())},lm.apply(t,arguments)}function Fte(){var t=FI(uT());return t.copy=function(){return ip(t,Fte()).constant(t.constant())},lm.apply(t,arguments)}function GI(){var t=RI(uT());return t.copy=function(){return ip(t,GI()).exponent(t.exponent())},lm.apply(t,arguments)}function FOe(){return GI.apply(null,arguments).exponent(.5)}const Kv=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:CI,scaleDiverging:Ete,scaleDivergingLog:Dte,scaleDivergingPow:GI,scaleDivergingSqrt:FOe,scaleDivergingSymlog:Fte,scaleIdentity:mte,scaleImplicit:ER,scaleLinear:ute,scaleLog:pte,scaleOrdinal:NI,scalePoint:wRe,scalePow:LI,scaleQuantile:bte,scaleQuantize:xte,scaleRadial:gte,scaleSequential:Tte,scaleSequentialLog:Ate,scaleSequentialPow:VI,scaleSequentialQuantile:jte,scaleSequentialSqrt:DOe,scaleSequentialSymlog:Mte,scaleSqrt:pLe,scaleSymlog:fte,scaleThreshold:yte,scaleTime:jOe,scaleUtc:EOe,tickFormat:dte},Symbol.toStringTag,{value:"Module"}));var cm=t=>t.chartData,mT=yt([cm],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),WI=(t,e,n,r)=>r?mT(t):cm(t),Rte=(t,e,n)=>n?mT(t):cm(t);function nm(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(qn(e)&&qn(n))return!0}return!1}function R7(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function Lte(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,i,s;if(qn(n))i=n;else if(typeof n=="function")return;if(qn(r))s=r;else if(typeof r=="function")return;var o=[i,s];if(nm(o))return o}}function ROe(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(nm(r))return R7(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[i,s]=t,o,l;if(i==="auto")e!=null&&(o=Math.min(...e));else if(on(i))o=i;else if(typeof i=="function")try{e!=null&&(o=i(e?.[0]))}catch{}else if(typeof i=="string"&&VV.test(i)){var c=VV.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(on(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&GV.test(s)){var u=GV.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(nm(p))return e==null?p:R7(p,e,n)}}}var uy=1e9,LOe={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},YI,xa=!0,tc="[DecimalError] ",Cf=tc+"Invalid argument: ",KI=tc+"Exponent out of range: ",my=Math.floor,Xp=Math.pow,OOe=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Jo,Di=1e7,ha=7,Ote=9007199254740991,rC=my(Ote/ha),hn={};hn.absoluteValue=hn.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};hn.comparedTo=hn.cmp=function(t){var e,n,r,i,s=this;if(t=new s.constructor(t),s.s!==t.s)return s.s||-t.s;if(s.e!==t.e)return s.e>t.e^s.s<0?1:-1;for(r=s.d.length,i=t.d.length,e=0,n=r<i?r:i;e<n;++e)if(s.d[e]!==t.d[e])return s.d[e]>t.d[e]^s.s<0?1:-1;return r===i?0:r>i^s.s<0?1:-1};hn.decimalPlaces=hn.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*ha;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};hn.dividedBy=hn.div=function(t){return Uu(this,new this.constructor(t))};hn.dividedToIntegerBy=hn.idiv=function(t){var e=this,n=e.constructor;return Jr(Uu(e,new n(t),0,1),n.precision)};hn.equals=hn.eq=function(t){return!this.cmp(t)};hn.exponent=function(){return di(this)};hn.greaterThan=hn.gt=function(t){return this.cmp(t)>0};hn.greaterThanOrEqualTo=hn.gte=function(t){return this.cmp(t)>=0};hn.isInteger=hn.isint=function(){return this.e>this.d.length-2};hn.isNegative=hn.isneg=function(){return this.s<0};hn.isPositive=hn.ispos=function(){return this.s>0};hn.isZero=function(){return this.s===0};hn.lessThan=hn.lt=function(t){return this.cmp(t)<0};hn.lessThanOrEqualTo=hn.lte=function(t){return this.cmp(t)<1};hn.logarithm=hn.log=function(t){var e,n=this,r=n.constructor,i=r.precision,s=i+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(Jo))throw Error(tc+"NaN");if(n.s<1)throw Error(tc+(n.s?"NaN":"-Infinity"));return n.eq(Jo)?new r(0):(xa=!1,e=Uu(sw(n,s),sw(t,s),s),xa=!0,Jr(e,i))};hn.minus=hn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?Ute(e,t):Ite(e,(t.s=-t.s,t))};hn.modulo=hn.mod=function(t){var e,n=this,r=n.constructor,i=r.precision;if(t=new r(t),!t.s)throw Error(tc+"NaN");return n.s?(xa=!1,e=Uu(n,t,0,1).times(t),xa=!0,n.minus(e)):Jr(new r(n),i)};hn.naturalExponential=hn.exp=function(){return zte(this)};hn.naturalLogarithm=hn.ln=function(){return sw(this)};hn.negated=hn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};hn.plus=hn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?Ite(e,t):Ute(e,(t.s=-t.s,t))};hn.precision=hn.sd=function(t){var e,n,r,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Cf+t);if(e=di(i)+1,r=i.d.length-1,n=r*ha+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};hn.squareRoot=hn.sqrt=function(){var t,e,n,r,i,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(tc+"NaN")}for(t=di(l),xa=!1,i=Math.sqrt(+l),i==0||i==1/0?(e=bd(l.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=my((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(i.toString()),n=c.precision,i=o=n+3;;)if(s=r,r=s.plus(Uu(l,s,o+2)).times(.5),bd(s.d).slice(0,o)===(e=bd(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),i==o&&e=="4999"){if(Jr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return xa=!0,Jr(r,n)};hn.times=hn.mul=function(t){var e,n,r,i,s,o,l,c,d,u=this,m=u.constructor,p=u.d,f=(t=new m(t)).d;if(!u.s||!t.s)return new m(0);for(t.s*=u.s,n=u.e+t.e,c=p.length,d=f.length,c<d&&(s=p,p=f,f=s,o=c,c=d,d=o),s=[],o=c+d,r=o;r--;)s.push(0);for(r=d;--r>=0;){for(e=0,i=c+r;i>r;)l=s[i]+f[r]*p[i-r-1]+e,s[i--]=l%Di|0,e=l/Di|0;s[i]=(s[i]+e)%Di|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,xa?Jr(t,m.precision):t};hn.toDecimalPlaces=hn.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(Td(t,0,uy),e===void 0?e=r.rounding:Td(e,0,8),Jr(n,t+di(n)+1,e))};hn.toExponential=function(t,e){var n,r=this,i=r.constructor;return t===void 0?n=eg(r,!0):(Td(t,0,uy),e===void 0?e=i.rounding:Td(e,0,8),r=Jr(new i(r),t+1,e),n=eg(r,!0,t+1)),n};hn.toFixed=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?eg(i):(Td(t,0,uy),e===void 0?e=s.rounding:Td(e,0,8),r=Jr(new s(i),t+di(i)+1,e),n=eg(r.abs(),!1,t+di(r)+1),i.isneg()&&!i.isZero()?"-"+n:n)};hn.toInteger=hn.toint=function(){var t=this,e=t.constructor;return Jr(new e(t),di(t)+1,e.rounding)};hn.toNumber=function(){return+this};hn.toPower=hn.pow=function(t){var e,n,r,i,s,o,l=this,c=l.constructor,d=12,u=+(t=new c(t));if(!t.s)return new c(Jo);if(l=new c(l),!l.s){if(t.s<1)throw Error(tc+"Infinity");return l}if(l.eq(Jo))return l;if(r=c.precision,t.eq(Jo))return Jr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=u<0?-u:u)<=Ote){for(i=new c(Jo),e=Math.ceil(r/ha+4),xa=!1;n%2&&(i=i.times(l),O7(i.d,e)),n=my(n/2),n!==0;)l=l.times(l),O7(l.d,e);return xa=!0,t.s<0?new c(Jo).div(i):Jr(i,r)}}else if(s<0)throw Error(tc+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,xa=!1,i=t.times(sw(l,r+d)),xa=!0,i=zte(i),i.s=s,i};hn.toPrecision=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?(n=di(i),r=eg(i,n<=s.toExpNeg||n>=s.toExpPos)):(Td(t,1,uy),e===void 0?e=s.rounding:Td(e,0,8),i=Jr(new s(i),t,e),n=di(i),r=eg(i,t<=n||n<=s.toExpNeg,t)),r};hn.toSignificantDigits=hn.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(Td(t,1,uy),e===void 0?e=r.rounding:Td(e,0,8)),Jr(new r(n),t,e)};hn.toString=hn.valueOf=hn.val=hn.toJSON=hn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=di(t),n=t.constructor;return eg(t,e<=n.toExpNeg||e>=n.toExpPos)};function Ite(t,e){var n,r,i,s,o,l,c,d,u=t.constructor,m=u.precision;if(!t.s||!e.s)return e.s||(e=new u(t)),xa?Jr(e,m):e;if(c=t.d,d=e.d,o=t.e,i=e.e,c=c.slice(),s=o-i,s){for(s<0?(r=c,s=-s,l=d.length):(r=d,i=o,l=c.length),o=Math.ceil(m/ha),l=o>l?o+1:l+1,s>l&&(s=l,r.length=1),r.reverse();s--;)r.push(0);r.reverse()}for(l=c.length,s=d.length,l-s<0&&(s=l,r=d,d=c,c=r),n=0;s;)n=(c[--s]=c[s]+d[s]+n)/Di|0,c[s]%=Di;for(n&&(c.unshift(n),++i),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=i,xa?Jr(e,m):e}function Td(t,e,n){if(t!==~~t||t<e||t>n)throw Error(Cf+t)}function bd(t){var e,n,r,i=t.length-1,s="",o=t[0];if(i>0){for(s+=o,e=1;e<i;e++)r=t[e]+"",n=ha-r.length,n&&(s+=ih(n)),s+=r;o=t[e],r=o+"",n=ha-r.length,n&&(s+=ih(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}var Uu=(function(){function t(r,i){var s,o=0,l=r.length;for(r=r.slice();l--;)s=r[l]*i+o,r[l]=s%Di|0,o=s/Di|0;return o&&r.unshift(o),r}function e(r,i,s,o){var l,c;if(s!=o)c=s>o?1:-1;else for(l=c=0;l<s;l++)if(r[l]!=i[l]){c=r[l]>i[l]?1:-1;break}return c}function n(r,i,s){for(var o=0;s--;)r[s]-=o,o=r[s]<i[s]?1:0,r[s]=o*Di+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o){var l,c,d,u,m,p,f,y,v,b,g,_,k,P,N,M,A,T,C=r.constructor,F=r.s==i.s?1:-1,$=r.d,I=i.d;if(!r.s)return new C(r);if(!i.s)throw Error(tc+"Division by zero");for(c=r.e-i.e,A=I.length,N=$.length,f=new C(F),y=f.d=[],d=0;I[d]==($[d]||0);)++d;if(I[d]>($[d]||0)&&--c,s==null?_=s=C.precision:o?_=s+(di(r)-di(i))+1:_=s,_<0)return new C(0);if(_=_/ha+2|0,d=0,A==1)for(u=0,I=I[0],_++;(d<N||u)&&_--;d++)k=u*Di+($[d]||0),y[d]=k/I|0,u=k%I|0;else{for(u=Di/(I[0]+1)|0,u>1&&(I=t(I,u),$=t($,u),A=I.length,N=$.length),P=A,v=$.slice(0,A),b=v.length;b<A;)v[b++]=0;T=I.slice(),T.unshift(0),M=I[0],I[1]>=Di/2&&++M;do u=0,l=e(I,v,A,b),l<0?(g=v[0],A!=b&&(g=g*Di+(v[1]||0)),u=g/M|0,u>1?(u>=Di&&(u=Di-1),m=t(I,u),p=m.length,b=v.length,l=e(m,v,p,b),l==1&&(u--,n(m,A<p?T:I,p))):(u==0&&(l=u=1),m=I.slice()),p=m.length,p<b&&m.unshift(0),n(v,m,b),l==-1&&(b=v.length,l=e(I,v,A,b),l<1&&(u++,n(v,A<b?T:I,b))),b=v.length):l===0&&(u++,v=[0]),y[d++]=u,l&&v[0]?v[b++]=$[P]||0:(v=[$[P]],b=1);while((P++<N||v[0]!==void 0)&&_--)}return y[0]||y.shift(),f.e=c,Jr(f,o?s+di(f)+1:s)}})();function zte(t,e){var n,r,i,s,o,l,c=0,d=0,u=t.constructor,m=u.precision;if(di(t)>16)throw Error(KI+di(t));if(!t.s)return new u(Jo);for(xa=!1,l=m,o=new u(.03125);t.abs().gte(.1);)t=t.times(o),d+=5;for(r=Math.log(Xp(2,d))/Math.LN10*2+5|0,l+=r,n=i=s=new u(Jo),u.precision=l;;){if(i=Jr(i.times(t),l),n=n.times(++c),o=s.plus(Uu(i,n,l)),bd(o.d).slice(0,l)===bd(s.d).slice(0,l)){for(;d--;)s=Jr(s.times(s),l);return u.precision=m,e==null?(xa=!0,Jr(s,m)):s}s=o}}function di(t){for(var e=t.e*ha,n=t.d[0];n>=10;n/=10)e++;return e}function Y2(t,e,n){if(e>t.LN10.sd())throw xa=!0,n&&(t.precision=n),Error(tc+"LN10 precision limit exceeded");return Jr(new t(t.LN10),e)}function ih(t){for(var e="";t--;)e+="0";return e}function sw(t,e){var n,r,i,s,o,l,c,d,u,m=1,p=10,f=t,y=f.d,v=f.constructor,b=v.precision;if(f.s<1)throw Error(tc+(f.s?"NaN":"-Infinity"));if(f.eq(Jo))return new v(0);if(e==null?(xa=!1,d=b):d=e,f.eq(10))return e==null&&(xa=!0),Y2(v,d);if(d+=p,v.precision=d,n=bd(y),r=n.charAt(0),s=di(f),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(t),n=bd(f.d),r=n.charAt(0),m++;s=di(f),r>1?(f=new v("0."+n),s++):f=new v(r+"."+n.slice(1))}else return c=Y2(v,d+2,b).times(s+""),f=sw(new v(r+"."+n.slice(1)),d-p).plus(c),v.precision=b,e==null?(xa=!0,Jr(f,b)):f;for(l=o=f=Uu(f.minus(Jo),f.plus(Jo),d),u=Jr(f.times(f),d),i=3;;){if(o=Jr(o.times(u),d),c=l.plus(Uu(o,new v(i),d)),bd(c.d).slice(0,d)===bd(l.d).slice(0,d))return l=l.times(2),s!==0&&(l=l.plus(Y2(v,d+2,b).times(s+""))),l=Uu(l,new v(m),d),v.precision=b,e==null?(xa=!0,Jr(l,b)):l;l=c,i+=2}}function L7(t,e){var n,r,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),r=0;e.charCodeAt(r)===48;)++r;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(r,i),e){if(i-=r,n=n-r-1,t.e=my(n/ha),t.d=[],r=(n+1)%ha,n<0&&(r+=ha),r<i){for(r&&t.d.push(+e.slice(0,r)),i-=ha;r<i;)t.d.push(+e.slice(r,r+=ha));e=e.slice(r),r=ha-e.length}else r-=i;for(;r--;)e+="0";if(t.d.push(+e),xa&&(t.e>rC||t.e<-rC))throw Error(KI+n)}else t.s=0,t.e=0,t.d=[0];return t}function Jr(t,e,n){var r,i,s,o,l,c,d,u,m=t.d;for(o=1,s=m[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=ha,i=e,d=m[u=0];else{if(u=Math.ceil((r+1)/ha),s=m.length,u>=s)return t;for(d=s=m[u],o=1;s>=10;s/=10)o++;r%=ha,i=r-ha+o}if(n!==void 0&&(s=Xp(10,o-i-1),l=d/s%10|0,c=e<0||m[u+1]!==void 0||d%s,c=n<4?(l||c)&&(n==0||n==(t.s<0?3:2)):l>5||l==5&&(n==4||c||n==6&&(r>0?i>0?d/Xp(10,o-i):0:m[u-1])%10&1||n==(t.s<0?8:7))),e<1||!m[0])return c?(s=di(t),m.length=1,e=e-s-1,m[0]=Xp(10,(ha-e%ha)%ha),t.e=my(-e/ha)||0):(m.length=1,m[0]=t.e=t.s=0),t;if(r==0?(m.length=u,s=1,u--):(m.length=u+1,s=Xp(10,ha-r),m[u]=i>0?(d/Xp(10,o-i)%Xp(10,i)|0)*s:0),c)for(;;)if(u==0){(m[0]+=s)==Di&&(m[0]=1,++t.e);break}else{if(m[u]+=s,m[u]!=Di)break;m[u--]=0,s=1}for(r=m.length;m[--r]===0;)m.pop();if(xa&&(t.e>rC||t.e<-rC))throw Error(KI+di(t));return t}function Ute(t,e){var n,r,i,s,o,l,c,d,u,m,p=t.constructor,f=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),xa?Jr(e,f):e;if(c=t.d,m=e.d,r=e.e,d=t.e,c=c.slice(),o=d-r,o){for(u=o<0,u?(n=c,o=-o,l=m.length):(n=m,r=d,l=c.length),i=Math.max(Math.ceil(f/ha),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]=Di-1;--c[s],c[i]+=Di}c[i]-=m[i]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--r;return c[0]?(e.d=c,e.e=r,xa?Jr(e,f):e):new p(0)}function eg(t,e,n){var r,i=di(t),s=bd(t.d),o=s.length;return e?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+ih(r):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&&(r=n-o)>0&&(s+=ih(r))):i>=o?(s+=ih(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+ih(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=ih(r))),t.s<0?"-"+s:s}function O7(t,e){if(t.length>e)return t.length=e,!0}function Bte(t){var e,n,r;function i(s){var o=this;if(!(o instanceof i))return new i(s);if(o.constructor=i,s instanceof i){o.s=s.s,o.e=s.e,o.d=(s=s.d)?s.slice():s;return}if(typeof s=="number"){if(s*0!==0)throw Error(Cf+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 L7(o,s.toString())}else if(typeof s!="string")throw Error(Cf+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,OOe.test(s))L7(o,s);else throw Error(Cf+s)}if(i.prototype=hn,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=Bte,i.config=i.set=IOe,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e<r.length;)t.hasOwnProperty(n=r[e++])||(t[n]=this[n]);return i.config(t),i}function IOe(t){if(!t||typeof t!="object")throw Error(tc+"Object expected");var e,n,r,i=["precision",1,uy,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e<i.length;e+=3)if((r=t[n=i[e]])!==void 0)if(my(r)===r&&r>=i[e+1]&&r<=i[e+2])this[n]=r;else throw Error(Cf+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(Cf+n+": "+r);return this}var YI=Bte(LOe);Jo=new YI(1);const Or=YI;function Hte(t){var e;return t===0?e=1:e=Math.floor(new Or(t).abs().log(10).toNumber())+1,e}function qte(t,e,n){for(var r=new Or(t),i=0,s=[];r.lt(e)&&i<1e5;)s.push(r.toNumber()),r=r.add(n),i++;return s}var $te=t=>{var[e,n]=t,[r,i]=[e,n];return e>n&&([r,i]=[n,e]),[r,i]},Vte=(t,e,n)=>{if(t.lte(0))return new Or(0);var r=Hte(t.toNumber()),i=new Or(10).pow(r),s=t.div(i),o=r!==1?.05:.1,l=new Or(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(i);return e?new Or(c.toNumber()):new Or(Math.ceil(c.toNumber()))},zOe=(t,e,n)=>{var r=new Or(1),i=new Or(t);if(!i.isint()&&n){var s=Math.abs(t);s<1?(r=new Or(10).pow(Hte(t)-1),i=new Or(Math.floor(i.div(r).toNumber())).mul(r)):s>1&&(i=new Or(Math.floor(t)))}else t===0?i=new Or(Math.floor((e-1)/2)):n||(i=new Or(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c<e;c++)l.push(i.add(new Or(c-o).mul(r)).toNumber());return l},Gte=function(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new Or(0),tickMin:new Or(0),tickMax:new Or(0)};var o=Vte(new Or(n).sub(e).div(r-1),i,s),l;e<=0&&n>=0?l=new Or(0):(l=new Or(e).add(n).div(2),l=l.sub(new Or(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),d=Math.ceil(new Or(n).sub(l).div(o).toNumber()),u=c+d+1;return u>r?Gte(e,n,r,i,s+1):(u<r&&(d=n>0?d+(r-u):d,c=n>0?c:c+(r-u)),{step:o,tickMin:l.sub(new Or(c).mul(o)),tickMax:l.add(new Or(d).mul(o))})},UOe=function(e){var[n,r]=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),[l,c]=$te([n,r]);if(l===-1/0||c===1/0){var d=c===1/0?[l,...Array(i-1).fill(1/0)]:[...Array(i-1).fill(-1/0),c];return n>r?d.reverse():d}if(l===c)return zOe(l,i,s);var{step:u,tickMin:m,tickMax:p}=Gte(l,c,o,s,0),f=qte(m,p.add(new Or(.1).mul(u)),u);return n>r?f.reverse():f},BOe=function(e,n){var[r,i]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=$te([r,i]);if(o===-1/0||l===1/0)return[r,i];if(o===l)return[o];var c=Math.max(n,2),d=Vte(new Or(l).sub(o).div(c-1),s,0),u=[...qte(new Or(o),new Or(l),d),l];return s===!1&&(u=u.map(m=>Math.round(m))),r>i?u.reverse():u},Wte=t=>t.rootProps.maxBarSize,HOe=t=>t.rootProps.barGap,Kte=t=>t.rootProps.barCategoryGap,qOe=t=>t.rootProps.barSize,tS=t=>t.rootProps.stackOffset,Yte=t=>t.rootProps.reverseStackOrder,XI=t=>t.options.chartName,QI=t=>t.rootProps.syncId,Xte=t=>t.rootProps.syncMethod,ZI=t=>t.options.eventEmitter,$Oe=t=>t.rootProps.baseValue,Ha={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Hp={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},nd={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},hT=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function pT(t,e,n){if(n!=="auto")return n;if(t!=null)return Bc(t,e)?"category":"number"}function I7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function aC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?I7(Object(n),!0).forEach(function(r){VOe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):I7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function VOe(t,e,n){return(e=GOe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function GOe(t){var e=WOe(t,"string");return typeof e=="symbol"?e:e+""}function WOe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var z7={allowDataOverflow:Hp.allowDataOverflow,allowDecimals:Hp.allowDecimals,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:Hp.angleAxisId,includeHidden:!1,name:void 0,reversed:Hp.reversed,scale:Hp.scale,tick:Hp.tick,tickCount:void 0,ticks:void 0,type:Hp.type,unit:void 0},U7={allowDataOverflow:nd.allowDataOverflow,allowDecimals:nd.allowDecimals,allowDuplicatedCategory:nd.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:nd.radiusAxisId,includeHidden:nd.includeHidden,name:void 0,reversed:nd.reversed,scale:nd.scale,tick:nd.tick,tickCount:nd.tickCount,ticks:void 0,type:nd.type,unit:void 0},KOe=(t,e)=>{if(e!=null)return t.polarAxis.angleAxis[e]},JI=yt([KOe,Dee],(t,e)=>{var n;if(t!=null)return t;var r=(n=pT(e,"angleAxis",z7.type))!==null&&n!==void 0?n:"category";return aC(aC({},z7),{},{type:r})}),YOe=(t,e)=>t.polarAxis.radiusAxis[e],e4=yt([YOe,Dee],(t,e)=>{var n;if(t!=null)return t;var r=(n=pT(e,"radiusAxis",U7.type))!==null&&n!==void 0?n:"category";return aC(aC({},U7),{},{type:r})}),fT=t=>t.polarOptions,t4=yt([sm,om,wi],Qee),Qte=yt([fT,t4],(t,e)=>{if(t!=null)return Es(t.innerRadius,e,0)}),Zte=yt([fT,t4],(t,e)=>{if(t!=null)return Es(t.outerRadius,e,e*.8)}),XOe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},Jte=yt([fT],XOe);yt([JI,Jte],hT);var ene=yt([t4,Qte,Zte],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});yt([e4,ene],hT);var tne=yt([yr,fT,Qte,Zte,sm,om],(t,e,n,r,i,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:d}=e;return{cx:Es(o,i,i/2),cy:Es(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:d,clockWise:!1}}}),Aa=(t,e)=>e,nS=(t,e,n)=>n;function gT(t){return t?.id}function nne(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:i,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,d=(c=l.data)!==null&&c!==void 0?c:r;if(!(d==null||d.length===0)){var u=gT(l);d.forEach((m,p)=>{var f=s==null||i?p:String(Dr(m,s,null)),y=Dr(m,l.dataKey,0),v;o.has(f)?v=o.get(f):v={},Object.assign(v,{[u]:y}),o.set(f,v)})}}),Array.from(o.values())}function bT(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var xT=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function yT(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function QOe(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 Ui=t=>{var e=yr(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},hy=t=>t.tooltip.settings.axisId;function ZOe(t){if(t in Kv)return Kv[t]();var e="scale".concat(Hw(t));if(e in Kv)return Kv[e]()}function B7(t){var e=t.ticks,n=t.bandwidth,r=t.range(),i=[Math.min(...r),Math.max(...r)];return{domain:()=>t.domain(),range:(function(s){function o(){return s.apply(this,arguments)}return o.toString=function(){return s.toString()},o})(()=>i),rangeMin:()=>i[0],rangeMax:()=>i[1],isInRange(s){var o=i[0],l=i[1];return o<=l?s>=o&&s<=l:s>=l&&s<=o},bandwidth:n?()=>n.call(t):void 0,ticks:e?s=>e.call(t,s):void 0,map:(s,o)=>{var l=t(s);if(l!=null){if(t.bandwidth&&o!==null&&o!==void 0&&o.position){var c=t.bandwidth();switch(o.position){case"middle":l+=c/2;break;case"end":l+=c;break}}return l}}}}function H7(t,e,n){if(typeof t=="function")return B7(t.copy().domain(e).range(n));if(t!=null){var r=ZOe(t);if(r!=null)return r.domain(e).range(n),B7(r)}}var rne=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!nm(e)){for(var n,r,i=0;i<e.length;i++){var s=e[i];qn(s)&&((n===void 0||s<n)&&(n=s),(r===void 0||s>r)&&(r=s))}return n!==void 0&&r!==void 0?[n,r]:void 0}return e}default:return e}};function q7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function iC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?q7(Object(n),!0).forEach(function(r){JOe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):q7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function JOe(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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var LR=[0,"auto"],ji={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},ane=(t,e)=>t.cartesianAxis.xAxis[e],Fd=(t,e)=>{var n=ane(t,e);return n??ji},Ei={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:LR,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:Gw},ine=(t,e)=>t.cartesianAxis.yAxis[e],Rd=(t,e)=>{var n=ine(t,e);return n??Ei},nIe={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:""},n4=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??nIe},Wa=(t,e,n)=>{switch(e){case"xAxis":return Fd(t,n);case"yAxis":return Rd(t,n);case"zAxis":return n4(t,n);case"angleAxis":return JI(t,n);case"radiusAxis":return e4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},rIe=(t,e,n)=>{switch(e){case"xAxis":return Fd(t,n);case"yAxis":return Rd(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},py=(t,e,n)=>{switch(e){case"xAxis":return Fd(t,n);case"yAxis":return Rd(t,n);case"angleAxis":return JI(t,n);case"radiusAxis":return e4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},sne=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function r4(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 rS=t=>t.graphicalItems.cartesianItems,aIe=yt([Aa,nS],r4),a4=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),aS=yt([rS,Wa,aIe],a4,{memoizeOptions:{resultEqualityCheck:yT}}),one=yt([aS],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(bT)),lne=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),iIe=yt([aS],lne),i4=t=>t.map(e=>e.data).filter(Boolean).flat(1),sIe=yt([aS],i4,{memoizeOptions:{resultEqualityCheck:yT}}),s4=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:i}=e;return t.length>0?t:n.slice(r,i+1)},o4=yt([sIe,WI],s4),l4=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:Dr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(i=>({value:Dr(i,r)}))):t.map(r=>({value:r})),vT=yt([o4,Wa,aS],l4);function cne(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function Ek(t){if(Jl(t)||t instanceof Date){var e=Number(t);if(qn(e))return e}}function $7(t){if(Array.isArray(t)){var e=[Ek(t[0]),Ek(t[1])];return nm(e)?e:void 0}var n=Ek(t);if(n!=null)return[n,n]}function rm(t){return t.map(Ek).filter(ko)}function oIe(t,e,n){return!n||typeof e!="number"||Rc(e)?[]:n.length?rm(n.flatMap(r=>{var i=Dr(t,r.dataKey),s,o;if(Array.isArray(i)?[s,o]=i:s=o=i,!(!qn(s)||!qn(o)))return[e-s,e+o]})):[]}var ki=t=>{var e=Ui(t),n=hy(t);return py(t,e,n)},iS=yt([ki],t=>t?.dataKey),lIe=yt([one,WI,ki],nne),dne=(t,e,n,r)=>{var i={},s=e.reduce((o,l)=>{if(l.stackId==null)return o;var c=o[l.stackId];return c==null&&(c=[]),c.push(l),o[l.stackId]=c,o},i);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,d=r?[...c].reverse():c,u=d.map(gT);return[l,{stackedData:ADe(t,u,n),graphicalItems:d}]}))},sC=yt([lIe,one,tS,Yte],dne),une=(t,e,n,r)=>{var{dataStartIndex:i,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=DDe(t,i,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},cIe=yt([Wa],t=>t.allowDataOverflow),c4=t=>{var e;if(t==null||!("domain"in t))return LR;if(t.domain!=null)return t.domain;if("ticks"in t&&t.ticks!=null){if(t.type==="number"){var n=rm(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:LR},d4=yt([Wa],c4),u4=yt([d4,cIe],Lte),dIe=yt([sC,cm,Aa,u4],une,{memoizeOptions:{resultEqualityCheck:xT}}),wT=t=>t.errorBars,uIe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>cne(n,r)),oC=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];var i=n.filter(Boolean);if(i.length!==0){var s=i.flat(),o=Math.min(...s),l=Math.max(...s);return[o,l]}},m4=(t,e,n,r,i)=>{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var d,u,m=(d=r[c.id])===null||d===void 0?void 0:d.filter(g=>cne(i,g)),p=Dr(l,(u=e.dataKey)!==null&&u!==void 0?u:c.dataKey),f=oIe(l,p,m);if(f.length>=2){var y=Math.min(...f),v=Math.max(...f);(s==null||y<s)&&(s=y),(o==null||v>o)&&(o=v)}var b=$7(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=$7(Dr(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]))}),qn(s)&&qn(o))return[s,o]},mIe=yt([o4,Wa,iIe,wT,Aa],m4,{memoizeOptions:{resultEqualityCheck:xT}});function hIe(t){var{value:e}=t;if(Jl(e)||e instanceof Date)return e}var pIe=(t,e,n)=>{var r=t.map(hIe).filter(i=>i!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&TJ(r))?tte(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},mne=t=>t.referenceElements.dots,fy=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),fIe=yt([mne,Aa,nS],fy),hne=t=>t.referenceElements.areas,gIe=yt([hne,Aa,nS],fy),pne=t=>t.referenceElements.lines,bIe=yt([pne,Aa,nS],fy),fne=(t,e)=>{if(t!=null){var n=rm(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},xIe=yt(fIe,Aa,fne),gne=(t,e)=>{if(t!=null){var n=rm(t.flatMap(r=>[e==="xAxis"?r.x1:r.y1,e==="xAxis"?r.x2:r.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},yIe=yt([gIe,Aa],gne);function vIe(t){var e;if(t.x!=null)return rm([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:rm(n)}function wIe(t){var e;if(t.y!=null)return rm([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:rm(n)}var bne=(t,e)=>{if(t!=null){var n=t.flatMap(r=>e==="xAxis"?vIe(r):wIe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},SIe=yt([bIe,Aa],bne),_Ie=yt(xIe,SIe,yIe,(t,e,n)=>oC(t,n,e)),h4=(t,e,n,r,i,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",d=c?oC(r,s,i):oC(s,i);return ROe(e,d,t.allowDataOverflow)},kIe=yt([Wa,d4,u4,dIe,mIe,_Ie,yr,Aa],h4,{memoizeOptions:{resultEqualityCheck:xT}}),NIe=[0,1],p4=(t,e,n,r,i,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,d=Bc(e,s);if(d&&l==null){var u;return tte(0,(u=n?.length)!==null&&u!==void 0?u:0)}return c==="category"?pIe(r,t,d):i==="expand"?NIe:o}},f4=yt([Wa,yr,o4,vT,tS,Aa,kIe],p4);function CIe(t){return t in Kv}var xne=(t,e,n)=>{if(t!=null){var{scale:r,type:i}=t;if(r==="auto")return i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!e)?"point":i==="category"?"band":"linear";if(typeof r=="string"){var s="scale".concat(Hw(r));return CIe(s)?s:"point"}}},sp=yt([Wa,sne,XI],xne);function g4(t,e,n,r){if(!(n==null||r==null))return typeof t.scale=="function"?H7(t.scale,n,r):H7(e,n,r)}var b4=(t,e,n)=>{var r=c4(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&nm(t))return UOe(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&nm(t))return BOe(t,e.tickCount,e.allowDecimals)}},x4=yt([f4,py,sp],b4),y4=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&nm(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},PIe=yt([Wa,f4,x4,Aa],y4),TIe=yt(vT,Wa,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(rm(t.map(m=>m.value))).sort((m,p)=>m-p),i=r[0],s=r[r.length-1];if(i==null||s==null)return 1/0;var o=s-i;if(o===0)return 1/0;for(var l=0;l<r.length-1;l++){var c=r[l],d=r[l+1];if(!(c==null||d==null)){var u=d-c;n=Math.min(n,u)}}return n/o}}),yne=yt(TIe,yr,Kte,wi,(t,e,n,r,i)=>i,(t,e,n,r,i)=>{if(!qn(t))return 0;var s=e==="vertical"?r.height:r.width;if(i==="gap")return t*s/2;if(i==="no-gap"){var o=Es(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),AIe=(t,e,n)=>{var r=Fd(t,e);return r==null||typeof r.padding!="string"?0:yne(t,"xAxis",e,n,r.padding)},MIe=(t,e,n)=>{var r=Rd(t,e);return r==null||typeof r.padding!="string"?0:yne(t,"yAxis",e,n,r.padding)},jIe=yt(Fd,AIe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:i}=t;return typeof i=="string"?{left:e,right:e}:{left:((n=i.left)!==null&&n!==void 0?n:0)+e,right:((r=i.right)!==null&&r!==void 0?r:0)+e}}),EIe=yt(Rd,MIe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:i}=t;return typeof i=="string"?{top:e,bottom:e}:{top:((n=i.top)!==null&&n!==void 0?n:0)+e,bottom:((r=i.bottom)!==null&&r!==void 0?r:0)+e}}),DIe=yt([wi,jIe,nT,tT,(t,e,n)=>n],(t,e,n,r,i)=>{var{padding:s}=r;return i?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),FIe=yt([wi,yr,EIe,nT,tT,(t,e,n)=>n],(t,e,n,r,i,s)=>{var{padding:o}=i;return s?[r.height-o.bottom,o.top]:e==="horizontal"?[t.top+t.height-n.bottom,t.top+n.top]:[t.top+n.top,t.top+t.height-n.bottom]}),sS=(t,e,n,r)=>{var i;switch(e){case"xAxis":return DIe(t,n,r);case"yAxis":return FIe(t,n,r);case"zAxis":return(i=n4(t,n))===null||i===void 0?void 0:i.range;case"angleAxis":return Jte(t);case"radiusAxis":return ene(t,n);default:return}},vne=yt([Wa,sS],hT),RIe=yt([sp,PIe],rne),Ix=yt([Wa,sp,RIe,vne],g4);yt([aS,wT,Aa],uIe);function wne(t,e){return t.id<e.id?-1:t.id>e.id?1:0}var ST=(t,e)=>e,_T=(t,e,n)=>n,LIe=yt(JP,ST,_T,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(wne)),OIe=yt(eT,ST,_T,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(wne)),Sne=(t,e)=>({width:t.width,height:e.height}),IIe=(t,e)=>{var n=typeof e.width=="number"?e.width:Gw;return{width:n,height:t.height}},_ne=yt(wi,Fd,Sne),zIe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},UIe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},BIe=yt(om,wi,LIe,ST,_T,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=Sne(e,l);o==null&&(o=zIe(e,r,t));var d=r==="top"&&!i||r==="bottom"&&i;s[l.id]=o-Number(d)*c.height,o+=(d?-1:1)*c.height}),s}),HIe=yt(sm,wi,OIe,ST,_T,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=IIe(e,l);o==null&&(o=UIe(e,r,t));var d=r==="left"&&!i||r==="right"&&i;s[l.id]=o-Number(d)*c.width,o+=(d?-1:1)*c.width}),s}),qIe=(t,e)=>{var n=Fd(t,e);if(n!=null)return BIe(t,n.orientation,n.mirror)},$Ie=yt([wi,Fd,qIe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:t.left,y:0}:{x:t.left,y:i}}}),VIe=(t,e)=>{var n=Rd(t,e);if(n!=null)return HIe(t,n.orientation,n.mirror)},GIe=yt([wi,Rd,VIe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:0,y:t.top}:{x:i,y:t.top}}}),kne=yt(wi,Rd,(t,e)=>{var n=typeof e.width=="number"?e.width:Gw;return{width:n,height:t.height}}),V7=(t,e,n)=>{switch(e){case"xAxis":return _ne(t,n).width;case"yAxis":return kne(t,n).height;default:return}},Nne=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:i,type:s,dataKey:o}=n,l=Bc(t,r),c=e.map(d=>d.value);if(o&&l&&s==="category"&&i&&TJ(c))return c}},v4=yt([yr,vT,Wa,Aa],Nne),Cne=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:i,scale:s}=n,o=Bc(t,r);if(o&&(i==="number"||s!=="auto"))return e.map(l=>l.value)}},w4=yt([yr,vT,py,Aa],Cne),G7=yt([yr,rIe,sp,Ix,v4,w4,sS,x4,Aa],(t,e,n,r,i,s,o,l,c)=>{if(e!=null){var d=Bc(t,c);return{angle:e.angle,interval:e.interval,minTickGap:e.minTickGap,orientation:e.orientation,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit,axisType:c,categoricalDomain:s,duplicateDomain:i,isCategorical:d,niceTicks:l,range:o,realScaleType:n,scale:r}}}),WIe=(t,e,n,r,i,s,o,l,c)=>{if(!(e==null||r==null)){var d=Bc(t,c),{type:u,ticks:m,tickCount:p}=e,f=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,y=u==="category"&&r.bandwidth?r.bandwidth()/f:0;y=c==="angleAxis"&&s!=null&&s.length>=2?Li(s[0]-s[1])*2*y:y;var v=m||i;return v?v.map((b,g)=>{var _=o?o.indexOf(b):b,k=r.map(_);return qn(k)?{index:g,coordinate:k+y,value:b,offset:y}:null}).filter(ko):d&&l?l.map((b,g)=>{var _=r.map(b);return qn(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(ko):r.ticks?r.ticks(p).map((b,g)=>{var _=r.map(b);return qn(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(ko):r.domain().map((b,g)=>{var _=r.map(b);return qn(_)?{coordinate:_+y,value:o?o[b]:b,index:g,offset:y}:null}).filter(ko)}},Pne=yt([yr,py,sp,Ix,x4,sS,v4,w4,Aa],WIe),KIe=(t,e,n,r,i,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Bc(t,o),{tickCount:c}=e,d=0;return d=o==="angleAxis"&&r?.length>=2?Li(r[0]-r[1])*2*d:d,l&&s?s.map((u,m)=>{var p=n.map(u);return qn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(ko):n.ticks?n.ticks(c).map((u,m)=>{var p=n.map(u);return qn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(ko):n.domain().map((u,m)=>{var p=n.map(u);return qn(p)?{coordinate:p+d,value:i?i[u]:u,index:m,offset:d}:null}).filter(ko)}},Ad=yt([yr,py,Ix,sS,v4,w4,Aa],KIe),Md=yt(Wa,Ix,(t,e)=>{if(!(t==null||e==null))return iC(iC({},t),{},{scale:e})}),YIe=yt([Wa,sp,f4,vne],g4);yt((t,e,n)=>n4(t,n),YIe,(t,e)=>{if(!(t==null||e==null))return iC(iC({},t),{},{scale:e})});var XIe=yt([yr,JP,eT],(t,e,n)=>{switch(t){case"horizontal":return e.some(r=>r.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(r=>r.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),Tne=t=>t.options.defaultTooltipEventType,Ane=t=>t.options.validateTooltipEventTypes;function Mne(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function S4(t,e){var n=Tne(t),r=Ane(t);return Mne(e,n,r)}function QIe(t){return dn(e=>S4(e,t))}var jne=(t,e)=>{var n,r=Number(e);if(!(Rc(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},ZIe=t=>t.tooltip.settings,mh={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},JIe={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}},Ene=Do({name:"tooltip",initialState:JIe,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:ba()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,i=jc(t).tooltipItemPayloads.indexOf(n);i>-1&&(t.tooltipItemPayloads[i]=r)},prepare:ba()},removeTooltipEntrySettings:{reducer(t,e){var n=jc(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:ba()},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:e4e,replaceTooltipEntrySettings:t4e,removeTooltipEntrySettings:n4e,setTooltipSettingsState:r4e,setActiveMouseOverItemIndex:Dne,mouseLeaveItem:a4e,mouseLeaveChart:Fne,setActiveClickItemIndex:i4e,setMouseOverAxisIndex:Rne,setMouseClickAxisIndex:s4e,setSyncInteraction:OR,setKeyboardInteraction:IR}=Ene.actions,o4e=Ene.reducer;function W7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function q1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?W7(Object(n),!0).forEach(function(r){l4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):W7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function l4e(t,e,n){return(e=c4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function c4e(t){var e=d4e(t,"string");return typeof e=="symbol"?e:e+""}function d4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function u4e(t,e,n){return e==="axis"?n==="click"?t.axisInteraction.click:t.axisInteraction.hover:n==="click"?t.itemInteraction.click:t.itemInteraction.hover}function m4e(t){return t.index!=null}var Lne=(t,e,n,r)=>{if(e==null)return mh;var i=u4e(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(m4e(i)){if(s)return q1(q1({},i),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return q1(q1({},mh),{},{coordinate:i.coordinate})};function h4e(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 p4e(t,e){var n=h4e(t),r=e[0],i=e[1];if(n===void 0)return!1;var s=Math.min(r,i),o=Math.max(r,i);return n>=s&&n<=o}function f4e(t,e,n){if(n==null||e==null)return!0;var r=Dr(t,e);return r==null||!nm(n)?!0:p4e(r,n)}var _4=(t,e,n,r)=>{var i=t?.index;if(i==null)return null;var s=Number(i);if(!qn(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||f4e(d,n,r)?String(c):null},One=(t,e,n,r,i,s,o)=>{if(s!=null){var l=o[0],c=l?.getPosition(s);if(c!=null)return c;var d=i?.[Number(s)];if(d)return n==="horizontal"?{x:d.coordinate,y:(r.top+e)/2}:{x:(r.left+t)/2,y:d.coordinate}}},Ine=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var i;if(n==="hover"?i=t.itemInteraction.hover.graphicalItemId:i=t.itemInteraction.click.graphicalItemId,i==null&&r!=null){var s=t.tooltipItemPayloads[0];return s!=null?[s]:[]}return t.tooltipItemPayloads.filter(o=>{var l;return((l=o.settings)===null||l===void 0?void 0:l.graphicalItemId)===i})},zne=t=>t.options.tooltipPayloadSearcher,gy=t=>t.tooltip;function K7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Y7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?K7(Object(n),!0).forEach(function(r){g4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):K7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function g4e(t,e,n){return(e=b4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function b4e(t){var e=x4e(t,"string");return typeof e=="symbol"?e:e+""}function x4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function y4e(t,e){return t??e}var Une=(t,e,n,r,i,s,o)=>{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:d,dataEndIndex:u}=n,m=[];return t.reduce((p,f)=>{var y,{dataDefinedOnItem:v,settings:b}=f,g=y4e(v,l),_=Array.isArray(g)?See(g,d,u):g,k=(y=b?.dataKey)!==null&&y!==void 0?y:r,P=b?.nameKey,N;if(r&&Array.isArray(_)&&!Array.isArray(_[0])&&o==="axis"?N=AJ(_,r,i):N=s(_,e,c,P),Array.isArray(N))N.forEach(A=>{var T=Y7(Y7({},b),{},{name:A.name,unit:A.unit,color:void 0,fill:void 0});p.push(WV({tooltipEntrySettings:T,dataKey:A.dataKey,payload:A.payload,value:Dr(A.payload,A.dataKey),name:A.name}))});else{var M;p.push(WV({tooltipEntrySettings:b,dataKey:k,payload:N,value:Dr(N,k),name:(M=Dr(N,P))!==null&&M!==void 0?M:b?.name}))}return p},m)}},k4=yt([ki,sne,XI],xne),v4e=yt([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),w4e=yt([Ui,hy],r4),by=yt([v4e,ki,w4e],a4,{memoizeOptions:{resultEqualityCheck:yT}}),S4e=yt([by],t=>t.filter(bT)),_4e=yt([by],i4,{memoizeOptions:{resultEqualityCheck:yT}}),xy=yt([_4e,cm],s4),k4e=yt([S4e,cm,ki],nne),N4=yt([xy,ki,by],l4),Bne=yt([ki],c4),N4e=yt([ki],t=>t.allowDataOverflow),Hne=yt([Bne,N4e],Lte),C4e=yt([by],t=>t.filter(bT)),P4e=yt([k4e,C4e,tS,Yte],dne),T4e=yt([P4e,cm,Ui,Hne],une),A4e=yt([by],lne),M4e=yt([xy,ki,A4e,wT,Ui],m4,{memoizeOptions:{resultEqualityCheck:xT}}),j4e=yt([mne,Ui,hy],fy),E4e=yt([j4e,Ui],fne),D4e=yt([hne,Ui,hy],fy),F4e=yt([D4e,Ui],gne),R4e=yt([pne,Ui,hy],fy),L4e=yt([R4e,Ui],bne),O4e=yt([E4e,L4e,F4e],oC),I4e=yt([ki,Bne,Hne,T4e,M4e,O4e,yr,Ui],h4),oS=yt([ki,yr,xy,N4,tS,Ui,I4e],p4),z4e=yt([oS,ki,k4],b4),U4e=yt([ki,oS,z4e,Ui],y4),qne=t=>{var e=Ui(t),n=hy(t),r=!1;return sS(t,e,n,r)},$ne=yt([ki,qne],hT),Vne=yt([ki,k4,U4e,$ne],g4),B4e=yt([yr,N4,ki,Ui],Nne),H4e=yt([yr,N4,ki,Ui],Cne),q4e=(t,e,n,r,i,s,o,l)=>{if(e){var{type:c}=e,d=Bc(t,l);if(r){var u=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,m=c==="category"&&r.bandwidth?r.bandwidth()/u:0;return m=l==="angleAxis"&&i!=null&&i?.length>=2?Li(i[0]-i[1])*2*m:m,d&&o?o.map((p,f)=>{var y=r.map(p);return qn(y)?{coordinate:y+m,value:p,index:f,offset:m}:null}).filter(ko):r.domain().map((p,f)=>{var y=r.map(p);return qn(y)?{coordinate:y+m,value:s?s[p]:p,index:f,offset:m}:null}).filter(ko)}}},dm=yt([yr,ki,k4,Vne,qne,B4e,H4e,Ui],q4e),C4=yt([Tne,Ane,ZIe],(t,e,n)=>Mne(n.shared,t,e)),Gne=t=>t.tooltip.settings.trigger,P4=t=>t.tooltip.settings.defaultIndex,lS=yt([gy,C4,Gne,P4],Lne),Yh=yt([lS,xy,iS,oS],_4),Wne=yt([dm,Yh],jne),T4=yt([lS],t=>{if(t)return t.dataKey}),$4e=yt([lS],t=>{if(t)return t.graphicalItemId}),Kne=yt([gy,C4,Gne,P4],Ine),V4e=yt([sm,om,yr,wi,dm,P4,Kne],One),G4e=yt([lS,V4e],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),W4e=yt([lS],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),K4e=yt([Kne,Yh,cm,iS,Wne,zne,C4],Une),Y4e=yt([K4e],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function X7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Q7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?X7(Object(n),!0).forEach(function(r){X4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):X7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function X4e(t,e,n){return(e=Q4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Q4e(t){var e=Z4e(t,"string");return typeof e=="symbol"?e:e+""}function Z4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var J4e=()=>dn(ki),eze=()=>{var t=J4e(),e=dn(dm),n=dn(Vne);return Kh(!t||!n?void 0:Q7(Q7({},t),{},{scale:n}),e)};function Z7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Eb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Z7(Object(n),!0).forEach(function(r){tze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Z7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function tze(t,e,n){return(e=nze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function nze(t){var e=rze(t,"string");return typeof e=="symbol"?e:e+""}function rze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var aze=(t,e,n,r)=>{var i=e.find(s=>s&&s.index===n);if(i){if(t==="horizontal")return{x:i.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:i.coordinate}}return{x:0,y:0}},ize=(t,e,n,r)=>{var i=e.find(d=>d&&d.index===n);if(i){if(t==="centric"){var s=i.coordinate,{radius:o}=r;return Eb(Eb(Eb({},r),oi(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=i.coordinate,{angle:c}=r;return Eb(Eb(Eb({},r),oi(r.cx,r.cy,l,c)),{},{angle:c,radius:l})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function sze(t,e){var{chartX:n,chartY:r}=t;return n>=e.left&&n<=e.left+e.width&&r>=e.top&&r<=e.top+e.height}var Yne=(t,e,n,r,i)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(r==="angleAxis"&&i!=null&&Math.abs(Math.abs(i[1]-i[0])-360)<=1e-6)for(var l=0;l<o;l++){var c,d,u,m,p,f=l>0?(c=n[l-1])===null||c===void 0?void 0:c.coordinate:(d=n[o-1])===null||d===void 0?void 0:d.coordinate,y=(u=n[l])===null||u===void 0?void 0:u.coordinate,v=l>=o-1?(m=n[0])===null||m===void 0?void 0:m.coordinate:(p=n[l+1])===null||p===void 0?void 0:p.coordinate,b=void 0;if(!(f==null||y==null||v==null))if(Li(y-f)!==Li(v-y)){var g=[];if(Li(v-y)===Li(i[1]-i[0])){b=v;var _=y+i[1]-i[0];g[0]=Math.min(_,(_+f)/2),g[1]=Math.max(_,(_+f)/2)}else{b=f;var k=v+i[1]-i[0];g[0]=Math.min(y,(k+y)/2),g[1]=Math.max(y,(k+y)/2)}var P=[Math.min(y,(b+y)/2),Math.max(y,(b+y)/2)];if(t>P[0]&&t<=P[1]||t>=g[0]&&t<=g[1]){var N;return(N=n[l])===null||N===void 0?void 0:N.index}}else{var M=Math.min(f,v),A=Math.max(f,v);if(t>(M+y)/2&&t<=(A+y)/2){var T;return(T=n[l])===null||T===void 0?void 0:T.index}}}else if(e)for(var C=0;C<o;C++){var F=e[C];if(F!=null){var $=e[C+1],I=e[C-1];if(C===0&&$!=null&&t<=(F.coordinate+$.coordinate)/2||C===o-1&&I!=null&&t>(F.coordinate+I.coordinate)/2||C>0&&C<o-1&&I!=null&&$!=null&&t>(F.coordinate+I.coordinate)/2&&t<=(F.coordinate+$.coordinate)/2)return F.index}}return-1},Xne=()=>dn(XI),A4=(t,e)=>e,Qne=(t,e,n)=>n,M4=(t,e,n,r)=>r,oze=yt(dm,t=>qP(t,e=>e.coordinate)),j4=yt([gy,A4,Qne,M4],Lne),E4=yt([j4,xy,iS,oS],_4),lze=(t,e,n)=>{if(e!=null){var r=gy(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},Zne=yt([gy,A4,Qne,M4],Ine),lC=yt([sm,om,yr,wi,dm,M4,Zne],One),cze=yt([j4,lC],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),Jne=yt([dm,E4],jne),dze=yt([Zne,E4,cm,iS,Jne,zne,A4],Une),uze=yt([j4,E4],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),mze=(t,e,n,r,i,s,o)=>{if(!(!t||!n||!r||!i)&&sze(t,o)){var l=FDe(t,e),c=Yne(l,s,i,n,r),d=aze(e,i,c,t);return{activeIndex:String(c),activeCoordinate:d}}},hze=(t,e,n,r,i,s,o)=>{if(!(!t||!r||!i||!s||!n)){var l=QFe(t,n);if(l){var c=RDe(l,e),d=Yne(c,o,s,r,i),u=ize(e,s,d,l);return{activeIndex:String(d),activeCoordinate:u}}}},pze=(t,e,n,r,i,s,o,l)=>{if(!(!t||!e||!r||!i||!s))return e==="horizontal"||e==="vertical"?mze(t,e,r,i,s,o,l):hze(t,e,n,r,i,s,o)},fze=yt(t=>t.zIndex.zIndexMap,(t,e)=>e,(t,e,n)=>n,(t,e,n)=>{if(e!=null){var r=t[e];if(r!=null)return n?r.panoramaElement:r.element}}),gze=yt(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(Ha)),n=Array.from(new Set(e));return n.sort((r,i)=>r-i)},{memoizeOptions:{resultEqualityCheck:QOe}});function J7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function e9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?J7(Object(n),!0).forEach(function(r){bze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):J7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function bze(t,e,n){return(e=xze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function xze(t){var e=yze(t,"string");return typeof e=="symbol"?e:e+""}function yze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var vze={},wze={zIndexMap:Object.values(Ha).reduce((t,e)=>e9(e9({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),vze)},Sze=new Set(Object.values(Ha));function _ze(t){return Sze.has(t)}var ere=Do({name:"zIndex",initialState:wze,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:ba()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!_ze(n)&&delete t.zIndexMap[n])},prepare:ba()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:r,isPanorama:i}=e.payload;t.zIndexMap[n]?i?t.zIndexMap[n].panoramaElement=r:t.zIndexMap[n].element=r:t.zIndexMap[n]={consumers:0,element:i?void 0:r,panoramaElement:i?r:void 0}},prepare:ba()},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:ba()}}}),{registerZIndexPortal:kze,unregisterZIndexPortal:Nze,registerZIndexPortalElement:Cze,unregisterZIndexPortalElement:Pze}=ere.actions,Tze=ere.reducer;function Ls(t){var{zIndex:e,children:n}=t,r=m3e(),i=r&&e!==void 0&&e!==0,s=Si(),o=ta();w.useLayoutEffect(()=>i?(o(kze({zIndex:e})),()=>{o(Nze({zIndex:e}))}):tp,[o,e,i]);var l=dn(c=>fze(c,e,s));return i?l?Cu.createPortal(n,l):null:n}function zR(){return zR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},zR.apply(null,arguments)}function t9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function $1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?t9(Object(n),!0).forEach(function(r){Aze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):t9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Aze(t,e,n){return(e=Mze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Mze(t){var e=jze(t,"string");return typeof e=="symbol"?e:e+""}function jze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Eze(t){var{cursor:e,cursorComp:n,cursorProps:r}=t;return w.isValidElement(e)?w.cloneElement(e,r):w.createElement(n,r)}function Dze(t){var e,{coordinate:n,payload:r,index:i,offset:s,tooltipAxisBandSize:o,layout:l,cursor:c,tooltipEventType:d,chartName:u}=t,m=n,p=r,f=i;if(!c||!m||u!=="ScatterChart"&&d!=="axis")return null;var y,v,b;if(u==="ScatterChart")y=m,v=uFe,b=Ha.cursorLine;else if(u==="BarChart")y=mFe(l,m,s,o),v=Xee,b=Ha.cursorRectangle;else if(l==="radial"&&jJ(m)){var{cx:g,cy:_,radius:k,startAngle:P,endAngle:N}=Zee(m);y={cx:g,cy:_,startAngle:P,endAngle:N,innerRadius:k,outerRadius:k},v=ete,b=Ha.cursorLine}else y={points:tRe(l,m,s)},v=dx,b=Ha.cursorLine;var M=typeof c=="object"&&"className"in c?c.className:void 0,A=$1($1($1($1({stroke:"#ccc",pointerEvents:"none"},s),y),Wf(c)),{},{payload:p,payloadIndex:f,className:wr("recharts-tooltip-cursor",M)});return w.createElement(Ls,{zIndex:(e=t.zIndex)!==null&&e!==void 0?e:b},w.createElement(Eze,{cursor:c,cursorComp:v,cursorProps:A}))}function Fze(t){var e=eze(),n=Eee(),r=rp(),i=Xne();return e==null||n==null||r==null||i==null?null:w.createElement(Dze,zR({},t,{offset:n,layout:r,tooltipAxisBandSize:e,chartName:i}))}var tre=w.createContext(null),Rze=()=>w.useContext(tre),X2={exports:{}},n9;function Lze(){return n9||(n9=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,d,u){this.fn=c,this.context=d,this.once=u||!1}function s(c,d,u,m,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,m||c,p),y=n?n+d:d;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],f]:c._events[y].push(f):(c._events[y]=f,c._eventsCount++),c}function o(c,d){--c._eventsCount===0?c._events=new r:delete c._events[d]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],u,m;if(this._eventsCount===0)return d;for(m in u=this._events)e.call(u,m)&&d.push(n?m.slice(1):m);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},l.prototype.listeners=function(d){var u=n?n+d:d,m=this._events[u];if(!m)return[];if(m.fn)return[m.fn];for(var p=0,f=m.length,y=new Array(f);p<f;p++)y[p]=m[p].fn;return y},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,y){var v=n?n+d:d;if(!this._events[v])return!1;var b=this._events[v],g=arguments.length,_,k;if(b.fn){switch(b.once&&this.removeListener(d,b.fn,void 0,!0),g){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,y),!0}for(k=1,_=new Array(g-1);k<g;k++)_[k-1]=arguments[k];b.fn.apply(b.context,_)}else{var P=b.length,N;for(k=0;k<P;k++)switch(b[k].once&&this.removeListener(d,b[k].fn,void 0,!0),g){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(!_)for(N=1,_=new Array(g-1);N<g;N++)_[N-1]=arguments[N];b[k].fn.apply(b[k].context,_)}}return!0},l.prototype.on=function(d,u,m){return s(this,d,u,m,!1)},l.prototype.once=function(d,u,m){return s(this,d,u,m,!0)},l.prototype.removeListener=function(d,u,m,p){var f=n?n+d:d;if(!this._events[f])return this;if(!u)return o(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!p||y.once)&&(!m||y.context===m)&&o(this,f);else{for(var v=0,b=[],g=y.length;v<g;v++)(y[v].fn!==u||p&&!y[v].once||m&&y[v].context!==m)&&b.push(y[v]);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 r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,t.exports=l})(X2)),X2.exports}var Oze=Lze();const Ize=rc(Oze);var ow=new Ize,UR="recharts.syncEvent.tooltip",r9="recharts.syncEvent.brush",kT=(t,e)=>{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!Rc(n))return t[n]}},zze={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},nre=Do({name:"options",initialState:zze,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),Uze=nre.reducer,{createEventEmitter:Bze}=nre.actions;function Hze(t){return t.tooltip.syncInteraction}var qze={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},rre=Do({name:"chartData",initialState:qze,reducers:{setChartData(t,e){if(t.chartData=e.payload,e.payload==null){t.dataStartIndex=0,t.dataEndIndex=0;return}e.payload.length>0&&t.dataEndIndex!==e.payload.length-1&&(t.dataEndIndex=e.payload.length-1)},setComputedData(t,e){t.computedData=e.payload},setDataStartEndIndexes(t,e){var{startIndex:n,endIndex:r}=e.payload;n!=null&&(t.dataStartIndex=n),r!=null&&(t.dataEndIndex=r)}}}),{setChartData:a9,setDataStartEndIndexes:$ze,setComputedData:Mit}=rre.actions,Vze=rre.reducer,Gze=["x","y"];function i9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Db(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?i9(Object(n),!0).forEach(function(r){Wze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):i9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Wze(t,e,n){return(e=Kze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Kze(t){var e=Yze(t,"string");return typeof e=="symbol"?e:e+""}function Yze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Xze(t,e){if(t==null)return{};var n,r,i=Qze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function Qze(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function Zze(){var t=dn(QI),e=dn(ZI),n=ta(),r=dn(Xte),i=dn(dm),s=rp(),o=Ww(),l=dn(c=>c.rootProps.className);w.useEffect(()=>{if(t==null)return tp;var c=(d,u,m)=>{if(e!==m&&t===d){if(r==="index"){var p;if(o&&u!==null&&u!==void 0&&(p=u.payload)!==null&&p!==void 0&&p.coordinate&&u.payload.sourceViewBox){var f=u.payload.coordinate,{x:y,y:v}=f,b=Xze(f,Gze),{x:g,y:_,width:k,height:P}=u.payload.sourceViewBox,N=Db(Db({},b),{},{x:o.x+(k?(y-g)/k:0)*o.width,y:o.y+(P?(v-_)/P:0)*o.height});n(Db(Db({},u),{},{payload:Db(Db({},u.payload),{},{coordinate:N})}))}else n(u);return}if(i!=null){var M;if(typeof r=="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},T=r(i,A);M=i[T]}else r==="value"&&(M=i.find(ae=>String(ae.value)===u.payload.label));var{coordinate:C}=u.payload;if(M==null||u.payload.active===!1||C==null||o==null){n(OR({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:F,y:$}=C,I=Math.min(F,o.x+o.width),X=Math.min($,o.y+o.height),L={x:s==="horizontal"?M.coordinate:I,y:s==="horizontal"?X:M.coordinate},te=OR({active:u.payload.active,coordinate:L,dataKey:u.payload.dataKey,index:String(M.index),label:u.payload.label,sourceViewBox:u.payload.sourceViewBox,graphicalItemId:u.payload.graphicalItemId});n(te)}}};return ow.on(UR,c),()=>{ow.off(UR,c)}},[l,n,e,t,r,i,s,o])}function Jze(){var t=dn(QI),e=dn(ZI),n=ta();w.useEffect(()=>{if(t==null)return tp;var r=(i,s,o)=>{e!==o&&t===i&&n($ze(s))};return ow.on(r9,r),()=>{ow.off(r9,r)}},[n,e,t])}function e5e(){var t=ta();w.useEffect(()=>{t(Bze())},[t]),Zze(),Jze()}function t5e(t,e,n,r,i,s){var o=dn(f=>lze(f,t,e)),l=dn(ZI),c=dn(QI),d=dn(Xte),u=dn(Hze),m=u?.active,p=Ww();w.useEffect(()=>{if(!m&&c!=null&&l!=null){var f=OR({active:s,coordinate:n,dataKey:o,index:i,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});ow.emit(UR,c,f,l)}},[m,n,o,i,r,l,c,d,s,p])}function s9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function o9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?s9(Object(n),!0).forEach(function(r){n5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):s9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function n5e(t,e,n){return(e=r5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function r5e(t){var e=a5e(t,"string");return typeof e=="symbol"?e:e+""}function a5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function i5e(t){return t.dataKey}function s5e(t,e){return w.isValidElement(t)?w.cloneElement(t,e):typeof t=="function"?w.createElement(t,e):w.createElement($3e,e)}var l9=[],o5e={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 kh(t){var e,n,r=Ta(t,o5e),{active:i,allowEscapeViewBox:s,animationDuration:o,animationEasing:l,content:c,filterNull:d,isAnimationActive:u,offset:m,payloadUniqBy:p,position:f,reverseDirection:y,useTranslate3d:v,wrapperStyle:b,cursor:g,shared:_,trigger:k,defaultIndex:P,portal:N,axisId:M}=r,A=ta(),T=typeof P=="number"?String(P):P;w.useEffect(()=>{A(r4e({shared:_,trigger:k,axisId:M,active:i,defaultIndex:T}))},[A,_,k,M,i,T]);var C=Ww(),F=Vee(),$=QIe(_),{activeIndex:I,isActive:X}=(e=dn(Y=>uze(Y,$,k,T)))!==null&&e!==void 0?e:{},L=dn(Y=>dze(Y,$,k,T)),te=dn(Y=>Jne(Y,$,k,T)),ae=dn(Y=>cze(Y,$,k,T)),ee=L,me=Rze(),le=(n=i??X)!==null&&n!==void 0?n:!1,[ue,K]=GJ([ee,le]),ne=$==="axis"?te:void 0;t5e($,k,ae,ne,I,le);var oe=N??me;if(oe==null||C==null||$==null)return null;var be=ee??l9;le||(be=l9),d&&be.length&&(be=UJ(be.filter(Y=>Y.value!=null&&(Y.hide!==!0||r.includeHidden)),p,i5e));var _e=be.length>0,B=w.createElement(Q3e,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:u,active:le,coordinate:ae,hasPayload:_e,offset:m,position:f,reverseDirection:y,useTranslate3d:v,viewBox:C,wrapperStyle:b,lastBoundingBox:ue,innerRef:K,hasPortalFromProps:!!N},s5e(c,o9(o9({},r),{},{payload:be,label:ne,active:le,activeIndex:I,coordinate:ae,accessibilityLayer:F})));return w.createElement(w.Fragment,null,Cu.createPortal(B,oe),le&&w.createElement(Fze,{cursor:g,tooltipEventType:$,coordinate:ae,payload:be,index:I}))}var zx=t=>null;zx.displayName="Cell";function l5e(t,e,n){return(e=c5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function c5e(t){var e=d5e(t,"string");return typeof e=="symbol"?e:e+""}function d5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class u5e{constructor(e){l5e(this,"cache",new Map),this.maxSize=e}get(e){var n=this.cache.get(e);return n!==void 0&&(this.cache.delete(e),this.cache.set(e,n)),n}set(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(e,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function c9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function m5e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?c9(Object(n),!0).forEach(function(r){h5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):c9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function h5e(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=f5e(t,"string");return typeof e=="symbol"?e:e+""}function f5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var g5e={cacheSize:2e3,enableCache:!0},are=m5e({},g5e),d9=new u5e(are.cacheSize),b5e={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},u9="recharts_measurement_span";function x5e(t,e){var n=e.fontSize||"",r=e.fontFamily||"",i=e.fontWeight||"",s=e.fontStyle||"",o=e.letterSpacing||"",l=e.textTransform||"";return"".concat(t,"|").concat(n,"|").concat(r,"|").concat(i,"|").concat(s,"|").concat(o,"|").concat(l)}var m9=(t,e)=>{try{var n=document.getElementById(u9);n||(n=document.createElement("span"),n.setAttribute("id",u9),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,b5e,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},m0=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Xw.isSsr)return{width:0,height:0};if(!are.enableCache)return m9(e,n);var r=x5e(e,n),i=d9.get(r);if(i)return i;var s=m9(e,n);return d9.set(r,s),s},ire;function y5e(t,e,n){return(e=v5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function v5e(t){var e=w5e(t,"string");return typeof e=="symbol"?e:e+""}function w5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var h9=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,p9=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,S5e=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,_5e=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,k5e={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},N5e=["cm","mm","pt","pc","in","Q","px"];function C5e(t){return N5e.includes(t)}var Zb="NaN";function P5e(t,e){return t*k5e[e]}class ts{static parse(e){var n,[,r,i]=(n=_5e.exec(e))!==null&&n!==void 0?n:[];return r==null?ts.NaN:new ts(parseFloat(r),i??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Rc(e)&&(this.unit=""),n!==""&&!S5e.test(n)&&(this.num=NaN,this.unit=""),C5e(n)&&(this.num=P5e(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new ts(NaN,""):new ts(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new ts(NaN,""):new ts(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new ts(NaN,""):new ts(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new ts(NaN,""):new ts(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Rc(this.num)}}ire=ts;y5e(ts,"NaN",new ire(NaN,""));function sre(t){if(t==null||t.includes(Zb))return Zb;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,i,s]=(n=h9.exec(e))!==null&&n!==void 0?n:[],o=ts.parse(r??""),l=ts.parse(s??""),c=i==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return Zb;e=e.replace(h9,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var d,[,u,m,p]=(d=p9.exec(e))!==null&&d!==void 0?d:[],f=ts.parse(u??""),y=ts.parse(p??""),v=m==="+"?f.add(y):f.subtract(y);if(v.isNaN())return Zb;e=e.replace(p9,v.toString())}return e}var f9=/\(([^()]*)\)/;function T5e(t){for(var e=t,n;(n=f9.exec(e))!=null;){var[,r]=n;e=e.replace(f9,sre(r))}return e}function A5e(t){var e=t.replace(/\s+/g,"");return e=T5e(e),e=sre(e),e}function M5e(t){try{return A5e(t)}catch{return Zb}}function Q2(t){var e=M5e(t.slice(5,-1));return e===Zb?"":e}var j5e=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],E5e=["dx","dy","angle","className","breakAll"];function BR(){return BR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},BR.apply(null,arguments)}function g9(t,e){if(t==null)return{};var n,r,i=D5e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function D5e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var ore=/[ \f\n\r\t\v\u2028\u2029]+/,lre=t=>{var{children:e,breakAll:n,style:r}=t;try{var i=[];Sa(e)||(n?i=e.toString().split(""):i=e.toString().split(ore));var s=i.map(l=>({word:l,width:m0(l,r).width})),o=n?0:m0(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function F5e(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var cre=(t,e,n,r)=>t.reduce((i,s)=>{var{word:o,width:l}=s,c=i[i.length-1];if(c&&l!=null&&(e==null||r||c.width+l+n<Number(e)))c.words.push(o),c.width+=l+n;else{var d={words:[o],width:l};i.push(d)}return i},[]),dre=t=>t.reduce((e,n)=>e.width>n.width?e:n),R5e="…",b9=(t,e,n,r,i,s,o,l)=>{var c=t.slice(0,e),d=lre({breakAll:n,style:r,children:c+R5e});if(!d)return[!1,[]];var u=cre(d.wordsWithComputedWidth,s,o,l),m=u.length>i||dre(u).width>Number(s);return[m,u]},L5e=(t,e,n,r,i)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,d=on(s),u=String(o),m=cre(e,r,n,i);if(!d||i)return m;var p=m.length>s||dre(m).width>Number(r);if(!p)return m;for(var f=0,y=u.length-1,v=0,b;f<=y&&v<=u.length-1;){var g=Math.floor((f+y)/2),_=g-1,[k,P]=b9(u,_,c,l,s,r,n,i),[N]=b9(u,g,c,l,s,r,n,i);if(!k&&!N&&(f=g+1),k&&N&&(y=g-1),!k&&N){b=P;break}v++}return b||m},x9=t=>{var e=Sa(t)?[]:t.toString().split(ore);return[{words:e,width:void 0}]},O5e=t=>{var{width:e,scaleToFit:n,children:r,style:i,breakAll:s,maxLines:o}=t;if((e||n)&&!Xw.isSsr){var l,c,d=lre({breakAll:s,children:r,style:i});if(d){var{wordsWithComputedWidth:u,spaceWidth:m}=d;l=u,c=m}else return x9(r);return L5e({breakAll:s,children:r,maxLines:o,style:i},l,c,e,!!n)}return x9(r)},ure="#808080",I5e={angle:0,breakAll:!1,capHeight:"0.71em",fill:ure,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},NT=w.forwardRef((t,e)=>{var n=Ta(t,I5e),{x:r,y:i,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:d,verticalAnchor:u}=n,m=g9(n,j5e),p=w.useMemo(()=>O5e({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:y,angle:v,className:b,breakAll:g}=m,_=g9(m,E5e);if(!Jl(r)||!Jl(i)||p.length===0)return null;var k=Number(r)+(on(f)?f:0),P=Number(i)+(on(y)?y:0);if(!qn(k)||!qn(P))return null;var N;switch(u){case"start":N=Q2("calc(".concat(o,")"));break;case"middle":N=Q2("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:N=Q2("calc(".concat(p.length-1," * -").concat(s,")"));break}var M=[],A=p[0];if(c&&A!=null){var T=A.width,{width:C}=m;M.push("scale(".concat(on(C)&&on(T)?C/T:1,")"))}return v&&M.push("rotate(".concat(v,", ").concat(k,", ").concat(P,")")),M.length&&(_.transform=M.join(" ")),w.createElement("text",BR({},ms(_),{ref:e,x:k,y:P,className:wr("recharts-text",b),textAnchor:d,fill:l.includes("url")?ure:l}),p.map((F,$)=>{var I=F.words.join(g?"":" ");return w.createElement("tspan",{x:k,dy:$===0?N:s,key:"".concat(I,"-").concat($)},I)}))});NT.displayName="Text";function y9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function rd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?y9(Object(n),!0).forEach(function(r){z5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):y9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function z5e(t,e,n){return(e=U5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function U5e(t){var e=B5e(t,"string");return typeof e=="symbol"?e:e+""}function B5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var H5e=t=>{var{viewBox:e,position:n,offset:r=0,parentViewBox:i}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:d}=xI(e),u=s,m=s+(c-d)/2,p=(u+m)/2,f=(c+d)/2,y=u+c/2,v=l>=0?1:-1,b=v*r,g=v>0?"end":"start",_=v>0?"start":"end",k=c>=0?1:-1,P=k*r,N=k>0?"end":"start",M=k>0?"start":"end",A=i;if(n==="top"){var T={x:u+c/2,y:o-b,horizontalAnchor:"middle",verticalAnchor:g};return A&&(T.height=Math.max(o-A.y,0),T.width=c),T}if(n==="bottom"){var C={x:m+d/2,y:o+l+b,horizontalAnchor:"middle",verticalAnchor:_};return A&&(C.height=Math.max(A.y+A.height-(o+l),0),C.width=d),C}if(n==="left"){var F={x:p-P,y:o+l/2,horizontalAnchor:N,verticalAnchor:"middle"};return A&&(F.width=Math.max(F.x-A.x,0),F.height=l),F}if(n==="right"){var $={x:p+f+P,y:o+l/2,horizontalAnchor:M,verticalAnchor:"middle"};return A&&($.width=Math.max(A.x+A.width-$.x,0),$.height=l),$}var I=A?{width:f,height:l}:{};return n==="insideLeft"?rd({x:p+P,y:o+l/2,horizontalAnchor:M,verticalAnchor:"middle"},I):n==="insideRight"?rd({x:p+f-P,y:o+l/2,horizontalAnchor:N,verticalAnchor:"middle"},I):n==="insideTop"?rd({x:u+c/2,y:o+b,horizontalAnchor:"middle",verticalAnchor:_},I):n==="insideBottom"?rd({x:m+d/2,y:o+l-b,horizontalAnchor:"middle",verticalAnchor:g},I):n==="insideTopLeft"?rd({x:u+P,y:o+b,horizontalAnchor:M,verticalAnchor:_},I):n==="insideTopRight"?rd({x:u+c-P,y:o+b,horizontalAnchor:N,verticalAnchor:_},I):n==="insideBottomLeft"?rd({x:m+P,y:o+l-b,horizontalAnchor:M,verticalAnchor:g},I):n==="insideBottomRight"?rd({x:m+d-P,y:o+l-b,horizontalAnchor:N,verticalAnchor:g},I):n&&typeof n=="object"&&(on(n.x)||Xf(n.x))&&(on(n.y)||Xf(n.y))?rd({x:s+Es(n.x,f),y:o+Es(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},I):rd({x:y,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},I)},q5e=["labelRef"],$5e=["content"];function v9(t,e){if(t==null)return{};var n,r,i=V5e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function V5e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function w9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Yv(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?w9(Object(n),!0).forEach(function(r){G5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):w9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function G5e(t,e,n){return(e=W5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function W5e(t){var e=K5e(t,"string");return typeof e=="symbol"?e:e+""}function K5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Nu(){return Nu=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Nu.apply(null,arguments)}var mre=w.createContext(null),hre=t=>{var{x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o,children:l}=t,c=w.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o}),[e,n,r,i,s,o]);return w.createElement(mre.Provider,{value:c},l)},pre=()=>{var t=w.useContext(mre),e=Ww();return t||(e?xI(e):void 0)},Y5e=w.createContext(null),X5e=()=>{var t=w.useContext(Y5e),e=dn(tne);return t||e},Q5e=t=>{var{value:e,formatter:n}=t,r=Sa(t.children)?e:t.children;return typeof n=="function"?n(r):r},D4=t=>t!=null&&typeof t=="function",Z5e=(t,e)=>{var n=Li(e-t),r=Math.min(Math.abs(e-t),360);return n*r},J5e=(t,e,n,r,i)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:d,outerRadius:u,startAngle:m,endAngle:p,clockWise:f}=i,y=(d+u)/2,v=Z5e(m,p),b=v>=0?1:-1,g,_;switch(e){case"insideStart":g=m+b*s,_=f;break;case"insideEnd":g=p-b*s,_=!f;break;case"end":g=p+b*s,_=f;break;default:throw new Error("Unsupported position ".concat(e))}_=v<=0?_:!_;var k=oi(l,c,y,g),P=oi(l,c,y,g+(_?1:-1)*359),N="M".concat(k.x,",").concat(k.y,`
  8122. A`).concat(y,",").concat(y,",0,1,").concat(_?0:1,`,
  8123. `).concat(P.x,",").concat(P.y),M=Sa(t.id)?K0("recharts-radial-line-"):t.id;return w.createElement("text",Nu({},r,{dominantBaseline:"central",className:wr("recharts-radial-bar-label",o)}),w.createElement("defs",null,w.createElement("path",{id:M,d:N})),w.createElement("textPath",{xlinkHref:"#".concat(M)},n))},eUe=(t,e,n)=>{var{cx:r,cy:i,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,d=(l+c)/2;if(n==="outside"){var{x:u,y:m}=oi(r,i,o+e,d);return{x:u,y:m,textAnchor:u>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:f,y}=oi(r,i,p,d);return{x:f,y,textAnchor:"middle",verticalAnchor:"middle"}},Dk=t=>t!=null&&"cx"in t&&on(t.cx),tUe={angle:0,offset:5,zIndex:Ha.label,position:"middle",textBreakAll:!1};function nUe(t){if(!Dk(t))return t;var{cx:e,cy:n,outerRadius:r}=t,i=r*2;return{x:e-r,y:n-r,width:i,upperWidth:i,lowerWidth:i,height:i}}function sh(t){var e=Ta(t,tUe),{viewBox:n,parentViewBox:r,position:i,value:s,children:o,content:l,className:c="",textBreakAll:d,labelRef:u}=e,m=X5e(),p=pre(),f=i==="center"?p:m??p,y,v,b;n==null?y=f:Dk(n)?y=n:y=xI(n);var g=nUe(y);if(!y||Sa(s)&&Sa(o)&&!w.isValidElement(l)&&typeof l!="function")return null;var _=Yv(Yv({},e),{},{viewBox:y});if(w.isValidElement(l)){var{labelRef:k}=_,P=v9(_,q5e);return w.cloneElement(l,P)}if(typeof l=="function"){var{content:N}=_,M=v9(_,$5e);if(v=w.createElement(l,M),w.isValidElement(v))return v}else v=Q5e(e);var A=ms(e);if(Dk(y)){if(i==="insideStart"||i==="insideEnd"||i==="end")return J5e(e,i,v,A,y);b=eUe(y,e.offset,e.position)}else{if(!g)return null;var T=H5e({viewBox:g,position:i,offset:e.offset,parentViewBox:Dk(r)?void 0:r});b=Yv(Yv({x:T.x,y:T.y,textAnchor:T.horizontalAnchor,verticalAnchor:T.verticalAnchor},T.width!==void 0?{width:T.width}:{}),T.height!==void 0?{height:T.height}:{})}return w.createElement(Ls,{zIndex:e.zIndex},w.createElement(NT,Nu({ref:u,className:wr("recharts-label",c)},A,b,{textAnchor:F5e(A.textAnchor)?A.textAnchor:b.textAnchor,breakAll:d}),v))}sh.displayName="Label";var rUe=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?w.createElement(sh,Nu({key:"label-implicit"},r)):Jl(t)?w.createElement(sh,Nu({key:"label-implicit",value:t},r)):w.isValidElement(t)?t.type===sh?w.cloneElement(t,Yv({key:"label-implicit"},r)):w.createElement(sh,Nu({key:"label-implicit",content:t},r)):D4(t)?w.createElement(sh,Nu({key:"label-implicit",content:t},r)):t&&typeof t=="object"?w.createElement(sh,Nu({},t,{key:"label-implicit"},r)):null};function fre(t){var{label:e,labelRef:n}=t,r=pre();return rUe(e,r,n)||null}var Z2={},J2={},S9;function aUe(){return S9||(S9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(J2)),J2}var eD={},_9;function iUe(){return _9||(_9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(eD)),eD}var k9;function sUe(){return k9||(k9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aUe(),n=iUe(),r=oI();function i(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=i})(Z2)),Z2}var tD,N9;function oUe(){return N9||(N9=1,tD=sUe().last),tD}var lUe=oUe();const cUe=rc(lUe);var dUe=["valueAccessor"],uUe=["dataKey","clockWise","id","textBreakAll","zIndex"];function cC(){return cC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},cC.apply(null,arguments)}function C9(t,e){if(t==null)return{};var n,r,i=mUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function mUe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var hUe=t=>Array.isArray(t.value)?cUe(t.value):t.value,gre=w.createContext(void 0),F4=gre.Provider,bre=w.createContext(void 0),pUe=bre.Provider;function fUe(){return w.useContext(gre)}function gUe(){return w.useContext(bre)}function Fk(t){var{valueAccessor:e=hUe}=t,n=C9(t,dUe),{dataKey:r,clockWise:i,id:s,textBreakAll:o,zIndex:l}=n,c=C9(n,uUe),d=fUe(),u=gUe(),m=d||u;return!m||!m.length?null:w.createElement(Ls,{zIndex:l??Ha.label},w.createElement(Pa,{className:"recharts-label-list"},m.map((p,f)=>{var y,v=Sa(r)?e(p,f):Dr(p.payload,r),b=Sa(s)?{}:{id:"".concat(s,"-").concat(f)};return w.createElement(sh,cC({key:"label-".concat(f)},ms(p),c,b,{fill:(y=n.fill)!==null&&y!==void 0?y:p.fill,parentViewBox:p.parentViewBox,value:v,textBreakAll:o,viewBox:p.viewBox,index:f,zIndex:0}))})))}Fk.displayName="LabelList";function CT(t){var{label:e}=t;return e?e===!0?w.createElement(Fk,{key:"labelList-implicit"}):w.isValidElement(e)||D4(e)?w.createElement(Fk,{key:"labelList-implicit",content:e}):typeof e=="object"?w.createElement(Fk,cC({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function HR(){return HR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},HR.apply(null,arguments)}var xre=t=>{var{cx:e,cy:n,r,className:i}=t,s=wr("recharts-dot",i);return on(e)&&on(n)&&on(r)?w.createElement("circle",HR({},to(t),sI(t),{className:s,cx:e,cy:n,r})):null},yre=t=>t.graphicalItems.polarItems,bUe=yt([Aa,nS],r4),PT=yt([yre,Wa,bUe],a4),xUe=yt([PT],i4),TT=yt([xUe,mT],s4),yUe=yt([TT,Wa,PT],l4);yt([TT,Wa,PT],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(i=>{var s,o=Dr(r,(s=e.dataKey)!==null&&s!==void 0?s:i.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:Dr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var P9=()=>{},vUe=yt([TT,Wa,PT,wT,Aa],m4),wUe=yt([Wa,d4,u4,P9,vUe,P9,yr,Aa],h4),vre=yt([Wa,yr,TT,yUe,tS,Aa,wUe],p4),SUe=yt([vre,py,sp],b4),_Ue=yt([Wa,vre,SUe,Aa],y4);yt([sp,_Ue],rne);var kUe={radiusAxis:{},angleAxis:{}},wre=Do({name:"polarAxis",initialState:kUe,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:jit,removeRadiusAxis:Eit,addAngleAxis:Dit,removeAngleAxis:Fit}=wre.actions,NUe=wre.reducer;function Sre(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function T9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function A9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?T9(Object(n),!0).forEach(function(r){CUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):T9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function CUe(t,e,n){return(e=PUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function PUe(t){var e=TUe(t,"string");return typeof e=="symbol"?e:e+""}function TUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var AUe=(t,e)=>e,R4=yt([yre,AUe],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),MUe=[],L4=(t,e,n)=>n?.length===0?MUe:n,_re=yt([mT,R4,L4],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var i;if(e?.data!=null&&e.data.length>0?i=e.data:i=r,(!i||!i.length)&&n!=null&&(i=n.map(s=>A9(A9({},e.presentationProps),s.props))),i!=null)return i}}),jUe=yt([_re,R4,L4],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,i)=>{var s,o=Dr(r,e.nameKey,e.name),l;return n!=null&&(s=n[i])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[i].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:np(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),EUe=yt([_re,R4,L4,wi],(t,e,n,r)=>{if(!(e==null||t==null))return DBe({offset:r,pieSettings:e,displayedData:t,cells:n})}),nD={exports:{}},Br={};var M9;function DUe(){if(M9)return Br;M9=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),f=Symbol.for("react.client.reference");function y(v){if(typeof v=="object"&&v!==null){var b=v.$$typeof;switch(b){case t:switch(v=v.type,v){case n:case i:case r:case c:case d:case p:return v;default:switch(v=v&&v.$$typeof,v){case o:case l:case m:case u:return v;case s:return v;default:return b}}case e:return b}}}return Br.ContextConsumer=s,Br.ContextProvider=o,Br.Element=t,Br.ForwardRef=l,Br.Fragment=n,Br.Lazy=m,Br.Memo=u,Br.Portal=e,Br.Profiler=i,Br.StrictMode=r,Br.Suspense=c,Br.SuspenseList=d,Br.isContextConsumer=function(v){return y(v)===s},Br.isContextProvider=function(v){return y(v)===o},Br.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===t},Br.isForwardRef=function(v){return y(v)===l},Br.isFragment=function(v){return y(v)===n},Br.isLazy=function(v){return y(v)===m},Br.isMemo=function(v){return y(v)===u},Br.isPortal=function(v){return y(v)===e},Br.isProfiler=function(v){return y(v)===i},Br.isStrictMode=function(v){return y(v)===r},Br.isSuspense=function(v){return y(v)===c},Br.isSuspenseList=function(v){return y(v)===d},Br.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===i||v===r||v===c||v===d||typeof v=="object"&&v!==null&&(v.$$typeof===m||v.$$typeof===u||v.$$typeof===o||v.$$typeof===s||v.$$typeof===l||v.$$typeof===f||v.getModuleId!==void 0)},Br.typeOf=y,Br}var j9;function FUe(){return j9||(j9=1,nD.exports=DUe()),nD.exports}var RUe=FUe(),E9=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",D9=null,rD=null,kre=t=>{if(t===D9&&Array.isArray(rD))return rD;var e=[];return w.Children.forEach(t,n=>{Sa(n)||(RUe.isFragment(n)?e=e.concat(kre(n.props.children)):e.push(n))}),rD=e,D9=t,e};function O4(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(i=>E9(i)):r=[E9(e)],kre(t).forEach(i=>{var s=Yf(i,"type.displayName")||Yf(i,"type.name");s&&r.indexOf(s)!==-1&&n.push(i)}),n}var I4=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,aD={},F9;function LUe(){return F9||(F9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(typeof n!="object"||n==null)return!1;if(Object.getPrototypeOf(n)===null)return!0;if(Object.prototype.toString.call(n)!=="[object Object]"){const i=n[Symbol.toStringTag];return i==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${i}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})(aD)),aD}var iD,R9;function OUe(){return R9||(R9=1,iD=LUe().isPlainObject),iD}var IUe=OUe();const zUe=rc(IUe);var L9,O9,I9,z9,U9;function B9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function H9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?B9(Object(n),!0).forEach(function(r){UUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):B9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function UUe(t,e,n){return(e=BUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function BUe(t){var e=HUe(t,"string");return typeof e=="symbol"?e:e+""}function HUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function dC(){return dC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},dC.apply(null,arguments)}function Dv(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var q9=(t,e,n,r,i)=>{var s=n-r,o;return o=Oa(L9||(L9=Dv(["M ",",",""])),t,e),o+=Oa(O9||(O9=Dv(["L ",",",""])),t+n,e),o+=Oa(I9||(I9=Dv(["L ",",",""])),t+n-s/2,e+i),o+=Oa(z9||(z9=Dv(["L ",",",""])),t+n-s/2-r,e+i),o+=Oa(U9||(U9=Dv(["L ",","," Z"])),t,e),o},qUe={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},$Ue=t=>{var e=Ta(t,qUe),{x:n,y:r,upperWidth:i,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:d,animationBegin:u,isUpdateAnimationActive:m}=e,p=w.useRef(null),[f,y]=w.useState(-1),v=w.useRef(i),b=w.useRef(s),g=w.useRef(o),_=w.useRef(n),k=w.useRef(r),P=cy(t,"trapezoid-");if(w.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var L=p.current.getTotalLength();L&&y(L)}catch{}},[]),n!==+n||r!==+r||i!==+i||s!==+s||o!==+o||i===0&&s===0||o===0)return null;var N=wr("recharts-trapezoid",l);if(!m)return w.createElement("g",null,w.createElement("path",dC({},ms(e),{className:N,d:q9(n,r,i,s,o)})));var M=v.current,A=b.current,T=g.current,C=_.current,F=k.current,$="0px ".concat(f===-1?1:f,"px"),I="".concat(f,"px 0px"),X=Gee(["strokeDasharray"],d,c);return w.createElement(ly,{animationId:P,key:P,canBegin:f>0,duration:d,easing:c,isActive:m,begin:u},L=>{var te=Er(M,i,L),ae=Er(A,s,L),ee=Er(T,o,L),me=Er(C,n,L),le=Er(F,r,L);p.current&&(v.current=te,b.current=ae,g.current=ee,_.current=me,k.current=le);var ue=L>0?{transition:X,strokeDasharray:I}:{strokeDasharray:$};return w.createElement("path",dC({},ms(e),{className:N,d:q9(me,le,te,ae,ee),ref:p,style:H9(H9({},ue),e.style)}))})},VUe=["option","shapeType","activeClassName"];function GUe(t,e){if(t==null)return{};var n,r,i=WUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function WUe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function $9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function uC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?$9(Object(n),!0).forEach(function(r){KUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):$9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function KUe(t,e,n){return(e=YUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function YUe(t){var e=XUe(t,"string");return typeof e=="symbol"?e:e+""}function XUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function QUe(t,e){return uC(uC({},e),t)}function ZUe(t,e){return t==="symbols"}function V9(t){var{shapeType:e,elementProps:n}=t;switch(e){case"rectangle":return w.createElement(Xee,n);case"trapezoid":return w.createElement($Ue,n);case"sector":return w.createElement(ete,n);case"symbols":if(ZUe(e))return w.createElement(iI,n);break;case"curve":return w.createElement(dx,n);default:return null}}function JUe(t){return w.isValidElement(t)?t.props:t}function z4(t){var{option:e,shapeType:n,activeClassName:r="recharts-active-shape"}=t,i=GUe(t,VUe),s;if(w.isValidElement(e))s=w.cloneElement(e,uC(uC({},i),JUe(e)));else if(typeof e=="function")s=e(i,i.index);else if(zUe(e)&&typeof e!="boolean"){var o=QUe(e,i);s=w.createElement(V9,{shapeType:n,elementProps:o})}else{var l=i;s=w.createElement(V9,{shapeType:n,elementProps:l})}return i.isActive?w.createElement(Pa,{className:r},s):s}var U4=(t,e,n)=>{var r=ta();return(i,s)=>o=>{t?.(i,s,o),r(Dne({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}},B4=t=>{var e=ta();return(n,r)=>i=>{t?.(n,r,i),e(a4e())}},H4=(t,e,n)=>{var r=ta();return(i,s)=>o=>{t?.(i,s,o),r(i4e({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}};function AT(t){var{tooltipEntrySettings:e}=t,n=ta(),r=Si(),i=w.useRef(null);return w.useLayoutEffect(()=>{r||(i.current===null?n(e4e(e)):i.current!==e&&n(t4e({prev:i.current,next:e})),i.current=e)},[e,n,r]),w.useLayoutEffect(()=>()=>{i.current&&(n(n4e(i.current)),i.current=null)},[n]),null}function q4(t){var{legendPayload:e}=t,n=ta(),r=Si(),i=w.useRef(null);return w.useLayoutEffect(()=>{r||(i.current===null?n(Bee(e)):i.current!==e&&n(Hee({prev:i.current,next:e})),i.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{i.current&&(n(qee(i.current)),i.current=null)},[n]),null}function eBe(t){var{legendPayload:e}=t,n=ta(),r=dn(yr),i=w.useRef(null);return w.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(i.current===null?n(Bee(e)):i.current!==e&&n(Hee({prev:i.current,next:e})),i.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{i.current&&(n(qee(i.current)),i.current=null)},[n]),null}var sD,tBe=()=>{var[t]=w.useState(()=>K0("uid-"));return t},nBe=(sD=gde.useId)!==null&&sD!==void 0?sD:tBe;function rBe(t,e){var n=nBe();return e||(t?"".concat(t,"-").concat(n):n)}var aBe=w.createContext(void 0),MT=t=>{var{id:e,type:n,children:r}=t,i=rBe("recharts-".concat(n),e);return w.createElement(aBe.Provider,{value:i},r(i))},iBe={cartesianItems:[],polarItems:[]},Nre=Do({name:"graphicalItems",initialState:iBe,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:ba()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,i=jc(t).cartesianItems.indexOf(n);i>-1&&(t.cartesianItems[i]=r)},prepare:ba()},removeCartesianGraphicalItem:{reducer(t,e){var n=jc(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:ba()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:ba()},removePolarGraphicalItem:{reducer(t,e){var n=jc(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:ba()}}}),{addCartesianGraphicalItem:sBe,replaceCartesianGraphicalItem:oBe,removeCartesianGraphicalItem:lBe,addPolarGraphicalItem:cBe,removePolarGraphicalItem:dBe}=Nre.actions,uBe=Nre.reducer,mBe=t=>{var e=ta(),n=w.useRef(null);return w.useLayoutEffect(()=>{n.current===null?e(sBe(t)):n.current!==t&&e(oBe({prev:n.current,next:t})),n.current=t},[e,t]),w.useLayoutEffect(()=>()=>{n.current&&(e(lBe(n.current)),n.current=null)},[e]),null},$4=w.memo(mBe);function hBe(t){var e=ta();return w.useLayoutEffect(()=>(e(cBe(t)),()=>{e(dBe(t))}),[e,t]),null}var pBe=["key"],fBe=["onMouseEnter","onClick","onMouseLeave"],gBe=["id"],bBe=["id"];function G9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ia(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?G9(Object(n),!0).forEach(function(r){xBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):G9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Xh(){return Xh=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Xh.apply(null,arguments)}function jT(t,e){if(t==null)return{};var n,r,i=wBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function wBe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function SBe(t){var e=w.useMemo(()=>O4(t.children,zx),[t.children]),n=dn(r=>jUe(r,t.id,e));return n==null?null:w.createElement(eBe,{legendPayload:n})}var _Be=w.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:i,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:r.map(p=>p.tooltipPayload),getPosition:p=>{var f;return(f=r[Number(p)])===null||f===void 0?void 0:f.tooltipPosition},settings:{stroke:i,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:np(l,e),hide:c,type:d,color:o,unit:"",graphicalItemId:u}};return w.createElement(AT,{tooltipEntrySettings:m})}),kBe=(t,e)=>t>e?"start":t<e?"end":"middle",NBe=(t,e,n)=>Es(typeof e=="function"?e(t):e,n,n*.8),CBe=(t,e,n)=>{var{top:r,left:i,width:s,height:o}=e,l=Qee(s,o),c=i+Es(t.cx,s,s/2),d=r+Es(t.cy,o,o/2),u=Es(t.innerRadius,l,0),m=NBe(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}},PBe=(t,e)=>{var n=Li(e-t),r=Math.min(Math.abs(e-t),360);return n*r},TBe=(t,e)=>{if(w.isValidElement(t))return w.cloneElement(t,e);if(typeof t=="function")return t(e);var n=wr("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,i=jT(e,pBe);return w.createElement(dx,Xh({},i,{type:"linear",className:n}))},ABe=(t,e,n)=>{if(w.isValidElement(t))return w.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),w.isValidElement(r)))return r;var i=wr("recharts-pie-label-text",Sre(t));return w.createElement(NT,Xh({},e,{alignmentBaseline:"middle",className:i}),r)};function MBe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i,labelLine:s,dataKey:o}=n;if(!r||!i||!e)return null;var l=to(n),c=Wf(i),d=Wf(s),u=typeof i=="object"&&"offsetRadius"in i&&typeof i.offsetRadius=="number"&&i.offsetRadius||20,m=e.map((p,f)=>{var y=(p.startAngle+p.endAngle)/2,v=oi(p.cx,p.cy,p.outerRadius+u,y),b=Ia(Ia(Ia(Ia({},l),p),{},{stroke:"none"},c),{},{index:f,textAnchor:kBe(v.x,p.cx)},v),g=Ia(Ia(Ia(Ia({},l),p),{},{fill:"none",stroke:p.fill},d),{},{index:f,points:[oi(p.cx,p.cy,p.outerRadius,y),v],key:"line"});return w.createElement(Ls,{zIndex:Ha.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(f)},w.createElement(Pa,null,s&&TBe(s,g),ABe(i,b,Dr(p,o))))});return w.createElement(Pa,{className:"recharts-pie-labels"},m)}function jBe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i}=n;return typeof i=="object"&&i!=null&&"position"in i?w.createElement(CT,{label:i}):w.createElement(MBe,{sectors:e,props:n,showLabels:r})}function EBe(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:i,shape:s,id:o}=t,l=dn(Yh),c=dn(T4),d=dn($4e),{onMouseEnter:u,onClick:m,onMouseLeave:p}=i,f=jT(i,fBe),y=U4(u,i.dataKey,o),v=B4(p),b=H4(m,i.dataKey,o);return e==null||e.length===0?null:w.createElement(w.Fragment,null,e.map((g,_)=>{if(g?.startAngle===0&&g?.endAngle===0&&e.length!==1)return null;var k=d==null||d===o,P=String(_)===l&&(c==null||i.dataKey===c)&&k,N=l?r:null,M=n&&P?n:N,A=Ia(Ia({},g),{},{stroke:g.stroke,tabIndex:-1,[Pee]:_,[Tee]:o});return w.createElement(Pa,Xh({key:"sector-".concat(g?.startAngle,"-").concat(g?.endAngle,"-").concat(g.midAngle,"-").concat(_),tabIndex:-1,className:"recharts-pie-sector"},qw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),w.createElement(z4,Xh({option:s??M,index:_,shapeType:"sector",isActive:P},A)))}))}function DBe(t){var e,{pieSettings:n,displayedData:r,cells:i,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:d,nameKey:u,tooltipType:m}=n,p=Math.abs(n.minAngle),f=PBe(l,c),y=Math.abs(f),v=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,b=r.filter(M=>Dr(M,d,0)!==0).length,g=(y>=360?b:b-1)*v,_=y-b*p-g,k=r.reduce((M,A)=>{var T=Dr(A,d,0);return M+(on(T)?T:0)},0),P;if(k>0){var N;P=r.map((M,A)=>{var T=Dr(M,d,0),C=Dr(M,u,A),F=CBe(n,s,M),$=(on(T)?T:0)/k,I,X=Ia(Ia({},M),i&&i[A]&&i[A].props);A?I=N.endAngle+Li(f)*v*(T!==0?1:0):I=l;var L=I+Li(f)*((T!==0?p:0)+$*_),te=(I+L)/2,ae=(F.innerRadius+F.outerRadius)/2,ee=[{name:C,value:T,payload:X,dataKey:d,type:m,graphicalItemId:n.id}],me=oi(F.cx,F.cy,ae,te);return N=Ia(Ia(Ia(Ia({},n.presentationProps),{},{percent:$,cornerRadius:typeof o=="string"?parseFloat(o):o,name:C,tooltipPayload:ee,midAngle:te,middleRadius:ae,tooltipPosition:me},X),F),{},{value:T,dataKey:d,startAngle:I,endAngle:L,payload:X,paddingAngle:Li(f)*v}),N})}return P}function FBe(t){var{showLabels:e,sectors:n,children:r}=t,i=w.useMemo(()=>!e||!n?[]:n.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[n,e]);return w.createElement(pUe,{value:e?i:void 0},r)}function RBe(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:d,inactiveShape:u,onAnimationStart:m,onAnimationEnd:p}=e,f=cy(e,"recharts-pie-"),y=n.current,[v,b]=w.useState(!1),g=w.useCallback(()=>{typeof p=="function"&&p(),b(!1)},[p]),_=w.useCallback(()=>{typeof m=="function"&&m(),b(!0)},[m]);return w.createElement(FBe,{showLabels:!v,sectors:i},w.createElement(ly,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:_,onAnimationEnd:g,key:f},k=>{var P,N=[],M=i&&i[0],A=(P=M?.startAngle)!==null&&P!==void 0?P:0;return i?.forEach((T,C)=>{var F=y&&y[C],$=C>0?Yf(T,"paddingAngle",0):0;if(F){var I=Er(F.endAngle-F.startAngle,T.endAngle-T.startAngle,k),X=Ia(Ia({},T),{},{startAngle:A+$,endAngle:A+I+$});N.push(X),A=X.endAngle}else{var{endAngle:L,startAngle:te}=T,ae=Er(0,L-te,k),ee=Ia(Ia({},T),{},{startAngle:A+$,endAngle:A+ae+$});N.push(ee),A=ee.endAngle}}),n.current=N,w.createElement(Pa,null,w.createElement(EBe,{sectors:N,activeShape:d,inactiveShape:u,allOtherPieProps:e,shape:e.shape,id:r}))}),w.createElement(jBe,{showLabels:!v,sectors:i,props:e}),e.children)}var LBe={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:Ha.area};function OBe(t){var{id:e}=t,n=jT(t,gBe),{hide:r,className:i,rootTabIndex:s}=t,o=w.useMemo(()=>O4(t.children,zx),[t.children]),l=dn(u=>EUe(u,e,o)),c=w.useRef(null),d=wr("recharts-pie",i);return r||l==null?(c.current=null,w.createElement(Pa,{tabIndex:s,className:d})):w.createElement(Ls,{zIndex:t.zIndex},w.createElement(_Be,{dataKey:t.dataKey,nameKey:t.nameKey,sectors:l,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,tooltipType:t.tooltipType,id:e}),w.createElement(Pa,{tabIndex:s,className:d},w.createElement(RBe,{props:Ia(Ia({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function qR(t){var e=Ta(t,LBe),{id:n}=e,r=jT(e,bBe),i=to(r);return w.createElement(MT,{id:n,type:"pie"},s=>w.createElement(w.Fragment,null,w.createElement(hBe,{type:"pie",id:s,data:r.data,dataKey:r.dataKey,hide:r.hide,angleAxisId:0,radiusAxisId:0,name:r.name,nameKey:r.nameKey,tooltipType:r.tooltipType,legendType:r.legendType,fill:r.fill,cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,paddingAngle:r.paddingAngle,minAngle:r.minAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius,cornerRadius:r.cornerRadius,presentationProps:i,maxRadius:e.maxRadius}),w.createElement(SBe,Xh({},r,{id:s})),w.createElement(OBe,Xh({},r,{id:s}))))}qR.displayName="Pie";var IBe=["points"];function W9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function oD(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?W9(Object(n),!0).forEach(function(r){zBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):W9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function zBe(t,e,n){return(e=UBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function UBe(t){var e=BBe(t,"string");return typeof e=="symbol"?e:e+""}function BBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function mC(){return mC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},mC.apply(null,arguments)}function HBe(t,e){if(t==null)return{};var n,r,i=qBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function qBe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function $Be(t){var{option:e,dotProps:n,className:r}=t;if(w.isValidElement(e))return w.cloneElement(e,n);if(typeof e=="function")return e(n);var i=wr(r,typeof e!="boolean"?e.className:""),s=n??{},{points:o}=s,l=HBe(s,IBe);return w.createElement(xre,mC({},l,{className:i}))}function VBe(t,e){return t==null?!1:e?!0:t.length===1}function Cre(t){var{points:e,dot:n,className:r,dotClassName:i,dataKey:s,baseProps:o,needClip:l,clipPathId:c,zIndex:d=Ha.scatter}=t;if(!VBe(e,n))return null;var u=I4(n),m=hje(n),p=e.map((y,v)=>{var b,g,_=oD(oD(oD({r:3},o),m),{},{index:v,cx:(b=y.x)!==null&&b!==void 0?b:void 0,cy:(g=y.y)!==null&&g!==void 0?g:void 0,dataKey:s,value:y.value,payload:y.payload,points:e});return w.createElement($Be,{key:"dot-".concat(v),option:n,dotProps:_,className:i})}),f={};return l&&c!=null&&(f.clipPath="url(#clipPath-".concat(u?"":"dots-").concat(c,")")),w.createElement(Ls,{zIndex:d},w.createElement(Pa,mC({className:r},f),p))}function K9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Y9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?K9(Object(n),!0).forEach(function(r){GBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):K9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function GBe(t,e,n){return(e=WBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function WBe(t){var e=KBe(t,"string");return typeof e=="symbol"?e:e+""}function KBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Pre=0,YBe={xAxis:{},yAxis:{},zAxis:{}},Tre=Do({name:"cartesianAxis",initialState:YBe,reducers:{addXAxis:{reducer(t,e){t.xAxis[e.payload.id]=e.payload},prepare:ba()},replaceXAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.xAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.xAxis[n.id],t.xAxis[r.id]=r)},prepare:ba()},removeXAxis:{reducer(t,e){delete t.xAxis[e.payload.id]},prepare:ba()},addYAxis:{reducer(t,e){t.yAxis[e.payload.id]=e.payload},prepare:ba()},replaceYAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.yAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.yAxis[n.id],t.yAxis[r.id]=r)},prepare:ba()},removeYAxis:{reducer(t,e){delete t.yAxis[e.payload.id]},prepare:ba()},addZAxis:{reducer(t,e){t.zAxis[e.payload.id]=e.payload},prepare:ba()},replaceZAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.zAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.zAxis[n.id],t.zAxis[r.id]=r)},prepare:ba()},removeZAxis:{reducer(t,e){delete t.zAxis[e.payload.id]},prepare:ba()},updateYAxisWidth(t,e){var{id:n,width:r}=e.payload,i=t.yAxis[n];if(i){var s,o=i.widthHistory||[];if(o.length===3&&o[0]===o[2]&&r===o[1]&&r!==i.width&&Math.abs(r-((s=o[0])!==null&&s!==void 0?s:0))<=1)return;var l=[...o,r].slice(-3);t.yAxis[n]=Y9(Y9({},i),{},{width:r,widthHistory:l})}}}}),{addXAxis:XBe,replaceXAxis:QBe,removeXAxis:ZBe,addYAxis:JBe,replaceYAxis:e8e,removeYAxis:t8e,addZAxis:Rit,replaceZAxis:Lit,removeZAxis:Oit,updateYAxisWidth:n8e}=Tre.actions,r8e=Tre.reducer,a8e=yt([wi],t=>({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),i8e=yt([a8e,sm,om],(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)}}),ET=()=>dn(i8e),s8e=()=>dn(Y4e);function X9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function lD(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?X9(Object(n),!0).forEach(function(r){o8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):X9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function o8e(t,e,n){return(e=l8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l8e(t){var e=c8e(t,"string");return typeof e=="symbol"?e:e+""}function c8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var d8e=t=>{var{point:e,childIndex:n,mainColor:r,activeDot:i,dataKey:s,clipPath:o}=t;if(i===!1||e.x==null||e.y==null)return null;var l={index:n,dataKey:s,cx:e.x,cy:e.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:e.payload,value:e.value},c=lD(lD(lD({},l),Wf(i)),sI(i)),d;return w.isValidElement(i)?d=w.cloneElement(i,c):typeof i=="function"?d=i(c):d=w.createElement(xre,c),w.createElement(Pa,{className:"recharts-active-dot",clipPath:o},d)};function $R(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:i,clipPath:s,zIndex:o=Ha.activeDot}=t,l=dn(Yh),c=s8e();if(e==null||c==null)return null;var d=e.find(u=>c.includes(u.payload));return Sa(d)?null:w.createElement(Ls,{zIndex:o},w.createElement(d8e,{point:d,childIndex:Number(l),mainColor:n,dataKey:i,activeDot:r,clipPath:s}))}var Q9=(t,e,n)=>{var r=n??t;if(!Sa(r))return Es(r,e,0)},u8e=(t,e,n)=>{var r={},i=t.filter(bT),s=t.filter(d=>d.stackId==null),o=i.reduce((d,u)=>{var m=d[u.stackId];return m==null&&(m=[]),m.push(u),d[u.stackId]=m,d},r),l=Object.entries(o).map(d=>{var u,[m,p]=d,f=p.map(v=>v.dataKey),y=Q9(e,n,(u=p[0])===null||u===void 0?void 0:u.barSize);return{stackId:m,dataKeys:f,barSize:y}}),c=s.map(d=>{var u=[d.dataKey].filter(p=>p!=null),m=Q9(e,n,d.barSize);return{stackId:void 0,dataKeys:u,barSize:m}});return[...l,...c]};function Z9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function V1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Z9(Object(n),!0).forEach(function(r){m8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Z9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function m8e(t,e,n){return(e=h8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function h8e(t){var e=p8e(t,"string");return typeof e=="symbol"?e:e+""}function p8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function f8e(t,e,n,r,i){var s,o=r.length;if(!(o<1)){var l=Es(t,n,0,!0),c,d=[];if(qn((s=r[0])===null||s===void 0?void 0:s.barSize)){var u=!1,m=n/o,p=r.reduce((_,k)=>_+(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,y={offset:f-l,size:0};c=r.reduce((_,k)=>{var P,N={stackId:k.stackId,dataKeys:k.dataKeys,position:{offset:y.offset+y.size+l,size:u?m:(P=k.barSize)!==null&&P!==void 0?P:0}},M=[..._,N];return y=N.position,M},d)}else{var v=Es(e,n,0,!0);n-2*v-(o-1)*l<=0&&(l=0);var b=(n-2*v-(o-1)*l)/o;b>1&&(b>>=0);var g=qn(i)?Math.min(b,i):b;c=r.reduce((_,k,P)=>[..._,{stackId:k.stackId,dataKeys:k.dataKeys,position:{offset:v+(b+l)*P+(b-g)/2,size:g}}],d)}return c}}var g8e=(t,e,n,r,i,s,o)=>{var l=Sa(o)?e:o,c=f8e(n,r,i!==s?i:s,t,l);return i!==s&&c!=null&&(c=c.map(d=>V1(V1({},d),{},{position:V1(V1({},d.position),{},{offset:d.position.offset-i/2})}))),c},b8e=(t,e)=>{var n=gT(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var i=t[r];if(i){var{stackedData:s}=i;if(s)return s.find(o=>o.key===n)}}}},x8e=(t,e)=>{if(!(t==null||e==null)){var n=t.find(r=>r.stackId===e.stackId&&e.dataKey!=null&&r.dataKeys.includes(e.dataKey));if(n!=null)return n.position}};function y8e(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&qn(t.zIndex)?t.zIndex:e}var Are=t=>{var{chartData:e}=t,n=ta(),r=Si();return w.useEffect(()=>r?()=>{}:(n(a9(e)),()=>{n(a9(void 0))}),[e,n,r]),null},J9={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},Mre=Do({name:"brush",initialState:J9,reducers:{setBrushSettings(t,e){return e.payload==null?J9:e.payload}}}),{setBrushSettings:Iit}=Mre.actions,v8e=Mre.reducer,w8e=(t,e)=>{var{x:n,y:r}=t,{x:i,y:s}=e;return{x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},S8e=t=>{var{x1:e,y1:n,x2:r,y2:i}=t;return w8e({x:e,y:n},{x:r,y:i})};function _8e(t){return(t%180+180)%180}var k8e=function(e){var{width:n,height:r}=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=_8e(i),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o<Math.PI-l?r/Math.sin(o):n/Math.cos(o);return Math.abs(c)},N8e={dots:[],areas:[],lines:[]},jre=Do({name:"referenceElements",initialState:N8e,reducers:{addDot:(t,e)=>{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=jc(t).dots.findIndex(r=>r===e.payload);n!==-1&&t.dots.splice(n,1)},addArea:(t,e)=>{t.areas.push(e.payload)},removeArea:(t,e)=>{var n=jc(t).areas.findIndex(r=>r===e.payload);n!==-1&&t.areas.splice(n,1)},addLine:(t,e)=>{t.lines.push(e.payload)},removeLine:(t,e)=>{var n=jc(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:zit,removeDot:Uit,addArea:Bit,removeArea:Hit,addLine:C8e,removeLine:P8e}=jre.actions,T8e=jre.reducer,Ere=w.createContext(void 0),A8e=t=>{var{children:e}=t,[n]=w.useState("".concat(K0("recharts"),"-clip")),r=ET();if(r==null)return null;var{x:i,y:s,width:o,height:l}=r;return w.createElement(Ere.Provider,{value:n},w.createElement("defs",null,w.createElement("clipPath",{id:n},w.createElement("rect",{x:i,y:s,height:l,width:o}))),e)},M8e=()=>w.useContext(Ere);class j8e{constructor(e){var{x:n,y:r}=e;this.xAxisScale=n,this.yAxisScale=r}map(e,n){var r,i,{position:s}=n;return{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:0,y:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:0}}mapWithFallback(e,n){var r,i,{position:s,fallback:o}=n,l,c;return o==="rangeMin"?l=this.yAxisScale.rangeMin():o==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,o==="rangeMin"?c=this.xAxisScale.rangeMin():o==="rangeMax"?c=this.xAxisScale.rangeMax():c=0,{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:c,y:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:l}}isInRange(e){var{x:n,y:r}=e,i=n==null||this.xAxisScale.isInRange(n),s=r==null||this.yAxisScale.isInRange(r);return i&&s}}function eW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function tW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?eW(Object(n),!0).forEach(function(r){E8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):eW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function E8e(t,e,n){return(e=D8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function D8e(t){var e=F8e(t,"string");return typeof e=="symbol"?e:e+""}function F8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function hC(){return hC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},hC.apply(null,arguments)}var R8e=(t,e)=>{var n;if(w.isValidElement(t))n=w.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!qn(e.x1)||!qn(e.y1)||!qn(e.x2)||!qn(e.y2))return null;n=w.createElement("line",hC({},e,{className:"recharts-reference-line-line"}))}return n},L8e=(t,e,n,r,i,s)=>{var{x:o,width:l}=s,c=i.map(t,{position:n});if(!qn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?d.reverse():d},O8e=(t,e,n,r,i,s)=>{var{y:o,height:l}=s,c=i.map(t,{position:n});if(!qn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?d.reverse():d},I8e=(t,e,n,r)=>{var i=[r.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&i.some(s=>!r.isInRange(s))?null:i},z8e=(t,e,n,r,i,s,o)=>{var{x:l,y:c,segment:d,ifOverflow:u}=o,m=Jl(l),p=Jl(c);return p?L8e(c,u,r,s,e,n):m?O8e(l,u,r,i,t,n):d!=null&&d.length===2?I8e(d,u,r,new j8e({x:t,y:e})):null};function U8e(t){var e=ta();return w.useEffect(()=>(e(C8e(t)),()=>{e(P8e(t))})),null}function B8e(t){var{xAxisId:e,yAxisId:n,shape:r,className:i,ifOverflow:s}=t,o=Si(),l=M8e(),c=dn(A=>Fd(A,e)),d=dn(A=>Rd(A,n)),u=dn(A=>Ix(A,"xAxis",e,o)),m=dn(A=>Ix(A,"yAxis",n,o)),p=Ww();if(!l||!p||c==null||d==null||u==null||m==null)return null;var f=z8e(u,m,p,t.position,c.orientation,d.orientation,t);if(!f)return null;var y=f[0],v=f[1];if(y==null||v==null)return null;var{x:b,y:g}=y,{x:_,y:k}=v,P=s==="hidden"?"url(#".concat(l,")"):void 0,N=tW(tW({clipPath:P},ms(t)),{},{x1:b,y1:g,x2:_,y2:k}),M=S8e({x1:b,y1:g,x2:_,y2:k});return w.createElement(Ls,{zIndex:t.zIndex},w.createElement(Pa,{className:wr("recharts-reference-line",i)},R8e(r,N),w.createElement(hre,hC({},M,{lowerWidth:M.width,upperWidth:M.width}),w.createElement(fre,{label:t.label}),t.children)))}var H8e={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:Ha.line};function Xv(t){var e=Ta(t,H8e);return w.createElement(w.Fragment,null,w.createElement(U8e,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),w.createElement(B8e,e))}Xv.displayName="ReferenceLine";function Dre(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;r<t.length;r+=e){var i=t[r];i!==void 0&&n.push(i)}return n}function q8e(t,e,n){var r={width:t.width+e.width,height:t.height+e.height};return k8e(r,n)}function $8e(t,e,n){var r=n==="width",{x:i,y:s,width:o,height:l}=t;return e===1?{start:r?i:s,end:r?i+o:s+l}:{start:r?i+o:s+l,end:r?i:s}}function lw(t,e,n,r,i){if(t*e<t*r||t*e>t*i)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-i)<=0}function V8e(t,e){return Dre(t,e+1)}function G8e(t,e,n,r,i){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,d=1,u=o,m=function(){var y=r?.[c];if(y===void 0)return{v:Dre(r,d)};var v=c,b,g=()=>(b===void 0&&(b=n(y,v)),b),_=y.coordinate,k=c===0||lw(t,_,g,u,l);k||(c=0,u=o,d+=1),k&&(u=_+t*(g()/2+i),c+=d)},p;d<=s.length;)if(p=m(),p)return p.v;return[]}function W8e(t,e,n,r,i){var s=(r||[]).slice(),o=s.length;if(o===0)return[];for(var{start:l,end:c}=e,d=1;d<=o;d++){for(var u=(o-1)%d,m=l,p=!0,f=function(){var P=r[v];if(P==null)return 0;var N=v,M,A=()=>(M===void 0&&(M=n(P,N)),M),T=P.coordinate,C=v===u||lw(t,T,A,m,c);if(!C)return p=!1,1;C&&(m=T+t*(A()/2+i))},y,v=u;v<o&&(y=f(),!(y!==0&&y===1));v+=d);if(p){for(var b=[],g=u;g<o;g+=d){var _=r[g];_!=null&&b.push(_)}return b}}return[]}function nW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Cs(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?nW(Object(n),!0).forEach(function(r){K8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):nW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function K8e(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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Q8e(t,e,n,r,i){for(var s=(r||[]).slice(),o=s.length,{start:l}=e,{end:c}=e,d=function(p){var f=s[p];if(f==null)return 1;var y=f,v,b=()=>(v===void 0&&(v=n(f,p)),v);if(p===o-1){var g=t*(y.coordinate+t*b()/2-c);s[p]=y=Cs(Cs({},y),{},{tickCoord:g>0?y.coordinate-g*t:y.coordinate})}else s[p]=y=Cs(Cs({},y),{},{tickCoord:y.coordinate});if(y.tickCoord!=null){var _=lw(t,y.tickCoord,b,l,c);_&&(c=y.tickCoord-t*(b()/2+i),s[p]=Cs(Cs({},y),{},{isShow:!0}))}},u=o-1;u>=0;u--)d(u);return s}function Z8e(t,e,n,r,i,s){var o=(r||[]).slice(),l=o.length,{start:c,end:d}=e;if(s){var u=r[l-1];if(u!=null){var m=n(u,l-1),p=t*(u.coordinate+t*m/2-d);if(o[l-1]=u=Cs(Cs({},u),{},{tickCoord:p>0?u.coordinate-p*t:u.coordinate}),u.tickCoord!=null){var f=lw(t,u.tickCoord,()=>m,c,d);f&&(d=u.tickCoord-t*(m/2+i),o[l-1]=Cs(Cs({},u),{},{isShow:!0}))}}}for(var y=s?l-1:l,v=function(_){var k=o[_];if(k==null)return 1;var P=k,N,M=()=>(N===void 0&&(N=n(k,_)),N);if(_===0){var A=t*(P.coordinate-t*M()/2-c);o[_]=P=Cs(Cs({},P),{},{tickCoord:A<0?P.coordinate-A*t:P.coordinate})}else o[_]=P=Cs(Cs({},P),{},{tickCoord:P.coordinate});if(P.tickCoord!=null){var T=lw(t,P.tickCoord,M,c,d);T&&(c=P.tickCoord+t*(M()/2+i),o[_]=Cs(Cs({},P),{},{isShow:!0}))}},b=0;b<y;b++)v(b);return o}function V4(t,e,n){var{tick:r,ticks:i,viewBox:s,minTickGap:o,orientation:l,interval:c,tickFormatter:d,unit:u,angle:m}=t;if(!i||!i.length||!r)return[];if(on(c)||Xw.isSsr){var p;return(p=V8e(i,on(c)?c:0))!==null&&p!==void 0?p:[]}var f=[],y=l==="top"||l==="bottom"?"width":"height",v=u&&y==="width"?m0(u,{fontSize:e,letterSpacing:n}):{width:0,height:0},b=(N,M)=>{var A=typeof d=="function"?d(N.value,M):N.value;return y==="width"?q8e(m0(A,{fontSize:e,letterSpacing:n}),v,m):m0(A,{fontSize:e,letterSpacing:n})[y]},g=i[0],_=i[1],k=i.length>=2&&g!=null&&_!=null?Li(_.coordinate-g.coordinate):1,P=$8e(s,k,y);return c==="equidistantPreserveStart"?G8e(k,P,b,i,o):c==="equidistantPreserveEnd"?W8e(k,P,b,i,o):(c==="preserveStart"||c==="preserveStartEnd"?f=Z8e(k,P,b,i,o,c==="preserveStartEnd"):f=Q8e(k,P,b,i,o),f.filter(N=>N.isShow))}var J8e=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:i=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(u=>{if(u){var m=u.getBoundingClientRect();m.width>o&&(o=m.width)}});var l=n?n.getBoundingClientRect().width:0,c=i+s,d=o+c+l+(n?r:0);return Math.round(d)}return 0},e6e=["axisLine","width","height","className","hide","ticks","axisType"];function t6e(t,e){if(t==null)return{};var n,r,i=n6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function n6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function tg(){return tg=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},tg.apply(null,arguments)}function rW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function La(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rW(Object(n),!0).forEach(function(r){r6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function r6e(t,e,n){return(e=a6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function a6e(t){var e=i6e(t,"string");return typeof e=="symbol"?e:e+""}function i6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Bu={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:Ha.axis};function s6e(t){var{x:e,y:n,width:r,height:i,orientation:s,mirror:o,axisLine:l,otherSvgProps:c}=t;if(!l)return null;var d=La(La(La({},c),to(l)),{},{fill:"none"});if(s==="top"||s==="bottom"){var u=+(s==="top"&&!o||s==="bottom"&&o);d=La(La({},d),{},{x1:e,y1:n+u*i,x2:e+r,y2:n+u*i})}else{var m=+(s==="left"&&!o||s==="right"&&o);d=La(La({},d),{},{x1:e+m*r,y1:n,x2:e+m*r,y2:n+i})}return w.createElement("line",tg({},d,{className:wr("recharts-cartesian-axis-line",Yf(l,"className"))}))}function o6e(t,e,n,r,i,s,o,l,c){var d,u,m,p,f,y,v=l?-1:1,b=t.tickSize||o,g=on(t.tickCoord)?t.tickCoord:t.coordinate;switch(s){case"top":d=u=t.coordinate,p=n+ +!l*i,m=p-v*b,y=m-v*c,f=g;break;case"left":m=p=t.coordinate,u=e+ +!l*r,d=u-v*b,f=d-v*c,y=g;break;case"right":m=p=t.coordinate,u=e+ +l*r,d=u+v*b,f=d+v*c,y=g;break;default:d=u=t.coordinate,p=n+ +l*i,m=p+v*b,y=m+v*c,f=g;break}return{line:{x1:d,y1:m,x2:u,y2:p},tick:{x:f,y}}}function l6e(t,e){switch(t){case"left":return e?"start":"end";case"right":return e?"end":"start";default:return"middle"}}function c6e(t,e){switch(t){case"left":case"right":return"middle";case"top":return e?"start":"end";default:return e?"end":"start"}}function d6e(t){var{option:e,tickProps:n,value:r}=t,i,s=wr(n.className,"recharts-cartesian-axis-tick-value");if(w.isValidElement(e))i=w.cloneElement(e,La(La({},n),{},{className:s}));else if(typeof e=="function")i=e(La(La({},n),{},{className:s}));else{var o="recharts-cartesian-axis-tick-value";typeof e!="boolean"&&(o=wr(o,Sre(e))),i=w.createElement(NT,tg({},n,{className:o}),r)}return i}var u6e=w.forwardRef((t,e)=>{var{ticks:n=[],tick:r,tickLine:i,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:d,orientation:u,mirror:m,x:p,y:f,width:y,height:v,tickSize:b,tickMargin:g,fontSize:_,letterSpacing:k,getTicksConfig:P,events:N,axisType:M}=t,A=V4(La(La({},P),{},{ticks:n}),_,k),T=l6e(u,m),C=c6e(u,m),F=to(P),$=Wf(r),I={};typeof i=="object"&&(I=i);var X=La(La({},F),{},{fill:"none"},I),L=A.map(ee=>La({entry:ee},o6e(ee,p,f,y,v,u,b,m,g))),te=L.map(ee=>{var{entry:me,line:le}=ee;return w.createElement(Pa,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(me.value,"-").concat(me.coordinate,"-").concat(me.tickCoord)},i&&w.createElement("line",tg({},X,le,{className:wr("recharts-cartesian-axis-tick-line",Yf(i,"className"))})))}),ae=L.map((ee,me)=>{var le,ue,{entry:K,tick:ne}=ee,oe=La(La(La(La({verticalAnchor:C},F),{},{textAnchor:T,stroke:"none",fill:s},ne),{},{index:me,payload:K,visibleTicksCount:A.length,tickFormatter:o,padding:c},d),{},{angle:(le=(ue=d?.angle)!==null&&ue!==void 0?ue:F.angle)!==null&&le!==void 0?le:0}),be=La(La({},oe),$);return w.createElement(Pa,tg({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(K.value,"-").concat(K.coordinate,"-").concat(K.tickCoord)},qw(N,K,me)),r&&w.createElement(d6e,{option:r,tickProps:be,value:"".concat(typeof o=="function"?o(K.value,me):K.value).concat(l||"")}))});return w.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(M,"-ticks")},ae.length>0&&w.createElement(Ls,{zIndex:Ha.label},w.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(M,"-tick-labels"),ref:e},ae)),te.length>0&&w.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(M,"-tick-lines")},te))}),m6e=w.forwardRef((t,e)=>{var{axisLine:n,width:r,height:i,className:s,hide:o,ticks:l,axisType:c}=t,d=t6e(t,e6e),[u,m]=w.useState(""),[p,f]=w.useState(""),y=w.useRef(null);w.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var b;return J8e({ticks:y.current,label:(b=t.labelRef)===null||b===void 0?void 0:b.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var v=w.useCallback(b=>{if(b){var g=b.getElementsByClassName("recharts-cartesian-axis-tick-value");y.current=g;var _=g[0];if(_){var k=window.getComputedStyle(_),P=k.fontSize,N=k.letterSpacing;(P!==u||N!==p)&&(m(P),f(N))}}},[u,p]);return o||r!=null&&r<=0||i!=null&&i<=0?null:w.createElement(Ls,{zIndex:t.zIndex},w.createElement(Pa,{className:wr("recharts-cartesian-axis",s)},w.createElement(s6e,{x:t.x,y:t.y,width:r,height:i,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:to(t)}),w.createElement(u6e,{ref:v,axisType:c,events:d,fontSize:u,getTicksConfig:t,height:t.height,letterSpacing:p,mirror:t.mirror,orientation:t.orientation,padding:t.padding,stroke:t.stroke,tick:t.tick,tickFormatter:t.tickFormatter,tickLine:t.tickLine,tickMargin:t.tickMargin,tickSize:t.tickSize,tickTextProps:t.tickTextProps,ticks:l,unit:t.unit,width:t.width,x:t.x,y:t.y}),w.createElement(hre,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},w.createElement(fre,{label:t.label,labelRef:t.labelRef}),t.children)))}),G4=w.forwardRef((t,e)=>{var n=Ta(t,Bu);return w.createElement(m6e,tg({},n,{ref:e}))});G4.displayName="CartesianAxis";var h6e=["x1","y1","x2","y2","key"],p6e=["offset"],f6e=["xAxisId","yAxisId"],g6e=["xAxisId","yAxisId"];function aW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function As(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?aW(Object(n),!0).forEach(function(r){b6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):aW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function 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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function df(){return df=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},df.apply(null,arguments)}function pC(t,e){if(t==null)return{};var n,r,i=v6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function v6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var w6e=t=>{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:i,width:s,height:o,ry:l}=t;return w.createElement("rect",{x:r,y:i,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Fre(t){var{option:e,lineItemProps:n}=t,r;if(w.isValidElement(e))r=w.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var i,{x1:s,y1:o,x2:l,y2:c,key:d}=n,u=pC(n,h6e),m=(i=to(u))!==null&&i!==void 0?i:{},{offset:p}=m,f=pC(m,p6e);r=w.createElement("line",df({},f,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:d}))}return r}function S6e(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=pC(t,f6e),c=i.map((d,u)=>{var m=As(As({},l),{},{x1:e,y1:d,x2:e+n,y2:d,key:"line-".concat(u),index:u});return w.createElement(Fre,{key:"line-".concat(u),option:r,lineItemProps:m})});return w.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function _6e(t){var{y:e,height:n,vertical:r=!0,verticalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=pC(t,g6e),c=i.map((d,u)=>{var m=As(As({},l),{},{x1:d,y1:e,x2:d,y2:e+n,key:"line-".concat(u),index:u});return w.createElement(Fre,{option:r,lineItemProps:m,key:"line-".concat(u)})});return w.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function k6e(t){var{horizontalFill:e,fillOpacity:n,x:r,y:i,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var d=l.map(m=>Math.round(m+i-i)).sort((m,p)=>m-p);i!==d[0]&&d.unshift(0);var u=d.map((m,p)=>{var f=d[p+1],y=f==null,v=y?i+o-m:f-m;if(v<=0)return null;var b=p%e.length;return w.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:v,width:s,stroke:"none",fill:e[b],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},u)}function N6e(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:i,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var d=c.map(m=>Math.round(m+i-i)).sort((m,p)=>m-p);i!==d[0]&&d.unshift(0);var u=d.map((m,p)=>{var f=d[p+1],y=f==null,v=y?i+o-m:f-m;if(v<=0)return null;var b=p%n.length;return w.createElement("rect",{key:"react-".concat(p),x:m,y:s,width:v,height:l,stroke:"none",fill:n[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},u)}var C6e=(t,e)=>{var{xAxis:n,width:r,height:i,offset:s}=t;return _ee(V4(As(As(As({},Bu),n),{},{ticks:kee(n),viewBox:{x:0,y:0,width:r,height:i}})),s.left,s.left+s.width,e)},P6e=(t,e)=>{var{yAxis:n,width:r,height:i,offset:s}=t;return _ee(V4(As(As(As({},Bu),n),{},{ticks:kee(n),viewBox:{x:0,y:0,width:r,height:i}})),s.top,s.top+s.height,e)},T6e={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Ha.grid};function uf(t){var e=yI(),n=vI(),r=Eee(),i=As(As({},Ta(t,T6e)),{},{x:on(t.x)?t.x:r.left,y:on(t.y)?t.y:r.top,width:on(t.width)?t.width:r.width,height:on(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:d,height:u,syncWithTicks:m,horizontalValues:p,verticalValues:f}=i,y=Si(),v=dn(C=>G7(C,"xAxis",s,y)),b=dn(C=>G7(C,"yAxis",o,y));if(!Pd(d)||!Pd(u)||!on(l)||!on(c))return null;var g=i.verticalCoordinatesGenerator||C6e,_=i.horizontalCoordinatesGenerator||P6e,{horizontalPoints:k,verticalPoints:P}=i;if((!k||!k.length)&&typeof _=="function"){var N=p&&p.length,M=_({yAxis:b?As(As({},b),{},{ticks:N?p:b.ticks}):void 0,width:e??d,height:n??u,offset:r},N?!0:m);IN(Array.isArray(M),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof M,"]")),Array.isArray(M)&&(k=M)}if((!P||!P.length)&&typeof g=="function"){var A=f&&f.length,T=g({xAxis:v?As(As({},v),{},{ticks:A?f:v.ticks}):void 0,width:e??d,height:n??u,offset:r},A?!0:m);IN(Array.isArray(T),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof T,"]")),Array.isArray(T)&&(P=T)}return w.createElement(Ls,{zIndex:i.zIndex},w.createElement("g",{className:"recharts-cartesian-grid"},w.createElement(w6e,{fill:i.fill,fillOpacity:i.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),w.createElement(k6e,df({},i,{horizontalPoints:k})),w.createElement(N6e,df({},i,{verticalPoints:P})),w.createElement(S6e,df({},i,{offset:r,horizontalPoints:k,xAxis:v,yAxis:b})),w.createElement(_6e,df({},i,{offset:r,verticalPoints:P,xAxis:v,yAxis:b}))))}uf.displayName="CartesianGrid";var A6e={},Rre=Do({name:"errorBars",initialState:A6e,reducers:{addErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]||(t[n]=[]),t[n].push(r)},replaceErrorBar:(t,e)=>{var{itemId:n,prev:r,next:i}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?i:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(i=>i.dataKey!==r.dataKey||i.direction!==r.direction))}}}),{addErrorBar:qit,replaceErrorBar:$it,removeErrorBar:Vit}=Rre.actions,M6e=Rre.reducer,j6e=["children"];function E6e(t,e){if(t==null)return{};var n,r,i=D6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function D6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var F6e={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},R6e=w.createContext(F6e);function Lre(t){var{children:e}=t,n=E6e(t,j6e);return w.createElement(R6e.Provider,{value:n},e)}function DT(t,e){var n,r,i=dn(d=>Fd(d,t)),s=dn(d=>Rd(d,e)),o=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:ji.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:Ei.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function W4(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,i=ET(),{needClipX:s,needClipY:o,needClip:l}=DT(e,n);if(!l||!i)return null;var{x:c,y:d,width:u,height:m}=i;return w.createElement("clipPath",{id:"clipPath-".concat(r)},w.createElement("rect",{x:s?c:c-u/2,y:o?d:d-m/2,width:s?u:u*2,height:o?m:m*2}))}var Ore=(t,e,n,r)=>Md(t,"xAxis",e,r),Ire=(t,e,n,r)=>Ad(t,"xAxis",e,r),zre=(t,e,n,r)=>Md(t,"yAxis",n,r),Ure=(t,e,n,r)=>Ad(t,"yAxis",n,r),L6e=yt([yr,Ore,zre,Ire,Ure],(t,e,n,r,i)=>Bc(t,"xAxis")?Kh(e,r,!1):Kh(n,i,!1)),O6e=(t,e,n,r,i)=>i;function I6e(t){return t.type==="line"}var z6e=yt([rS,O6e],(t,e)=>t.filter(I6e).find(n=>n.id===e)),U6e=yt([yr,Ore,zre,Ire,Ure,z6e,L6e,WI],(t,e,n,r,i,s,o,l)=>{var{chartData:c,dataStartIndex:d,dataEndIndex:u}=l;if(!(s==null||e==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:m,data:p}=s,f;if(p!=null&&p.length>0?f=p:f=c?.slice(d,u+1),f!=null)return CHe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:m,bandSize:o,displayedData:f})}});function Bre(t){var e=Wf(t),n=3,r=2;if(e!=null){var{r:i,strokeWidth:s}=e,o=Number(i),l=Number(s);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(l)||l<0)&&(l=r),{r:o,strokeWidth:l}}return{r:n,strokeWidth:r}}var cD={exports:{}},dD={};var iW;function B6e(){if(iW)return dD;iW=1;var t=og();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var n=typeof Object.is=="function"?Object.is:e,r=t.useSyncExternalStore,i=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return dD.useSyncExternalStoreWithSelector=function(c,d,u,m,p){var f=i(null);if(f.current===null){var y={hasValue:!1,value:null};f.current=y}else y=f.current;f=o(function(){function b(N){if(!g){if(g=!0,_=N,N=m(N),p!==void 0&&y.hasValue){var M=y.value;if(p(M,N))return k=M}return k=N}if(M=k,n(_,N))return M;var A=m(N);return p!==void 0&&p(M,A)?(_=N,M):(_=N,k=A)}var g=!1,_,k,P=u===void 0?null:u;return[function(){return b(d())},P===null?void 0:function(){return b(P())}]},[d,u,m,p]);var v=r(c,f[0],f[1]);return s(function(){y.hasValue=!0,y.value=v},[v]),l(v),v},dD}var sW;function H6e(){return sW||(sW=1,cD.exports=B6e()),cD.exports}H6e();function q6e(t){t()}function $6e(){let t=null,e=null;return{clear(){t=null,e=null},notify(){q6e(()=>{let n=t;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=t;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const i=e={callback:n,next:null,prev:e};return i.prev?i.prev.next=i:t=i,function(){!r||t===null||(r=!1,i.next?i.next.prev=i.prev:e=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}var oW={notify(){},get:()=>[]};function V6e(t,e){let n,r=oW,i=0,s=!1;function o(v){u();const b=r.subscribe(v);let g=!1;return()=>{g||(g=!0,b(),m())}}function l(){r.notify()}function c(){y.onStateChange&&y.onStateChange()}function d(){return s}function u(){i++,n||(n=t.subscribe(c),r=$6e())}function m(){i--,n&&i===0&&(n(),n=void 0,r.clear(),r=oW)}function p(){s||(s=!0,u())}function f(){s&&(s=!1,m())}const y={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:p,tryUnsubscribe:f,getListeners:()=>r};return y}var G6e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",W6e=G6e(),K6e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Y6e=K6e(),X6e=()=>W6e||Y6e?w.useLayoutEffect:w.useEffect,Q6e=X6e();function lW(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function Z6e(t,e){if(lW(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(!Object.prototype.hasOwnProperty.call(e,n[i])||!lW(t[n[i]],e[n[i]]))return!1;return!0}var J6e=Symbol.for("react-redux-context"),eHe=typeof globalThis<"u"?globalThis:{};function tHe(){if(!w.createContext)return{};const t=eHe[J6e]??=new Map;let e=t.get(w.createContext);return e||(e=w.createContext(null),t.set(w.createContext,e)),e}var nHe=tHe();function rHe(t){const{children:e,context:n,serverState:r,store:i}=t,s=w.useMemo(()=>{const c=V6e(i);return{store:i,subscription:c,getServerState:r?()=>r:void 0}},[i,r]),o=w.useMemo(()=>i.getState(),[i]);Q6e(()=>{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||nHe;return w.createElement(l.Provider,{value:s},e)}var aHe=rHe,iHe=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function sHe(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function cS(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(iHe.has(r)){if(t[r]==null&&e[r]==null)continue;if(!Z6e(t[r],e[r]))return!1}else if(!sHe(t[r],e[r]))return!1;return!0}var oHe=["id"],lHe=["type","layout","connectNulls","needClip","shape"],cHe=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function cw(){return cw=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},cw.apply(null,arguments)}function cW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function dd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cW(Object(n),!0).forEach(function(r){dHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function dHe(t,e,n){return(e=uHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function uHe(t){var e=mHe(t,"string");return typeof e=="symbol"?e:e+""}function mHe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function K4(t,e){if(t==null)return{};var n,r,i=hHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function hHe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var pHe=t=>{var{dataKey:e,name:n,stroke:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:np(n,e),payload:t}]},fHe=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:tp,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:np(o,e),hide:l,type:d,color:r,unit:c,graphicalItemId:u}};return w.createElement(AT,{tooltipEntrySettings:m})}),Hre=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function gHe(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],i=0;i<e;++i)r=[...r,...n];return r}var bHe=(t,e,n)=>{var r=n.reduce((f,y)=>f+y);if(!r)return Hre(e,t);for(var i=Math.floor(t/r),s=t%r,o=e-t,l=[],c=0,d=0;c<n.length;d+=(u=n[c])!==null&&u!==void 0?u:0,++c){var u,m=n[c];if(m!=null&&d+m>s){l=[...n.slice(0,c),s-d];break}}var p=l.length%2===0?[0,o]:[o];return[...gHe(n,i),...l,...p].map(f=>"".concat(f,"px")).join(", ")};function xHe(t){var{clipPathId:e,points:n,props:r}=t,{dot:i,dataKey:s,needClip:o}=r,{id:l}=r,c=K4(r,oHe),d=to(c);return w.createElement(Cre,{points:n,dot:i,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:d,needClip:o,clipPathId:e})}function yHe(t){var{showLabels:e,children:n,points:r}=t,i=w.useMemo(()=>r?.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return dd(dd({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return w.createElement(F4,{value:e?i:void 0},n)}function dW(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:i,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:d,shape:u}=s,m=K4(s,lHe),p=dd(dd({},ms(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:d?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:i??s.strokeDasharray});return w.createElement(w.Fragment,null,r?.length>1&&w.createElement(z4,cw({shapeType:"curve",option:u},p,{pathRef:n})),w.createElement(xHe,{points:r,clipPathId:e,props:s}))}function vHe(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function wHe(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:i,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,animateNewValues:p,width:f,height:y,onAnimationEnd:v,onAnimationStart:b}=n,g=i.current,_=cy(o,"recharts-line-"),k=w.useRef(_),[P,N]=w.useState(!1),M=!P,A=w.useCallback(()=>{typeof v=="function"&&v(),N(!1)},[v]),T=w.useCallback(()=>{typeof b=="function"&&b(),N(!0)},[b]),C=vHe(r.current),F=w.useRef(0);k.current!==_&&(F.current=s.current,k.current=_);var $=F.current;return w.createElement(yHe,{points:o,showLabels:M},n.children,w.createElement(ly,{animationId:_,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:A,onAnimationStart:T,key:_},I=>{var X=Er($,C+$,I),L=Math.min(X,C),te;if(c)if(l){var ae="".concat(l).split(/[,\s]+/gim).map(le=>parseFloat(le));te=bHe(L,C,ae)}else te=Hre(C,L);else te=l==null?void 0:String(l);if(I>0&&C>0&&(i.current=o,s.current=Math.max(s.current,L)),g){var ee=g.length/o.length,me=I===1?o:o.map((le,ue)=>{var K=Math.floor(ue*ee);if(g[K]){var ne=g[K];return dd(dd({},le),{},{x:Er(ne.x,le.x,I),y:Er(ne.y,le.y,I)})}return p?dd(dd({},le),{},{x:Er(f*2,le.x,I),y:Er(y/2,le.y,I)}):dd(dd({},le),{},{x:le.x,y:le.y})});return i.current=me,w.createElement(dW,{props:n,points:me,clipPathId:e,pathRef:r,strokeDasharray:te})}return w.createElement(dW,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:te})}),w.createElement(CT,{label:n.label}))}function SHe(t){var{clipPathId:e,props:n}=t,r=w.useRef(null),i=w.useRef(0),s=w.useRef(null);return w.createElement(wHe,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:i,pathRef:s})}var _He=(t,e)=>{var n,r;return{x:(n=t.x)!==null&&n!==void 0?n:void 0,y:(r=t.y)!==null&&r!==void 0?r:void 0,value:t.value,errorVal:Dr(t.payload,e)}};class kHe extends w.Component{render(){var{hide:e,dot:n,points:r,className:i,xAxisId:s,yAxisId:o,top:l,left:c,width:d,height:u,id:m,needClip:p,zIndex:f}=this.props;if(e)return null;var y=wr("recharts-line",i),v=m,{r:b,strokeWidth:g}=Bre(n),_=I4(n),k=b*2+g,P=p?"url(#clipPath-".concat(_?"":"dots-").concat(v,")"):void 0;return w.createElement(Ls,{zIndex:f},w.createElement(Pa,{className:y},p&&w.createElement("defs",null,w.createElement(W4,{clipPathId:v,xAxisId:s,yAxisId:o}),!_&&w.createElement("clipPath",{id:"clipPath-dots-".concat(v)},w.createElement("rect",{x:c-k/2,y:l-k/2,width:d+k,height:u+k}))),w.createElement(Lre,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:_He,errorBarOffset:0},w.createElement(SHe,{props:this.props,clipPathId:v}))),w.createElement($R,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:P}))}}var qre={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:Ha.line,type:"linear"};function NHe(t){var e=Ta(t,qre),{activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:d,isAnimationActive:u,label:m,legendType:p,xAxisId:f,yAxisId:y,id:v}=e,b=K4(e,cHe),{needClip:g}=DT(f,y),_=ET(),k=rp(),P=Si(),N=dn(F=>U6e(F,f,y,P,v));if(k!=="horizontal"&&k!=="vertical"||N==null||_==null)return null;var{height:M,width:A,x:T,y:C}=_;return w.createElement(kHe,cw({},b,{id:v,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,isAnimationActive:u,hide:d,label:m,legendType:p,xAxisId:f,yAxisId:y,points:N,layout:k,height:M,width:A,left:T,top:C,needClip:g}))}function CHe(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((d,u)=>{var m=Dr(d,o);if(e==="horizontal"){var p=ON({axis:n,ticks:i,bandSize:l,entry:d,index:u}),f=Sa(m)?null:r.scale.map(m);return{x:p,y:f??null,value:m,payload:d}}var y=Sa(m)?null:n.scale.map(m),v=ON({axis:r,ticks:s,bandSize:l,entry:d,index:u});return y==null||v==null?null:{x:y,y:v,value:m,payload:d}}).filter(Boolean)}function PHe(t){var e=Ta(t,qre),n=Si();return w.createElement(MT,{id:e.id,type:"line"},r=>w.createElement(w.Fragment,null,w.createElement(q4,{legendPayload:pHe(e)}),w.createElement(fHe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:r}),w.createElement($4,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),w.createElement(NHe,cw({},e,{id:r}))))}var $re=w.memo(PHe,cS);$re.displayName="Line";function Ld(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:Pre}function Od(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:Pre}var Vre=(t,e,n)=>Md(t,"xAxis",Ld(t,e),n),Gre=(t,e,n)=>Ad(t,"xAxis",Ld(t,e),n),Wre=(t,e,n)=>Md(t,"yAxis",Od(t,e),n),Kre=(t,e,n)=>Ad(t,"yAxis",Od(t,e),n),THe=yt([yr,Vre,Wre,Gre,Kre],(t,e,n,r,i)=>Bc(t,"xAxis")?Kh(e,r,!1):Kh(n,i,!1)),AHe=(t,e)=>e,Yre=yt([rS,AHe],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),Xre=t=>{var e=yr(t),n=Bc(e,"xAxis");return n?"yAxis":"xAxis"},MHe=(t,e)=>{var n=Xre(t);return n==="yAxis"?Od(t,e):Ld(t,e)},jHe=(t,e,n)=>sC(t,Xre(t),MHe(t,e),n),EHe=yt([Yre,jHe],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:r}=t,i=gT(t);if(!(r==null||i==null)){var s=(n=e[r])===null||n===void 0?void 0:n.stackedData,o=s?.find(l=>l.key===i);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),DHe=yt([yr,Vre,Wre,Gre,Kre,EHe,Rte,THe,Yre,$Oe],(t,e,n,r,i,s,o,l,c,d)=>{var{chartData:u,dataStartIndex:m,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||i==null||r.length===0||i.length===0||l==null)){var{data:f}=c,y;if(f&&f.length>0?y=f:y=u?.slice(m,p+1),y!=null)return ZHe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataStartIndex:m,areaSettings:c,stackedData:s,displayedData:y,chartBaseValue:d,bandSize:l})}}),FHe=["id"],RHe=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function Pf(){return Pf=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Pf.apply(null,arguments)}function Qre(t,e){if(t==null)return{};var n,r,i=LHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function LHe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function uW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Jb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?uW(Object(n),!0).forEach(function(r){OHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):uW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function OHe(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=zHe(t,"string");return typeof e=="symbol"?e:e+""}function zHe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fC(t,e){return t&&t!=="none"?t:e}var UHe=t=>{var{dataKey:e,name:n,stroke:r,fill:i,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:fC(r,i),value:np(n,e),payload:t}]},BHe=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:tp,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:np(o,e),hide:l,type:d,color:fC(r,s),unit:c,graphicalItemId:u}};return w.createElement(AT,{tooltipEntrySettings:m})});function HHe(t){var{clipPathId:e,points:n,props:r}=t,{needClip:i,dot:s,dataKey:o}=r,l=to(r);return w.createElement(Cre,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:i,clipPathId:e})}function qHe(t){var{showLabels:e,children:n,points:r}=t,i=r.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Jb(Jb({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return w.createElement(F4,{value:e?i:void 0},n)}function mW(t){var{points:e,baseLine:n,needClip:r,clipPathId:i,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:d,isRange:u}=s,{id:m}=s,p=Qre(s,FHe),f=to(p),y=ms(p);return w.createElement(w.Fragment,null,e?.length>1&&w.createElement(Pa,{clipPath:r?"url(#clipPath-".concat(i,")"):void 0},w.createElement(dx,Pf({},y,{id:m,points:e,connectNulls:d,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&w.createElement(dx,Pf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:e})),c!=="none"&&u&&w.createElement(dx,Pf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:n}))),w.createElement(HHe,{points:e,props:p,clipPathId:i}))}function $He(t){var e,n,{alpha:r,baseLine:i,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.y,c=(n=s[s.length-1])===null||n===void 0?void 0:n.y;if(!qn(l)||!qn(c))return null;var d=r*Math.abs(l-c),u=Math.max(...s.map(m=>m.x||0));return on(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.x||0),u)),on(u)?w.createElement("rect",{x:0,y:l<c?l:l-d,width:u+(o?parseInt("".concat(o),10):1),height:Math.floor(d)}):null}function VHe(t){var e,n,{alpha:r,baseLine:i,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.x,c=(n=s[s.length-1])===null||n===void 0?void 0:n.x;if(!qn(l)||!qn(c))return null;var d=r*Math.abs(l-c),u=Math.max(...s.map(m=>m.y||0));return on(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.y||0),u)),on(u)?w.createElement("rect",{x:l<c?l:l-d,y:0,width:d,height:Math.floor(u+(o?parseInt("".concat(o),10):1))}):null}function GHe(t){var{alpha:e,layout:n,points:r,baseLine:i,strokeWidth:s}=t;return n==="vertical"?w.createElement($He,{alpha:e,points:r,baseLine:i,strokeWidth:s}):w.createElement(VHe,{alpha:e,points:r,baseLine:i,strokeWidth:s})}function WHe(t){var{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s}=t,{points:o,baseLine:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,onAnimationStart:p,onAnimationEnd:f}=r,y=w.useMemo(()=>({points:o,baseLine:l}),[o,l]),v=cy(y,"recharts-area-"),b=wI(),[g,_]=w.useState(!1),k=!g,P=w.useCallback(()=>{typeof f=="function"&&f(),_(!1)},[f]),N=w.useCallback(()=>{typeof p=="function"&&p(),_(!0)},[p]);if(b==null)return null;var M=i.current,A=s.current;return w.createElement(qHe,{showLabels:k,points:o},r.children,w.createElement(ly,{animationId:v,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:P,onAnimationStart:N,key:v},T=>{if(M){var C=M.length/o.length,F=T===1?o:o.map((I,X)=>{var L=Math.floor(X*C);if(M[L]){var te=M[L];return Jb(Jb({},I),{},{x:Er(te.x,I.x,T),y:Er(te.y,I.y,T)})}return I}),$;return on(l)?$=Er(A,l,T):Sa(l)||Rc(l)?$=Er(A,0,T):$=l.map((I,X)=>{var L=Math.floor(X*C);if(Array.isArray(A)&&A[L]){var te=A[L];return Jb(Jb({},I),{},{x:Er(te.x,I.x,T),y:Er(te.y,I.y,T)})}return I}),T>0&&(i.current=F,s.current=$),w.createElement(mW,{points:F,baseLine:$,needClip:e,clipPathId:n,props:r})}return T>0&&(i.current=o,s.current=l),w.createElement(Pa,null,c&&w.createElement("defs",null,w.createElement("clipPath",{id:"animationClipPath-".concat(n)},w.createElement(GHe,{alpha:T,points:o,baseLine:l,layout:b,strokeWidth:r.strokeWidth}))),w.createElement(Pa,{clipPath:"url(#animationClipPath-".concat(n,")")},w.createElement(mW,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),w.createElement(CT,{label:r.label}))}function KHe(t){var{needClip:e,clipPathId:n,props:r}=t,i=w.useRef(null),s=w.useRef();return w.createElement(WHe,{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s})}class YHe extends w.PureComponent{render(){var{hide:e,dot:n,points:r,className:i,top:s,left:o,needClip:l,xAxisId:c,yAxisId:d,width:u,height:m,id:p,baseLine:f,zIndex:y}=this.props;if(e)return null;var v=wr("recharts-area",i),b=p,{r:g,strokeWidth:_}=Bre(n),k=I4(n),P=g*2+_,N=l?"url(#clipPath-".concat(k?"":"dots-").concat(b,")"):void 0;return w.createElement(Ls,{zIndex:y},w.createElement(Pa,{className:v},l&&w.createElement("defs",null,w.createElement(W4,{clipPathId:b,xAxisId:c,yAxisId:d}),!k&&w.createElement("clipPath",{id:"clipPath-dots-".concat(b)},w.createElement("rect",{x:o-P/2,y:s-P/2,width:u+P,height:m+P}))),w.createElement(KHe,{needClip:l,clipPathId:b,props:this.props})),w.createElement($R,{points:r,mainColor:fC(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}),this.props.isRange&&Array.isArray(f)&&w.createElement($R,{points:f,mainColor:fC(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}))}}var Zre={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:Ha.area};function XHe(t){var e,n=Ta(t,Zre),{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:d,fillOpacity:u,hide:m,isAnimationActive:p,legendType:f,stroke:y,xAxisId:v,yAxisId:b}=n,g=Qre(n,RHe),_=rp(),k=Xne(),{needClip:P}=DT(v,b),N=Si(),{points:M,isRange:A,baseLine:T}=(e=dn(L=>DHe(L,t.id,N)))!==null&&e!==void 0?e:{},C=ET();if(_!=="horizontal"&&_!=="vertical"||C==null||k!=="AreaChart"&&k!=="ComposedChart")return null;var{height:F,width:$,x:I,y:X}=C;return!M||!M.length?null:w.createElement(YHe,Pf({},g,{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,baseLine:T,connectNulls:l,dot:c,fill:d,fillOpacity:u,height:F,hide:m,layout:_,isAnimationActive:p==="auto"?!Xw.isSsr:p,isRange:A,legendType:f,needClip:P,points:M,stroke:y,width:$,left:I,top:X,xAxisId:v,yAxisId:b}))}var QHe=(t,e,n,r,i)=>{var s=n??e;if(on(s))return s;var o=t==="horizontal"?i:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),d=Math.min(l[0],l[1]);return s==="dataMin"?d:s==="dataMax"||c<0?c:Math.max(Math.min(l[0],l[1]),0)}return s==="dataMin"?l[0]:s==="dataMax"?l[1]:l[0]};function ZHe(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:i,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:d,dataStartIndex:u,xAxisTicks:m,yAxisTicks:p,bandSize:f}=t,y=i&&i.length,v=QHe(s,o,n,l,c),b=s==="horizontal",g=!1,_=d.map((P,N)=>{var M,A,T,C;if(y)C=i[u+N];else{var F=Dr(P,r);Array.isArray(F)?(C=F,g=!0):C=[v,F]}var $=(M=(A=C)===null||A===void 0?void 0:A[1])!==null&&M!==void 0?M:null,I=$==null||y&&!e&&Dr(P,r)==null;if(b){var X;return{x:ON({axis:l,ticks:m,bandSize:f,entry:P,index:N}),y:I?null:(X=c.scale.map($))!==null&&X!==void 0?X:null,value:C,payload:P}}return{x:I?null:(T=l.scale.map($))!==null&&T!==void 0?T:null,y:ON({axis:c,ticks:p,bandSize:f,entry:P,index:N}),value:C,payload:P}}),k;return y||g?k=_.map(P=>{var N,M=Array.isArray(P.value)?P.value[0]:null;if(b){var A;return{x:P.x,y:M!=null&&P.y!=null&&(A=c.scale.map(M))!==null&&A!==void 0?A:null,payload:P.payload}}return{x:M!=null&&(N=l.scale.map(M))!==null&&N!==void 0?N:null,y:P.y,payload:P.payload}}):k=b?c.scale.map(v):l.scale.map(v),{points:_,baseLine:k??0,isRange:g}}function JHe(t){var e=Ta(t,Zre),n=Si();return w.createElement(MT,{id:e.id,type:"area"},r=>w.createElement(w.Fragment,null,w.createElement(q4,{legendPayload:UHe(e)}),w.createElement(BHe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:r}),w.createElement($4,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:Nee(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),w.createElement(XHe,Pf({},e,{id:r}))))}var Jre=w.memo(JHe,cS);Jre.displayName="Area";var eqe="Invariant failed";function tqe(t,e){throw new Error(eqe)}function VR(){return VR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},VR.apply(null,arguments)}function gC(t){return w.createElement(z4,VR({shapeType:"rectangle",activeClassName:"recharts-active-bar"},t))}var nqe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(r,i)=>{if(on(e))return e;var s=on(r)||Sa(r);return s?e(r,i):(s||tqe(),n)}},rqe=(t,e,n)=>n,aqe=(t,e)=>e,dS=yt([rS,aqe],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),iqe=yt([dS],t=>t?.maxBarSize),sqe=(t,e,n,r)=>r,oqe=yt([yr,rS,Ld,Od,rqe],(t,e,n,r,i)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===i).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),lqe=(t,e,n)=>{var r=yr(t),i=Ld(t,e),s=Od(t,e);if(!(i==null||s==null))return r==="horizontal"?sC(t,"yAxis",s,n):sC(t,"xAxis",i,n)},cqe=(t,e)=>{var n=yr(t),r=Ld(t,e),i=Od(t,e);if(!(r==null||i==null))return n==="horizontal"?V7(t,"xAxis",r):V7(t,"yAxis",i)},dqe=yt([oqe,qOe,cqe],u8e),uqe=(t,e,n)=>{var r,i,s=dS(t,e);if(s==null)return 0;var o=Ld(t,e),l=Od(t,e);if(o==null||l==null)return 0;var c=yr(t),d=Wte(t),{maxBarSize:u}=s,m=Sa(u)?d:u,p,f;return c==="horizontal"?(p=Md(t,"xAxis",o,n),f=Ad(t,"xAxis",o,n)):(p=Md(t,"yAxis",l,n),f=Ad(t,"yAxis",l,n)),(r=(i=Kh(p,f,!0))!==null&&i!==void 0?i:m)!==null&&r!==void 0?r:0},eae=(t,e,n)=>{var r=yr(t),i=Ld(t,e),s=Od(t,e);if(!(i==null||s==null)){var o,l;return r==="horizontal"?(o=Md(t,"xAxis",i,n),l=Ad(t,"xAxis",i,n)):(o=Md(t,"yAxis",s,n),l=Ad(t,"yAxis",s,n)),Kh(o,l)}},mqe=yt([dqe,Wte,HOe,Kte,uqe,eae,iqe],g8e),hqe=(t,e,n)=>{var r=Ld(t,e);if(r!=null)return Md(t,"xAxis",r,n)},pqe=(t,e,n)=>{var r=Od(t,e);if(r!=null)return Md(t,"yAxis",r,n)},fqe=(t,e,n)=>{var r=Ld(t,e);if(r!=null)return Ad(t,"xAxis",r,n)},gqe=(t,e,n)=>{var r=Od(t,e);if(r!=null)return Ad(t,"yAxis",r,n)},bqe=yt([mqe,dS],x8e),xqe=yt([lqe,dS],b8e),yqe=yt([wi,gI,hqe,pqe,fqe,gqe,bqe,yr,Rte,eae,xqe,dS,sqe],(t,e,n,r,i,s,o,l,c,d,u,m,p)=>{var{chartData:f,dataStartIndex:y,dataEndIndex:v}=c;if(!(m==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||i==null||s==null||d==null)){var{data:b}=m,g;if(b!=null&&b.length>0?g=b:g=f?.slice(y,v+1),g!=null)return Wqe({layout:l,barSettings:m,pos:o,parentViewBox:e,bandSize:d,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,stackedData:u,displayedData:g,offset:t,cells:p,dataStartIndex:y})}}),vqe=["index"];function GR(){return GR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},GR.apply(null,arguments)}function wqe(t,e){if(t==null)return{};var n,r,i=Sqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function Sqe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var tae=w.createContext(void 0),_qe=t=>{var e=w.useContext(tae);if(e!=null)return e.stackId;if(t!=null)return Nee(t)},kqe=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),Nqe=t=>{var e=w.useContext(tae);if(e!=null){var{stackId:n}=e;return"url(#".concat(kqe(n,t),")")}},nae=t=>{var{index:e}=t,n=wqe(t,vqe),r=Nqe(e);return w.createElement(Pa,GR({className:"recharts-bar-stack-layer",clipPath:r},n))},Cqe=["onMouseEnter","onMouseLeave","onClick"],Pqe=["value","background","tooltipPosition"],Tqe=["id"],Aqe=["onMouseEnter","onClick","onMouseLeave"];function am(){return am=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},am.apply(null,arguments)}function hW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ws(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?hW(Object(n),!0).forEach(function(r){Mqe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):hW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Mqe(t,e,n){return(e=jqe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function jqe(t){var e=Eqe(t,"string");return typeof e=="symbol"?e:e+""}function Eqe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function bC(t,e){if(t==null)return{};var n,r,i=Dqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function Dqe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var Fqe=t=>{var{dataKey:e,name:n,fill:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:np(n,e),payload:t}]},Rqe=w.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:i,name:s,hide:o,unit:l,tooltipType:c,id:d}=t,u={dataDefinedOnItem:void 0,getPosition:tp,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:e,nameKey:void 0,name:np(s,e),hide:o,type:c,color:i,unit:l,graphicalItemId:d}};return w.createElement(AT,{tooltipEntrySettings:u})});function Lqe(t){var e=dn(Yh),{data:n,dataKey:r,background:i,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,d=bC(s,Cqe),u=U4(o,r,s.id),m=B4(l),p=H4(c,r,s.id);if(!i||n==null)return null;var f=Wf(i);return w.createElement(Ls,{zIndex:y8e(i,Ha.barBackground)},n.map((y,v)=>{var{value:b,background:g,tooltipPosition:_}=y,k=bC(y,Pqe);if(!g)return null;var P=u(y,v),N=m(y,v),M=p(y,v),A=Ws(Ws(Ws(Ws(Ws({option:i,isActive:String(v)===e},k),{},{fill:"#eee"},g),f),qw(d,y,v)),{},{onMouseEnter:P,onMouseLeave:N,onClick:M,dataKey:r,index:v,className:"recharts-bar-background-rectangle"});return w.createElement(gC,am({key:"background-bar-".concat(v)},A))}))}function Oqe(t){var{showLabels:e,children:n,rects:r}=t,i=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return Ws(Ws({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return w.createElement(F4,{value:e?i:void 0},n)}function Iqe(t){var{shape:e,activeBar:n,baseProps:r,entry:i,index:s,dataKey:o}=t,l=dn(Yh),c=dn(T4),d=n&&String(s)===l&&(c==null||o===c),u=d?n:e;return d?w.createElement(Ls,{zIndex:Ha.activeBar},w.createElement(nae,{index:s},w.createElement(gC,am({},r,{name:String(r.name)},i,{isActive:d,option:u,index:s,dataKey:o})))):w.createElement(gC,am({},r,{name:String(r.name)},i,{isActive:d,option:u,index:s,dataKey:o}))}function zqe(t){var{shape:e,baseProps:n,entry:r,index:i,dataKey:s}=t;return w.createElement(gC,am({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:i,dataKey:s}))}function Uqe(t){var e,{data:n,props:r}=t,i=(e=to(r))!==null&&e!==void 0?e:{},{id:s}=i,o=bC(i,Tqe),{shape:l,dataKey:c,activeBar:d}=r,{onMouseEnter:u,onClick:m,onMouseLeave:p}=r,f=bC(r,Aqe),y=U4(u,c,s),v=B4(p),b=H4(m,c,s);return n?w.createElement(w.Fragment,null,n.map((g,_)=>w.createElement(nae,am({index:_,key:"rectangle-".concat(g?.x,"-").concat(g?.y,"-").concat(g?.value,"-").concat(_),className:"recharts-bar-rectangle"},qw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),d?w.createElement(Iqe,{shape:l,activeBar:d,baseProps:o,entry:g,index:_,dataKey:c}):w.createElement(zqe,{shape:l,baseProps:o,entry:g,index:_,dataKey:c})))):null}function Bqe(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:d,onAnimationStart:u}=e,m=n.current,p=cy(e,"recharts-bar-"),[f,y]=w.useState(!1),v=!f,b=w.useCallback(()=>{typeof d=="function"&&d(),y(!1)},[d]),g=w.useCallback(()=>{typeof u=="function"&&u(),y(!0)},[u]);return w.createElement(Oqe,{showLabels:v,rects:r},w.createElement(ly,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:b,onAnimationStart:g,key:p},_=>{var k=_===1?r:r?.map((P,N)=>{var M=m&&m[N];if(M)return Ws(Ws({},P),{},{x:Er(M.x,P.x,_),y:Er(M.y,P.y,_),width:Er(M.width,P.width,_),height:Er(M.height,P.height,_)});if(i==="horizontal"){var A=Er(0,P.height,_),T=Er(P.stackedBarStart,P.y,_);return Ws(Ws({},P),{},{y:T,height:A})}var C=Er(0,P.width,_),F=Er(P.stackedBarStart,P.x,_);return Ws(Ws({},P),{},{width:C,x:F})});return _>0&&(n.current=k??null),k==null?null:w.createElement(Pa,null,w.createElement(Uqe,{props:e,data:k}))}),w.createElement(CT,{label:e.label}),e.children)}function Hqe(t){var e=w.useRef(null);return w.createElement(Bqe,{previousRectanglesRef:e,props:t})}var rae=0,qqe=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:Dr(t,e)}};class $qe extends w.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:i,xAxisId:s,yAxisId:o,needClip:l,background:c,id:d}=this.props;if(e||n==null)return null;var u=wr("recharts-bar",i),m=d;return w.createElement(Pa,{className:u,id:d},l&&w.createElement("defs",null,w.createElement(W4,{clipPathId:m,xAxisId:s,yAxisId:o})),w.createElement(Pa,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(m,")"):void 0},w.createElement(Lqe,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),w.createElement(Hqe,this.props)))}}var Vqe={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:rae,xAxisId:0,yAxisId:0,zIndex:Ha.bar};function Gqe(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u}=t,{needClip:m}=DT(e,n),p=rp(),f=Si(),y=O4(t.children,zx),v=dn(_=>yqe(_,t.id,f,y));if(p!=="vertical"&&p!=="horizontal")return null;var b,g=v?.[0];return g==null||g.height==null||g.width==null?b=0:b=p==="vertical"?g.height/2:g.width/2,w.createElement(Lre,{xAxisId:e,yAxisId:n,data:v,dataPointFormatter:qqe,errorBarOffset:b},w.createElement($qe,am({},t,{layout:p,needClip:m,data:v,xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u})))}function Wqe(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:i,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:d,stackedData:u,displayedData:m,offset:p,cells:f,parentViewBox:y,dataStartIndex:v}=t,b=e==="horizontal"?l:o,g=u?b.scale.domain():null,_=MDe({numericAxis:b}),k=b.scale.map(_);return m.map((P,N)=>{var M,A,T,C,F,$;if(u){var I=u[N+v];if(I==null)return null;M=NDe(I,g)}else M=Dr(P,n),Array.isArray(M)||(M=[_,M]);var X=nqe(r,rae)(M[1],N);if(e==="horizontal"){var L,te=l.scale.map(M[0]),ae=l.scale.map(M[1]);if(te==null||ae==null)return null;A=$V({axis:o,ticks:c,bandSize:s,offset:i.offset,entry:P,index:N}),T=(L=ae??te)!==null&&L!==void 0?L:void 0,C=i.size;var ee=te-ae;if(F=Rc(ee)?0:ee,$={x:A,y:p.top,width:C,height:p.height},Math.abs(X)>0&&Math.abs(F)<Math.abs(X)){var me=Li(F||X)*(Math.abs(X)-Math.abs(F));T-=me,F+=me}}else{var le=o.scale.map(M[0]),ue=o.scale.map(M[1]);if(le==null||ue==null)return null;if(A=le,T=$V({axis:l,ticks:d,bandSize:s,offset:i.offset,entry:P,index:N}),C=ue-le,F=i.size,$={x:p.left,y:T,width:p.width,height:F},Math.abs(X)>0&&Math.abs(C)<Math.abs(X)){var K=Li(C||X)*(Math.abs(X)-Math.abs(C));C+=K}}if(A==null||T==null||C==null||F==null)return null;var ne=Ws(Ws({},P),{},{stackedBarStart:k,x:A,y:T,width:C,height:F,value:u?M:M[1],payload:P,background:$,tooltipPosition:{x:A+C/2,y:T+F/2},parentViewBox:y},f&&f[N]&&f[N].props);return ne}).filter(Boolean)}function Kqe(t){var e=Ta(t,Vqe),n=_qe(e.stackId),r=Si();return w.createElement(MT,{id:e.id,type:"bar"},i=>w.createElement(w.Fragment,null,w.createElement(q4,{legendPayload:Fqe(e)}),w.createElement(Rqe,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:i}),w.createElement($4,{type:"bar",id:i,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:n,hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:r}),w.createElement(Ls,{zIndex:e.zIndex},w.createElement(Gqe,am({},e,{id:i})))))}var Hb=w.memo(Kqe,cS);Hb.displayName="Bar";var Yqe=["domain","range"],Xqe=["domain","range"];function pW(t,e){if(t==null)return{};var n,r,i=Qqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function Qqe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function fW(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 aae(t,e){if(t===e)return!0;var{domain:n,range:r}=t,i=pW(t,Yqe),{domain:s,range:o}=e,l=pW(e,Xqe);return!fW(n,s)||!fW(r,o)?!1:cS(i,l)}var Zqe=["type"],Jqe=["dangerouslySetInnerHTML","ticks","scale"],e$e=["id","scale"];function WR(){return WR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},WR.apply(null,arguments)}function gW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function bW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gW(Object(n),!0).forEach(function(r){t$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function t$e(t,e,n){return(e=n$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function n$e(t){var e=r$e(t,"string");return typeof e=="symbol"?e:e+""}function r$e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function KR(t,e){if(t==null)return{};var n,r,i=a$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function a$e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function i$e(t){var e=ta(),n=w.useRef(null),r=wI(),{type:i}=t,s=KR(t,Zqe),o=pT(r,"xAxis",i),l=w.useMemo(()=>{if(o!=null)return bW(bW({},s),{},{type:o})},[s,o]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(XBe(l)):n.current!==l&&e(QBe({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(ZBe(n.current)),n.current=null)},[e]),null}var s$e=t=>{var{xAxisId:e,className:n}=t,r=dn(gI),i=Si(),s="xAxis",o=dn(g=>Pne(g,s,e,i)),l=dn(g=>_ne(g,e)),c=dn(g=>$Ie(g,e)),d=dn(g=>ane(g,e));if(l==null||c==null||d==null)return null;var{dangerouslySetInnerHTML:u,ticks:m,scale:p}=t,f=KR(t,Jqe),{id:y,scale:v}=d,b=KR(d,e$e);return w.createElement(G4,WR({},f,b,{x:c.x,y:c.y,width:l.width,height:l.height,className:wr("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:o,axisType:s}))},o$e={allowDataOverflow:ji.allowDataOverflow,allowDecimals:ji.allowDecimals,allowDuplicatedCategory:ji.allowDuplicatedCategory,angle:ji.angle,axisLine:Bu.axisLine,height:ji.height,hide:!1,includeHidden:ji.includeHidden,interval:ji.interval,label:!1,minTickGap:ji.minTickGap,mirror:ji.mirror,orientation:ji.orientation,padding:ji.padding,reversed:ji.reversed,scale:ji.scale,tick:ji.tick,tickCount:ji.tickCount,tickLine:Bu.tickLine,tickSize:Bu.tickSize,type:ji.type,xAxisId:0},l$e=t=>{var e=Ta(t,o$e);return w.createElement(w.Fragment,null,w.createElement(i$e,{allowDataOverflow:e.allowDataOverflow,allowDecimals:e.allowDecimals,allowDuplicatedCategory:e.allowDuplicatedCategory,angle:e.angle,dataKey:e.dataKey,domain:e.domain,height:e.height,hide:e.hide,id:e.xAxisId,includeHidden:e.includeHidden,interval:e.interval,minTickGap:e.minTickGap,mirror:e.mirror,name:e.name,orientation:e.orientation,padding:e.padding,reversed:e.reversed,scale:e.scale,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit}),w.createElement(s$e,e))},mf=w.memo(l$e,aae);mf.displayName="XAxis";var c$e=["type"],d$e=["dangerouslySetInnerHTML","ticks","scale"],u$e=["id","scale"];function YR(){return YR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},YR.apply(null,arguments)}function xW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function yW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?xW(Object(n),!0).forEach(function(r){m$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):xW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function m$e(t,e,n){return(e=h$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function h$e(t){var e=p$e(t,"string");return typeof e=="symbol"?e:e+""}function p$e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function XR(t,e){if(t==null)return{};var n,r,i=f$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function f$e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function g$e(t){var e=ta(),n=w.useRef(null),r=wI(),{type:i}=t,s=XR(t,c$e),o=pT(r,"yAxis",i),l=w.useMemo(()=>{if(o!=null)return yW(yW({},s),{},{type:o})},[o,s]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(JBe(l)):n.current!==l&&e(e8e({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(t8e(n.current)),n.current=null)},[e]),null}function b$e(t){var{yAxisId:e,className:n,width:r,label:i}=t,s=w.useRef(null),o=w.useRef(null),l=dn(gI),c=Si(),d=ta(),u="yAxis",m=dn(M=>kne(M,e)),p=dn(M=>GIe(M,e)),f=dn(M=>Pne(M,u,e,c)),y=dn(M=>ine(M,e));if(w.useLayoutEffect(()=>{if(!(r!=="auto"||!m||D4(i)||w.isValidElement(i)||y==null)){var M=s.current;if(M){var A=M.getCalculatedWidth();Math.round(m.width)!==Math.round(A)&&d(n8e({id:e,width:A}))}}},[f,m,d,i,e,r,y]),m==null||p==null||y==null)return null;var{dangerouslySetInnerHTML:v,ticks:b,scale:g}=t,_=XR(t,d$e),{id:k,scale:P}=y,N=XR(y,u$e);return w.createElement(G4,YR({},_,N,{ref:s,labelRef:o,x:p.x,y:p.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:m.width,height:m.height,className:wr("recharts-".concat(u," ").concat(u),n),viewBox:l,ticks:f,axisType:u}))}var x$e={allowDataOverflow:Ei.allowDataOverflow,allowDecimals:Ei.allowDecimals,allowDuplicatedCategory:Ei.allowDuplicatedCategory,angle:Ei.angle,axisLine:Bu.axisLine,hide:!1,includeHidden:Ei.includeHidden,interval:Ei.interval,label:!1,minTickGap:Ei.minTickGap,mirror:Ei.mirror,orientation:Ei.orientation,padding:Ei.padding,reversed:Ei.reversed,scale:Ei.scale,tick:Ei.tick,tickCount:Ei.tickCount,tickLine:Bu.tickLine,tickSize:Bu.tickSize,type:Ei.type,width:Ei.width,yAxisId:0},y$e=t=>{var e=Ta(t,x$e);return w.createElement(w.Fragment,null,w.createElement(g$e,{interval:e.interval,id:e.yAxisId,scale:e.scale,type:e.type,domain:e.domain,allowDataOverflow:e.allowDataOverflow,dataKey:e.dataKey,allowDuplicatedCategory:e.allowDuplicatedCategory,allowDecimals:e.allowDecimals,tickCount:e.tickCount,padding:e.padding,includeHidden:e.includeHidden,reversed:e.reversed,ticks:e.ticks,width:e.width,orientation:e.orientation,mirror:e.mirror,hide:e.hide,unit:e.unit,name:e.name,angle:e.angle,minTickGap:e.minTickGap,tick:e.tick,tickFormatter:e.tickFormatter}),w.createElement(b$e,e))},hf=w.memo(y$e,aae);hf.displayName="YAxis";var v$e=(t,e)=>e,Y4=yt([v$e,yr,tne,Ui,$ne,dm,oze,wi],pze),X4=t=>{var e=t.currentTarget.getBoundingClientRect(),n=e.width/t.currentTarget.offsetWidth,r=e.height/t.currentTarget.offsetHeight;return{chartX:Math.round((t.clientX-e.left)/n),chartY:Math.round((t.clientY-e.top)/r)}},iae=ec("mouseClick"),sae=Vw();sae.startListening({actionCreator:iae,effect:(t,e)=>{var n=t.payload,r=Y4(e.getState(),X4(n));r?.activeIndex!=null&&e.dispatch(s4e({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var QR=ec("mouseMove"),oae=Vw(),G1=null;oae.startListening({actionCreator:QR,effect:(t,e)=>{var n=t.payload;G1!==null&&cancelAnimationFrame(G1);var r=X4(n);G1=requestAnimationFrame(()=>{var i=e.getState(),s=S4(i,i.tooltip.settings.shared);if(s==="axis"){var o=Y4(i,r);o?.activeIndex!=null?e.dispatch(Rne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(Fne())}G1=null})}});function w$e(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 vW={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},lae=Do({name:"rootProps",initialState:vW,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:vW.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}}}),S$e=lae.reducer,{updateOptions:_$e}=lae.actions,k$e=null,N$e={updatePolarOptions:(t,e)=>e.payload},cae=Do({name:"polarOptions",initialState:k$e,reducers:N$e}),{updatePolarOptions:C$e}=cae.actions,P$e=cae.reducer,dae=ec("keyDown"),uae=ec("focus"),Q4=Vw();Q4.startListening({actionCreator:dae,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=_4(i,xy(n),iS(n),oS(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=dm(n);if(s==="Enter"){var d=lC(n,"axis","hover",String(i.index));e.dispatch(IR({active:!i.active,activeIndex:i.index,activeCoordinate:d}));return}var u=XIe(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 y=lC(n,"axis","hover",String(f));e.dispatch(IR({active:!0,activeIndex:f.toString(),activeCoordinate:y}))}}}}}});Q4.startListening({actionCreator:uae,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip;if(!i.active&&i.index==null){var s="0",o=lC(n,"axis","hover",String(s));e.dispatch(IR({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Tl=ec("externalEvent"),mae=Vw(),uD=new Map;mae.startListening({actionCreator:Tl,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var i=r.type,s=uD.get(i);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:G4e(l),activeDataKey:T4(l),activeIndex:Yh(l),activeLabel:Wne(l),activeTooltipIndex:Yh(l),isTooltipActive:W4e(l)};n(c,r)}finally{uD.delete(i)}});uD.set(i,o)}}});var T$e=yt([gy],t=>t.tooltipItemPayloads),A$e=yt([T$e,(t,e)=>e,(t,e,n)=>n],(t,e,n)=>{if(e!=null){var r=t.find(s=>s.settings.graphicalItemId===n);if(r!=null){var{getPosition:i}=r;if(i!=null)return i(e)}}}),hae=ec("touchMove"),pae=Vw();pae.startListening({actionCreator:hae,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),i=S4(r,r.tooltip.settings.shared);if(i==="axis"){var s=n.touches[0];if(s==null)return;var o=Y4(r,X4({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(Rne({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(Pee),m=(l=d.getAttribute(Tee))!==null&&l!==void 0?l:void 0,p=by(r).find(v=>v.id===m);if(u==null||p==null||m==null)return;var{dataKey:f}=p,y=A$e(r,u,m);e.dispatch(Dne({activeDataKey:f,activeIndex:u,activeCoordinate:y,activeGraphicalItemId:m}))}}}});var M$e=KJ({brush:v8e,cartesianAxis:r8e,chartData:Vze,errorBars:M6e,graphicalItems:uBe,layout:vDe,legend:C3e,options:Uze,polarAxis:NUe,polarOptions:P$e,referenceElements:T8e,rootProps:S$e,tooltip:o4e,zIndex:Tze}),j$e=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return V2e({reducer:M$e,preloadedState:e,middleware:r=>{var i;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((i="es6")!==null&&i!==void 0?i:"")}).concat([sae.middleware,oae.middleware,Q4.middleware,mae.middleware,pae.middleware])},enhancers:r=>{var i=r;return typeof r=="function"&&(i=r()),i.concat(cee({type:"raf"}))},devTools:{serialize:{replacer:w$e},name:"recharts-".concat(n)}})};function fae(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,i=Si(),s=w.useRef(null);if(i)return n;s.current==null&&(s.current=j$e(e,r));var o=cI;return w.createElement(aHe,{context:o,store:s.current},n)}function E$e(t){var{layout:e,margin:n}=t,r=ta(),i=Si();return w.useEffect(()=>{i||(r(bDe(e)),r(gDe(n)))},[r,i,e,n]),null}var gae=w.memo(E$e,cS);function bae(t){var e=ta();return w.useEffect(()=>{e(_$e(t))},[e,t]),null}function wW(t){var{zIndex:e,isPanorama:n}=t,r=w.useRef(null),i=ta();return w.useLayoutEffect(()=>(r.current&&i(Cze({zIndex:e,element:r.current,isPanorama:n})),()=>{i(Pze({zIndex:e,isPanorama:n}))}),[i,e,n]),w.createElement("g",{tabIndex:-1,ref:r})}function SW(t){var{children:e,isPanorama:n}=t,r=dn(gze);if(!r||r.length===0)return e;var i=r.filter(o=>o<0),s=r.filter(o=>o>0);return w.createElement(w.Fragment,null,i.map(o=>w.createElement(wW,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>w.createElement(wW,{key:o,zIndex:o,isPanorama:n})))}var D$e=["children"];function F$e(t,e){if(t==null)return{};var n,r,i=R$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function R$e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function xC(){return xC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},xC.apply(null,arguments)}var L$e={width:"100%",height:"100%",display:"block"},O$e=w.forwardRef((t,e)=>{var n=yI(),r=vI(),i=Vee();if(!Pd(n)||!Pd(r))return null;var{children:s,otherAttributes:o,title:l,desc:c}=t,d,u;return o!=null&&(typeof o.tabIndex=="number"?d=o.tabIndex:d=i?0:void 0,typeof o.role=="string"?u=o.role:u=i?"application":void 0),w.createElement(ZO,xC({},o,{title:l,desc:c,role:u,tabIndex:d,width:n,height:r,style:L$e,ref:e}),s)}),I$e=t=>{var{children:e}=t,n=dn(nT);if(!n)return null;var{width:r,height:i,y:s,x:o}=n;return w.createElement(ZO,{width:r,height:i,x:o,y:s},e)},_W=w.forwardRef((t,e)=>{var{children:n}=t,r=F$e(t,D$e),i=Si();return i?w.createElement(I$e,null,w.createElement(SW,{isPanorama:!0},n)):w.createElement(O$e,xC({ref:e},r),w.createElement(SW,{isPanorama:!1},n))});function z$e(){var t=ta(),[e,n]=w.useState(null),r=dn(LDe);return w.useEffect(()=>{if(e!=null){var i=e.getBoundingClientRect(),s=i.width/e.offsetWidth;qn(s)&&s!==r&&t(yDe(s))}},[e,t,r]),n}function kW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function U$e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?kW(Object(n),!0).forEach(function(r){B$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):kW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function B$e(t,e,n){return(e=H$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function H$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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zh(){return zh=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},zh.apply(null,arguments)}var $$e=()=>(e5e(),null);function yC(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var V$e=w.forwardRef((t,e)=>{var n,r,i=w.useRef(null),[s,o]=w.useState({containerWidth:yC((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:yC((r=t.style)===null||r===void 0?void 0:r.height)}),l=w.useCallback((d,u)=>{o(m=>{var p=Math.round(d),f=Math.round(u);return m.containerWidth===p&&m.containerHeight===f?m:{containerWidth:p,containerHeight:f}})},[]),c=w.useCallback(d=>{if(typeof e=="function"&&e(d),d!=null&&typeof ResizeObserver<"u"){var{width:u,height:m}=d.getBoundingClientRect();l(u,m);var p=y=>{var v=y[0];if(v!=null){var{width:b,height:g}=v.contentRect;l(b,g)}},f=new ResizeObserver(p);f.observe(d),i.current=f}},[e,l]);return w.useEffect(()=>()=>{var d=i.current;d?.disconnect()},[l]),w.createElement(w.Fragment,null,w.createElement(Kw,{width:s.containerWidth,height:s.containerHeight}),w.createElement("div",zh({ref:c},t)))}),G$e=w.forwardRef((t,e)=>{var{width:n,height:r}=t,[i,s]=w.useState({containerWidth:yC(n),containerHeight:yC(r)}),o=w.useCallback((c,d)=>{s(u=>{var m=Math.round(c),p=Math.round(d);return u.containerWidth===m&&u.containerHeight===p?u:{containerWidth:m,containerHeight:p}})},[]),l=w.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:d,height:u}=c.getBoundingClientRect();o(d,u)}},[e,o]);return w.createElement(w.Fragment,null,w.createElement(Kw,{width:i.containerWidth,height:i.containerHeight}),w.createElement("div",zh({ref:l},t)))}),W$e=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return w.createElement(w.Fragment,null,w.createElement(Kw,{width:n,height:r}),w.createElement("div",zh({ref:e},t)))}),K$e=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return typeof n=="string"||typeof r=="string"?w.createElement(G$e,zh({},t,{ref:e})):typeof n=="number"&&typeof r=="number"?w.createElement(W$e,zh({},t,{width:n,height:r,ref:e})):w.createElement(w.Fragment,null,w.createElement(Kw,{width:n,height:r}),w.createElement("div",zh({ref:e},t)))});function Y$e(t){return t?V$e:K$e}var X$e=w.forwardRef((t,e)=>{var{children:n,className:r,height:i,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:d,onMouseLeave:u,onMouseMove:m,onMouseUp:p,onTouchEnd:f,onTouchMove:y,onTouchStart:v,style:b,width:g,responsive:_,dispatchTouchEvents:k=!0}=t,P=w.useRef(null),N=ta(),[M,A]=w.useState(null),[T,C]=w.useState(null),F=z$e(),$=bI(),I=$?.width>0?$.width:g,X=$?.height>0?$.height:i,L=w.useCallback(j=>{F(j),typeof e=="function"&&e(j),A(j),C(j),j!=null&&(P.current=j)},[F,e,A,C]),te=w.useCallback(j=>{N(iae(j)),N(Tl({handler:s,reactEvent:j}))},[N,s]),ae=w.useCallback(j=>{N(QR(j)),N(Tl({handler:d,reactEvent:j}))},[N,d]),ee=w.useCallback(j=>{N(Fne()),N(Tl({handler:u,reactEvent:j}))},[N,u]),me=w.useCallback(j=>{N(QR(j)),N(Tl({handler:m,reactEvent:j}))},[N,m]),le=w.useCallback(()=>{N(uae())},[N]),ue=w.useCallback(j=>{N(dae(j.key))},[N]),K=w.useCallback(j=>{N(Tl({handler:o,reactEvent:j}))},[N,o]),ne=w.useCallback(j=>{N(Tl({handler:l,reactEvent:j}))},[N,l]),oe=w.useCallback(j=>{N(Tl({handler:c,reactEvent:j}))},[N,c]),be=w.useCallback(j=>{N(Tl({handler:p,reactEvent:j}))},[N,p]),_e=w.useCallback(j=>{N(Tl({handler:v,reactEvent:j}))},[N,v]),B=w.useCallback(j=>{k&&N(hae(j)),N(Tl({handler:y,reactEvent:j}))},[N,k,y]),Y=w.useCallback(j=>{N(Tl({handler:f,reactEvent:j}))},[N,f]),D=Y$e(_);return w.createElement(tre.Provider,{value:M},w.createElement(dJ.Provider,{value:T},w.createElement(D,{width:I??b?.width,height:X??b?.height,className:wr("recharts-wrapper",r),style:U$e({position:"relative",cursor:"default",width:I,height:X},b),onClick:te,onContextMenu:K,onDoubleClick:ne,onFocus:le,onKeyDown:ue,onMouseDown:oe,onMouseEnter:ae,onMouseLeave:ee,onMouseMove:me,onMouseUp:be,onTouchEnd:Y,onTouchMove:B,onTouchStart:_e,ref:L},w.createElement($$e,null),n)))}),Q$e=["width","height","responsive","children","className","style","compact","title","desc"];function Z$e(t,e){if(t==null)return{};var n,r,i=J$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function J$e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var xae=w.forwardRef((t,e)=>{var{width:n,height:r,responsive:i,children:s,className:o,style:l,compact:c,title:d,desc:u}=t,m=Z$e(t,Q$e),p=to(m);return c?w.createElement(w.Fragment,null,w.createElement(Kw,{width:n,height:r}),w.createElement(_W,{otherAttributes:p,title:d,desc:u},s)):w.createElement(X$e,{className:o,style:l,width:n,height:r,responsive:i??!1,onClick:t.onClick,onMouseLeave:t.onMouseLeave,onMouseEnter:t.onMouseEnter,onMouseMove:t.onMouseMove,onMouseDown:t.onMouseDown,onMouseUp:t.onMouseUp,onContextMenu:t.onContextMenu,onDoubleClick:t.onDoubleClick,onTouchStart:t.onTouchStart,onTouchMove:t.onTouchMove,onTouchEnd:t.onTouchEnd},w.createElement(_W,{otherAttributes:p,title:d,desc:u,ref:e},w.createElement(A8e,null,s)))});function ZR(){return ZR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ZR.apply(null,arguments)}var eVe={top:5,right:5,bottom:5,left:5},tVe={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:eVe,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},Z4=w.forwardRef(function(e,n){var r,i=Ta(e.categoricalChartProps,tVe),{chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,categoricalChartProps:d}=e,u={chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return w.createElement(fae,{preloadedState:{options:u},reduxStoreName:(r=d.id)!==null&&r!==void 0?r:s},w.createElement(Are,{chartData:d.data}),w.createElement(gae,{layout:i.layout,margin:i.margin}),w.createElement(bae,{baseValue:i.baseValue,accessibilityLayer:i.accessibilityLayer,barCategoryGap:i.barCategoryGap,maxBarSize:i.maxBarSize,stackOffset:i.stackOffset,barGap:i.barGap,barSize:i.barSize,syncId:i.syncId,syncMethod:i.syncMethod,className:i.className,reverseStackOrder:i.reverseStackOrder}),w.createElement(xae,ZR({},i,{ref:n})))}),nVe=["axis"],rVe=w.forwardRef((t,e)=>w.createElement(Z4,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:nVe,tooltipPayloadSearcher:kT,categoricalChartProps:t,ref:e})),aVe=["axis","item"],W1=w.forwardRef((t,e)=>w.createElement(Z4,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:aVe,tooltipPayloadSearcher:kT,categoricalChartProps:t,ref:e}));function iVe(t){var e=ta();return w.useEffect(()=>{e(C$e(t))},[e,t]),null}var sVe=["layout"];function JR(){return JR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},JR.apply(null,arguments)}function oVe(t,e){if(t==null)return{};var n,r,i=lVe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function lVe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var cVe={top:5,right:5,bottom:5,left:5},yae={accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:cVe,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},dVe=w.forwardRef(function(e,n){var r,i=Ta(e.categoricalChartProps,yae),{layout:s}=i,o=oVe(i,sVe),{chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u}=e,m={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u,eventEmitter:void 0};return w.createElement(fae,{preloadedState:{options:m},reduxStoreName:(r=i.id)!==null&&r!==void 0?r:l},w.createElement(Are,{chartData:i.data}),w.createElement(gae,{layout:s,margin:i.margin}),w.createElement(bae,{baseValue:void 0,accessibilityLayer:i.accessibilityLayer,barCategoryGap:i.barCategoryGap,maxBarSize:i.maxBarSize,stackOffset:i.stackOffset,barGap:i.barGap,barSize:i.barSize,syncId:i.syncId,syncMethod:i.syncMethod,className:i.className,reverseStackOrder:i.reverseStackOrder}),w.createElement(iVe,{cx:i.cx,cy:i.cy,startAngle:i.startAngle,endAngle:i.endAngle,innerRadius:i.innerRadius,outerRadius:i.outerRadius}),w.createElement(xae,JR({},o,{ref:n})))});function NW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function CW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?NW(Object(n),!0).forEach(function(r){uVe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):NW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function uVe(t,e,n){return(e=mVe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mVe(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 r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var pVe=["item"],fVe=CW(CW({},yae),{},{layout:"centric",startAngle:0,endAngle:360}),PW=w.forwardRef((t,e)=>{var n=Ta(t,fVe);return w.createElement(dVe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:pVe,tooltipPayloadSearcher:kT,categoricalChartProps:n,ref:e})}),gVe=["axis"],bVe=w.forwardRef((t,e)=>w.createElement(Z4,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:gVe,tooltipPayloadSearcher:kT,categoricalChartProps:t,ref:e}));const TW=[{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 xVe({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:i,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Lt(),{mode:d}=cg(),[u,m]=w.useState("24h"),[p,f]=w.useState(o),y=d==="dark",{data:v}=et({queryKey:["settings"],queryFn:pe.getSettings}),b=v?.time_format||"system";w.useEffect(()=>{if(!t)return;const Y=D=>{D.key==="Escape"&&e()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[t,e]);const g=TW.find(Y=>Y.value===u)?.hours||24,{data:_,isLoading:k,error:P}=et({queryKey:["ams-history",n,i,g],queryFn:()=>pe.getAMSHistory(n,i,g),enabled:t,refetchInterval:6e4});if(!t)return null;const N=_?.data.map(Y=>({time:(Qn(Y.recorded_at)||new Date).getTime(),humidity:Y.humidity,temperature:Y.temperature}))||[],M=Date.now()-g*60*60*1e3,A=Date.now(),T=[...N];if(T.length>0){const Y=T[0];Y.time>M&&T.unshift({...Y,time:M});const D=T[T.length-1];D.time<A&&T.push({...D,time:A})}const C=l?.humidityGood||40,F=l?.humidityFair||60,$=l?.tempGood||30,I=l?.tempFair||35,X=T[T.length-1],L=X?.humidity,te=X?.temperature,ae=Y=>{const D=Y.filter(O=>O!=null);if(D.length<4)return"stable";const j=D.slice(0,Math.floor(D.length/4)),z=D.slice(-Math.floor(D.length/4)),W=j.reduce((O,G)=>O+G,0)/j.length,de=z.reduce((O,G)=>O+G,0)/z.length-W;return Math.abs(de)<2?"stable":de>0?"up":"down"},ee=ae(T.map(Y=>Y.humidity)),me=ae(T.map(Y=>Y.temperature)),le=({trend:Y})=>Y==="up"?a.jsx($3,{className:"w-4 h-4 text-red-400"}):Y==="down"?a.jsx(fO,{className:"w-4 h-4 text-green-400"}):a.jsx(rN,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),ue=Y=>Y==null?"#9ca3af":Y<=C?"#22a352":Y<=F?"#d4a017":"#c62828",K=Y=>Y==null?"#9ca3af":Y<=$?"#22a352":Y<=I?"#d4a017":"#c62828",ne=y?"#2d2d2d":"#ffffff",oe=y?"#1d1d1d":"#f3f4f6",be=y?"#3d3d3d":"#e5e7eb",_e=y?"#ffffff":"#111827",B=y?"#9ca3af":"#4b5563";return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:ne},onClick:Y=>Y.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:be},children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold",style:{color:_e},children:[s," ",c("common.history","History")]}),a.jsx("p",{className:"text-sm",style:{color:B},children:r})]}),a.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:B},children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[a.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[a.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:oe},children:[a.jsxs("button",{onClick:()=>f("humidity"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="humidity"?"bg-blue-600 text-white":""}`,style:p!=="humidity"?{color:B}:void 0,children:[a.jsx(mO,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),a.jsxs("button",{onClick:()=>f("temperature"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="temperature"?"bg-orange-600 text-white":""}`,style:p!=="temperature"?{color:B}:void 0,children:[a.jsx(PP,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),a.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:oe},children:TW.map(Y=>a.jsx("button",{onClick:()=>m(Y.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${u===Y.value?"bg-bambu-green text-white":""}`,style:u!==Y.value?{color:B}:void 0,children:Y.label},Y.value))})]}),a.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:ue(L)},children:L!=null?`${L}%`:"—"}),a.jsx(le,{trend:ee})]})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:_e},children:_?.avg_humidity!=null?`${_.avg_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-green-500",children:_?.min_humidity!=null?`${_.min_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_humidity!=null?`${_.max_humidity}%`:"—"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:K(te)},children:te!=null?`${te}°C`:"—"}),a.jsx(le,{trend:me})]})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:_e},children:_?.avg_temperature!=null?`${_.avg_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-blue-500",children:_?.min_temperature!=null?`${_.min_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:B},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_temperature!=null?`${_.max_temperature}°C`:"—"})]})]})}),a.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:k?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:B},children:c("common.loading","Loading...")}):P?a.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):T.length===0?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:B},children:c("common.noData","No data available for this time range")}):a.jsx(_h,{width:"100%",height:300,children:a.jsxs(rVe,{data:T,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:y?"#3d3d3d":"#e5e7eb"}),a.jsx(mf,{dataKey:"time",type:"number",domain:[Date.now()-g*60*60*1e3,Date.now()],tickFormatter:Y=>{const D=new Date(Y);return g>24?D.toLocaleDateString([],{day:"numeric",month:"short"}):D.toLocaleTimeString([],O0({hour:"2-digit",minute:"2-digit"},b))},stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12}}),a.jsx(hf,{stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:Y=>p==="humidity"?`${Y}%`:`${Y}°C`}),a.jsx(kh,{contentStyle:{backgroundColor:y?"#2d2d2d":"#ffffff",border:`1px solid ${y?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:y?"#fff":"#000"},labelFormatter:Y=>new Date(Y).toLocaleString(void 0,O0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},b)),formatter:Y=>[p==="humidity"?`${Y??0}%`:`${Y??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),a.jsx($ee,{}),p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsx(Xv,{y:C,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(Xv,{y:F,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):a.jsxs(a.Fragment,{children:[a.jsx(Xv,{y:$,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(Xv,{y:I,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),a.jsx($re,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),a.jsx("div",{className:"text-xs text-center",style:{color:B},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}const vC={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function yVe(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,d=0;if(s!==o){const u=s-o;d=l>.5?u/(2-s-o):u/(s+o);const m=n/255,p=r/255,f=i/255;s===m?c=((p-f)/u+(p<f?6:0))/6:s===p?c=((f-m)/u+2)/6:c=((m-p)/u+4)/6}return c=c*360,l<.15?"Black":l>.85?"White":d<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c>=15&&c<45&&l<.45||c>=45&&c<70&&l<.4?"Brown":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function Vl(t){const e=t.replace("#","").toLowerCase().substring(0,6);return vC[e]?vC[e]:yVe(t)}function FT(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(vC[n])return vC[n]}return null}function J4(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),i=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return i===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${i})`}function vae(t){if(!t||t.length<6)return!1;const e=t.replace("#",""),n=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);return(.299*n+.587*r+.114*i)/255>.6}function mD({data:t,children:e,disabled:n,className:r="",spoolman:i,inventory:s,configureSlot:o}){const{t:l}=Lt(),[c,d]=w.useState(!1),[u,m]=w.useState("top"),[p,f]=w.useState(!1),[y,v]=w.useState(!1),b=w.useRef(null),g=w.useRef(null),_=w.useRef(null),k=()=>{const F=t.trayUuid;F&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(F).then(()=>{f(!0),setTimeout(()=>f(!1),2e3)}).catch(()=>{P(F)}):P(F))},P=F=>{const $=document.createElement("textarea");$.value=F,$.style.position="fixed",$.style.opacity="0",document.body.appendChild($),$.select();try{document.execCommand("copy"),f(!0),setTimeout(()=>f(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild($)};w.useEffect(()=>{if(c&&b.current&&g.current){const F=b.current.getBoundingClientRect(),$=g.current.offsetHeight,X=F.top-56,L=window.innerHeight-F.bottom;X<$+12&&L>X?m("bottom"):m("top")}},[c]);const N=()=>{n||(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>d(!0),80))},M=()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>d(!1),100)};w.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const A=F=>F<=15?"#ef4444":F<=30?"#f97316":F<=50?"#eab308":"#22c55e",T=t.colorHex?`#${t.colorHex.replace("#","")}`:null,C=s?.assignedSpool?.remainingWeightGrams??null;return a.jsxs("div",{ref:b,className:`relative ${r}`,onMouseEnter:N,onMouseLeave:M,children:[e,c&&a.jsxs("div",{ref:g,className:`
  8124. absolute left-1/2 -translate-x-1/2 z-[60]
  8125. ${u==="top"?"bottom-full mb-2":"top-full mt-2"}
  8126. animate-in fade-in-0 zoom-in-95 duration-150
  8127. `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsxs("div",{className:`
  8128. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8129. rounded-lg shadow-xl overflow-hidden
  8130. backdrop-blur-sm
  8131. `,children:[a.jsxs("div",{className:"h-12 relative overflow-hidden",style:{backgroundColor:T||"#3d3d3d"},children:[a.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-white/10 to-transparent"}),a.jsx("div",{className:`
  8132. absolute inset-0 flex items-center justify-center
  8133. font-semibold text-sm tracking-wide
  8134. ${vae(T)?"text-black/80":"text-white/90"}
  8135. `,children:t.colorName}),a.jsx("div",{className:`
  8136. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  8137. ${t.vendor==="Bambu Lab"?"bg-black/60 text-white":"bg-black/50 text-white/90"}
  8138. `,children:t.vendor==="Bambu Lab"?"BBL":"GEN"})]}),a.jsxs("div",{className:"p-3 space-y-2.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.profile")}),a.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[120px]",children:t.profile})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.kFactor")}),a.jsx("span",{className:"text-xs text-bambu-green font-mono font-bold",children:t.kFactor})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1",children:[a.jsx(mO,{className:"w-3 h-3"}),l("ams.fill")]}),a.jsxs("span",{className:"text-xs text-white font-semibold flex items-center gap-1",children:[a.jsx("span",{children:t.fillLevel!==null?`${t.fillLevel}%`:"—"}),C!==null&&t.fillLevel!==null&&a.jsxs("span",{className:"text-[9px] text-bambu-gray font-normal",children:["• ",C,"g"]}),t.fillSource==="spoolman"&&t.fillLevel!==null&&a.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("spoolman.fillSourceLabel")}),t.fillSource==="inventory"&&t.fillLevel!==null&&a.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("inventory.fillSourceLabel")})]})]}),a.jsx("div",{className:"h-1.5 bg-black/40 rounded-full overflow-hidden",children:t.fillLevel!==null?a.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${t.fillLevel}%`,backgroundColor:A(t.fillLevel)}}):a.jsx("div",{className:"h-full w-full bg-bambu-gray/30 rounded-full"})})]}),i?.enabled&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("spoolman.spoolId")}),t.trayUuid?a.jsxs("button",{onClick:F=>{F.stopPropagation(),k()},className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",title:"Copy spool UUID",children:[a.jsxs("span",{className:"font-mono text-[10px] truncate max-w-[80px]",children:[t.trayUuid.slice(0,8),"..."]}),p?a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}):a.jsx(Mo,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"—"})]}),i.linkedSpoolId&&i.spoolmanUrl&&a.jsxs(a.Fragment,{children:[a.jsxs("a",{href:`${i.spoolmanUrl.replace(/\/$/,"")}/spool/show/${i.linkedSpoolId}`,target:"_blank",rel:"noopener noreferrer",onClick:F=>F.stopPropagation(),className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green",title:l("spoolman.openInSpoolman"),children:[a.jsx(sa,{className:"w-3.5 h-3.5"}),l("spoolman.openInSpoolman")]}),i.onUnlinkSpool&&(t.vendor!=="Bambu Lab"||i.syncMode==="manual")&&a.jsxs("button",{onClick:F=>{F.stopPropagation(),v(!0)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",title:l("spoolman.unlinkSpool"),children:[a.jsx(qh,{className:"w-3.5 h-3.5"}),l("spoolman.unlinkSpool")]})]}),!i.linkedSpoolId&&a.jsxs("button",{onClick:F=>{F.stopPropagation(),i.onLinkSpool&&i.onLinkSpool?.()},disabled:!i.onLinkSpool,className:`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors ${i.onLinkSpool?"bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green":"bg-bambu-gray/10 text-bambu-gray cursor-not-allowed"}`,children:[a.jsx(Lu,{className:"w-3.5 h-3.5"}),l("spoolman.linkToSpoolman")]})]}),s&&t.vendor!=="Bambu Lab"&&a.jsx("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:s.assignedSpool?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Na,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("inventory.assigned")})]}),a.jsxs("p",{className:"text-xs text-white truncate",children:[s.assignedSpool.brand?`${s.assignedSpool.brand} `:"",s.assignedSpool.material,s.assignedSpool.color_name?` - ${s.assignedSpool.color_name}`:""]}),s.onUnassignSpool&&a.jsxs("button",{onClick:F=>{F.stopPropagation(),s.onUnassignSpool?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:[a.jsx(qh,{className:"w-3.5 h-3.5"}),l("inventory.unassignSpool")]})]}):s.onAssignSpool?a.jsxs("button",{onClick:F=>{F.stopPropagation(),s.onAssignSpool?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",children:[a.jsx(Na,{className:"w-3.5 h-3.5"}),l("inventory.assignSpool")]}):null}),o?.enabled&&a.jsx("div",{className:`${i?.enabled&&t.trayUuid?"":"pt-2 mt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("button",{onClick:F=>{F.stopPropagation(),o.onConfigure?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",title:l("ams.configureSlot"),children:[a.jsx(Nd,{className:"w-3.5 h-3.5"}),l("ams.configure")]})})]})]}),a.jsx("div",{className:`
  8139. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8140. border-l-[6px] border-l-transparent
  8141. border-r-[6px] border-r-transparent
  8142. ${u==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8143. `})]}),y&&a.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",onClick:()=>v(!1),children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),a.jsx("div",{className:"relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary",onClick:F=>F.stopPropagation(),children:a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx("h3",{className:"text-base font-semibold text-white",children:l("spoolman.unlinkConfirmTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:l("spoolman.unlinkConfirmMessage")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white",children:l("common.cancel")}),a.jsx("button",{onClick:()=>{i?.onUnlinkSpool?.(),v(!1)},className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:l("spoolman.unlinkSpool")})]})]})})]})]})}function hD({children:t,className:e="",configureSlot:n,inventory:r}){const{t:i}=Lt(),[s,o]=w.useState(!1),l=w.useRef(null),c=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!0),80)},d=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!1),100)};return w.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),a.jsxs("div",{className:`relative ${e}`,onMouseEnter:c,onMouseLeave:d,children:[t,s&&a.jsxs("div",{className:`
  8144. absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50
  8145. animate-in fade-in-0 zoom-in-95 duration-150
  8146. `,children:[a.jsxs("div",{className:`
  8147. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8148. rounded-md shadow-lg overflow-hidden
  8149. `,children:[a.jsx("div",{className:"px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap",children:i("ams.emptySlot")}),n?.enabled&&a.jsx("div",{className:"px-2 pb-2",children:a.jsxs("button",{onClick:u=>{u.stopPropagation(),n.onConfigure?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",title:i("ams.configureSlot"),children:[a.jsx(Nd,{className:"w-3.5 h-3.5"}),i("ams.configure")]})}),r?.onAssignSpool&&a.jsx("div",{className:"px-2 pb-2",children:a.jsxs("button",{onClick:u=>{u.stopPropagation(),r.onAssignSpool?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",children:[a.jsx(Na,{className:"w-3.5 h-3.5"}),i("inventory.assignSpool")]})})]}),a.jsx("div",{className:`
  8150. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  8151. border-l-[5px] border-l-transparent
  8152. border-r-[5px] border-r-transparent
  8153. border-t-[5px] border-t-bambu-dark-tertiary
  8154. `})]})]})}function wae({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:i,amsId:s,trayId:o}){const{t:l}=Lt(),c=mn(),{showToast:d}=xn(),[u,m]=w.useState(""),p=r||n,{data:f,isLoading:y}=et({queryKey:["unlinked-spools"],queryFn:pe.getUnlinkedSpools,enabled:t}),v=w.useMemo(()=>f?f.filter(g=>{if(!u)return!0;const _=u.toLowerCase();return g.filament_name&&g.filament_name.toLowerCase().includes(_)||g.filament_material&&g.filament_material.toLowerCase().includes(_)||String(g.id).includes(_)}):[],[f,u]),b=lt({mutationFn:g=>pe.linkSpool(g,{spoolTag:p,printerId:i,amsId:s,trayId:o}),onSuccess:()=>{c.invalidateQueries({queryKey:["unlinked-spools"]}),c.invalidateQueries({queryKey:["linked-spools"]}),d(l("spoolman.linkSuccess"),"success"),e()},onError:g=>{d(g.message||l("spoolman.linkFailed"),"error")}});return t?a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ny,{className:"w-5 h-5 text-bambu-green"}),l("spoolman.selectSpool")]}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",i]})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-white/10",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:u,onChange:g=>m(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(r||n)&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:r||n,children:["Tag: ",r||n]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:y?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):v.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):v.map(g=>a.jsxs("button",{onClick:()=>b.mutate(g.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:[a.jsx("span",{className:"w-6 h-6 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:g.filament_color_hex?`#${g.filament_color_hex}`:"#808080"}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm text-white font-medium truncate",children:g.filament_name||l("spoolman.spoolId")}),a.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.filament_material||"Unknown"," · #",g.id]})]}),a.jsx("span",{className:"text-xs text-bambu-gray",children:g.remaining_weight!=null?`${Math.round(g.remaining_weight)}g`:"—"})]},g.id))}),a.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:a.jsx(Ie,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function Sae({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:i,trayInfo:s}){const{t:o}=Lt(),l=mn(),{showToast:c}=xn(),[d,u]=w.useState(!1),[m,p]=w.useState(null);w.useEffect(()=>{p(null)},[d]);const[f,y]=w.useState(""),[v,b]=w.useState(null),[g,_]=w.useState(!1),[k,P]=w.useState(null);w.useEffect(()=>{t&&u(!1)},[t]);const{data:N,isLoading:M}=et({queryKey:["inventory-spools"],queryFn:()=>pe.getSpools(),enabled:t}),{data:A}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),enabled:t}),{data:T}=et({queryKey:["settings"],queryFn:()=>pe.getSettings(),enabled:t}),C=lt({mutationFn:le=>pe.assignSpool({spool_id:le,printer_id:n,ams_id:r,tray_id:i}),onSuccess:le=>{l.setQueryData(["spool-assignments"],ue=>{const K=(ue||[]).filter(ne=>!(ne.printer_id===n&&ne.ams_id===r&&ne.tray_id===i));return K.push(le),K}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),_(!1),b(null),P(null),e()},onError:le=>{c(`${o("inventory.assignFailed")}: ${le.message}`,"error")}}),F=le=>(le??"").trim().toUpperCase(),$=(le,ue)=>{const K=F(le),ne=F(ue);return!K||!ne?"none":K===ne?"exact":ne.includes(K)||K.includes(ne)?"partial":"none"},I=(le,ue)=>{const K=F(le),ne=F(ue);return!K||!ne?!1:K===ne};if(!t)return null;const X=new Set((A||[]).filter(le=>!(le.printer_id===n&&le.ams_id===r&&le.tray_id===i)).map(le=>le.spool_id)),L=r===254||r===255,te=N?.filter(le=>!X.has(le.id)&&(L||!le.tag_uid&&!le.tray_uuid));let ae=te;if(!d&&(s?.profile||s?.type)){const le=F(s.profile||s.type);ae=ae?.filter(ue=>{const K=F(ue.slicer_filament_name||ue.slicer_filament);return le&&K&&K===le})}if(f&&ae){const le=f.toLowerCase();ae=ae.filter(ue=>ue.material.toLowerCase().includes(le)||(ue.brand?.toLowerCase().includes(le)??!1)||(ue.color_name?.toLowerCase().includes(le)??!1)||(ue.subtype?.toLowerCase().includes(le)??!1))}const ee=()=>{if(!m)return;const le=N?.find(ue=>ue.id===m);if(!le){c(o("inventory.assignFailed"),"error");return}if(!T?.disable_filament_warnings&&s){const ue=s.material||s.type,K=$(le.material,ue),ne=le.slicer_filament_name||le.slicer_filament,oe=s.profile||s.type,be=I(ne,oe);if(K!=="exact"||!be){let _e="profile";K==="none"&&!be?_e="material_profile":K==="partial"&&!be?_e="partial_profile":K==="none"?_e="material":K==="partial"&&(_e="partial"),b(m),P({type:_e,spoolMaterial:le.material||"",trayMaterial:ue||"",spoolProfile:ne||void 0,trayProfile:oe||void 0}),_(!0);return}}C.mutate(m)},me=()=>{v&&(C.mutate(v),_(!1),b(null))};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-2xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto",children:[s&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${s.color}`}}),a.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),a.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:f,onChange:le=>y(le.target.value),placeholder:o("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),a.jsx("div",{children:M?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):ae&&ae.length>0?a.jsx("div",{className:"max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2",children:ae.map(le=>a.jsxs("button",{onClick:()=>p(le.id),title:le.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${m===le.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[le.brand?`${le.brand} `:"",le.material,le.subtype?` ${le.subtype}`:""]}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[le.rgba&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${le.rgba.substring(0,6)}`}}),a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:le.color_name||""})]}),le.label_weight&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[Math.max(0,Math.round(le.label_weight-le.weight_used))," / ",le.label_weight,"g"]})]},le.id))}):te&&te.length===0?a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:o("inventory.noManualSpools")})}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),a.jsxs("div",{className:"flex justify-between items-center p-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{id:"disable-filtering-toggle",type:"checkbox",checked:d,onChange:()=>u(le=>!le),className:"accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary"}),a.jsx("label",{htmlFor:"disable-filtering-toggle",className:"text-xs text-bambu-gray select-none cursor-pointer",children:o("inventory.showAllSpools")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Ie,{onClick:ee,disabled:!m||C.isPending,children:C.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]})]}),C.isError&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:C.error.message})]})]}),g&&s&&m&&k&&(()=>{let le="";return k.type==="material"?le=o("inventory.assignMismatchMessage",{spoolMaterial:k.spoolMaterial,trayMaterial:k.trayMaterial,location:s.location}):k.type==="partial"?le=o("inventory.assignPartialMismatchMessage",{spoolMaterial:k.spoolMaterial,trayMaterial:k.trayMaterial,location:s.location}):k.type==="material_profile"?le=`${o("inventory.assignMismatchMessage",{spoolMaterial:k.spoolMaterial,trayMaterial:k.trayMaterial,location:s.location})}
  8155. ${o("inventory.assignProfileMismatchMessage",{spoolProfile:k.spoolProfile||o("common.unknown"),trayProfile:k.trayProfile||o("common.unknown"),location:s.location})}`:k.type==="partial_profile"?le=`${o("inventory.assignPartialMismatchMessage",{spoolMaterial:k.spoolMaterial,trayMaterial:k.trayMaterial,location:s.location})}
  8156. ${o("inventory.assignProfileMismatchMessage",{spoolProfile:k.spoolProfile||o("common.unknown"),trayProfile:k.trayProfile||o("common.unknown"),location:s.location})}`:k.type==="profile"&&(le=o("inventory.assignProfileMismatchMessage",{spoolProfile:k.spoolProfile||o("common.unknown"),trayProfile:k.trayProfile||o("common.unknown"),location:s.location})),a.jsx(kn,{title:o("inventory.assignMismatchTitle"),message:le,confirmText:o("inventory.assignMismatchConfirm"),variant:"warning",isLoading:C.isPending,onConfirm:me,onCancel:()=>{C.isPending||(_(!1),b(null),P(null))}})})()]})}function AW(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return r?`HT-${i}`:`AMS-${i}`}function K1(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 h0=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function MW(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){const s=n.slice(r.index+r[0].length);for(const o of h0)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,r.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of h0){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 vVe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const wVe={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"},jW=[{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"}],EW=[{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 DW(t){const e=t.toLowerCase().trim();return wVe[e]||null}function SVe(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function _ae({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Lt(),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(""),[k,P]=w.useState(!1),[N,M]=w.useState(!1),A=w.useRef(""),{data:T,isLoading:C,isError:F}=et({queryKey:["cloudSettings"],queryFn:()=>pe.getCloudSettings(),enabled:t,retry:!1}),{data:$,isLoading:I}=et({queryKey:["localPresets"],queryFn:()=>pe.getLocalPresets(),enabled:t}),{data:X,isLoading:L}=et({queryKey:["builtinFilaments"],queryFn:()=>pe.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:te,isLoading:ae}=et({queryKey:["kprofiles",n,i],queryFn:()=>pe.getKProfiles(n,i),enabled:t&&!!n}),{data:ee}=et({queryKey:["colorCatalog"],queryFn:()=>pe.getColorCatalog(),enabled:t,staleTime:1/0}),me=lt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const j=d.startsWith("local_"),z=d.startsWith("builtin_"),W=j?parseInt(d.replace("local_",""),10):null,q=z?d.replace("builtin_",""):null,de=j?$?.filament.find(Te=>Te.id===W):null,O=z?X?.find(Te=>Te.filament_id===q):null,G=!j&&!z?T?.filament.find(Te=>Te.setting_id===d):null;if(!j&&!z&&!G)throw new Error("Selected preset not found");if(j&&!de)throw new Error("Selected local preset not found");if(z&&!O)throw new Error("Selected builtin preset not found");const Q=j?de.name:z?O.name:G.name,V=MW(Q),J=m?.slot_id??-1,ie=f||r.trayColor?.slice(0,6)||"FFFFFF",he=Q.replace(/@.+$/,"").trim();let fe,se;const U=V.material.toUpperCase();if(j){const Te=(h0.includes(U)?U:de?.filament_type||V.material||"").toUpperCase(),Fe={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"};fe=Fe[Te]||Fe[Te.replace(/[-\s]?CF$/,"")]||Fe[Te.replace(/\+$/,"")]||Fe[Te.split(/[-\s]/)[0]]||"",se=""}else if(z)fe=q,se="";else if(fe=K1(d),se=d,!d.startsWith("GFS"))try{const Te=await pe.getCloudSettingDetail(d);Te.filament_id?fe=Te.filament_id:Te.base_id&&(fe=K1(Te.base_id),console.log(`Derived tray_info_idx from base_id: ${Te.base_id} -> ${fe}`))}catch(Te){console.warn("Failed to fetch preset detail for filament_id:",Te)}let R=j&&de?.nozzle_temp_min?de.nozzle_temp_min:190,re=j&&de?.nozzle_temp_max?de.nozzle_temp_max:230;if(!j||z||!de?.nozzle_temp_min&&!de?.nozzle_temp_max){const Te=(j?h0.includes(U)?U:de?.filament_type||V.material||"":V.material).toUpperCase();Te.includes("PLA")?(R=190,re=230):Te.includes("PETG")?(R=220,re=260):Te.includes("ABS")||Te.includes("ASA")?(R=240,re=280):Te.includes("TPU")?(R=200,re=240):Te==="PCTG"?(R=220,re=260):Te.includes("PC")?(R=260,re=300):(Te.includes("PA")||Te.includes("NYLON"))&&(R=250,re=290)}const xe=m?.k_value?parseFloat(m.k_value):0,we=j?h0.includes(U)?U:de?.filament_type||V.material||"PLA":V.material||"PLA",ye=await pe.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:fe,tray_type:we,tray_sub_brands:he,tray_color:ie+"FF",nozzle_temp_min:R,nozzle_temp_max:re,cali_idx:J,nozzle_diameter:i,setting_id:se,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:xe}),Ae=j?`local_${W}`:z?`builtin_${q}`:d,ve=j?"local":z?"builtin":"cloud";try{await pe.saveSlotPreset(n,r.amsId,r.trayId,Ae,he,ve)}catch(Te){console.warn("Failed to save slot preset mapping:",Te)}return ye},onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),le=lt({mutationFn:async()=>pe.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),ue=w.useMemo(()=>{const j=g.toLowerCase(),z=[],W=new Set,q=r.savedPresetId,de=r.trayInfoIdx;if(T?.filament)for(const O of T.filament){W.add(O.setting_id);const Q=q===O.setting_id||de&&(O.setting_id===de||K1(O.setting_id)===de);if(!(j&&!O.name.toLowerCase().includes(j))){if(!Q&&s){const V=SVe(O.name);if(V&&V.toUpperCase()!==s.toUpperCase())continue}z.push({id:O.setting_id,name:O.name,source:"cloud",isUser:vVe(O.setting_id)})}}if($?.filament)for(const O of $.filament){const G=`local_${O.id}`;j&&!O.name.toLowerCase().includes(j)||z.push({id:G,name:O.name,source:"local",isUser:!1})}if(X)for(const O of X){if(W.has(O.filament_id))continue;const G=O.filament_id.startsWith("GF")?"GFS"+O.filament_id.slice(2):O.filament_id;W.has(G)||(!j||O.name.toLowerCase().includes(j))&&z.push({id:`builtin_${O.filament_id}`,name:O.name,source:"builtin",isUser:!1})}return z.sort((O,G)=>{const Q={cloud:0,local:1,builtin:2};return O.source!==G.source?Q[O.source]-Q[G.source]:O.isUser&&!G.isUser?-1:!O.isUser&&G.isUser?1:O.name.localeCompare(G.name)})},[T?.filament,$?.filament,X,g,s,r.savedPresetId,r.trayInfoIdx]),K=w.useMemo(()=>{if(!d)return null;let j=null;if(d.startsWith("local_")){const q=parseInt(d.replace("local_",""),10);j=$?.filament.find(O=>O.id===q)?.name||null}else if(d.startsWith("builtin_")){const q=d.replace("builtin_","");j=X?.find(O=>O.filament_id===q)?.name||null}else T?.filament&&(j=T.filament.find(de=>de.setting_id===d)?.name||null);if(!j)return null;let z=j.replace(/@.+$/,"").trim();z.startsWith("# ")&&(z=z.slice(2).trim());const W=MW(z);return{fullName:z,material:W.material,brand:W.brand}},[d,T?.filament,$?.filament,X]),ne=K?.fullName||"",oe=w.useMemo(()=>{if(!ee||!K)return[];const{fullName:j,brand:z}=K,W=j.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return ee.filter(q=>{const de=(q.material||"").toUpperCase(),O=q.manufacturer.toUpperCase();if(!(de===W.toUpperCase()||de.includes(W.toUpperCase())||W.toUpperCase().includes(de)))return!1;if(z){const Q=z.toUpperCase();if(!O.includes(Q)&&!Q.includes(O))return!1}return!0})},[ee,K]),be=w.useMemo(()=>{if(!te?.profiles||!K)return[];const{fullName:j,material:z,brand:W}=K,q=j.toUpperCase(),de=z.toUpperCase(),O=W.toUpperCase();if(!de||de.length<2)return[];const G=te.profiles.filter(V=>{const J=V.name.toUpperCase();if(O)return!(!J.includes(O)||!J.includes(de));if(J.includes(q)||J.includes(de))return!0;const he={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[de]||[];for(const fe of he)if(J.includes(fe))return!0;return!1}),Q=new Map;for(const V of G){const J=`${V.name}|${V.k_value}`,ie=Q.get(J);ie?r.extruderId!==void 0&&V.extruder_id===r.extruderId&&ie.extruder_id!==r.extruderId&&Q.set(J,V):Q.set(J,V)}return Array.from(Q.values())},[te?.profiles,K,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&T?.filament){let j=T.filament.find(z=>z.setting_id===r.trayInfoIdx);j||(j=T.filament.find(z=>K1(z.setting_id)===r.trayInfoIdx)),j&&u(j.setting_id)}else if(r.trayInfoIdx&&X?.length){const j=r.trayInfoIdx,z=X.find(W=>W.filament_id===j);z&&u(`builtin_${z.filament_id}`)}if(r.trayColor){const j=r.trayColor.slice(0,6);j&&y(j)}}else u(""),p(null),y(""),b(""),_(""),P(!1),A.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,T?.filament,X]),w.useEffect(()=>{if(be.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const j=be.find(z=>z.slot_id===r.caliIdx);if(j){p(j);return}}p(be[0])}else p(null)},[d,be,r.caliIdx]);const _e=w.useCallback(j=>{j.key==="Escape"&&e()},[e]);w.useEffect(()=>{if(t)return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[t,_e]);const B=C&&!F||I||L||ae;if(w.useEffect(()=>{if(!B&&d&&d!==A.current){const j=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(j)}},[d,B]),!t)return null;const Y=d&&!me.isPending,D=f||r.trayColor?.slice(0,6)||"FFFFFF";return a.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-5 h-5 text-bambu-blue"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&a.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[a.jsx("span",{className:"text-white/30",children:"|"}),r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:AW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&a.jsxs("span",{children:["(",r.traySubBrands,")"]})]})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[k&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx(Cc,{className:"w-16 h-16 text-bambu-green mx-auto"}),a.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:AW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&a.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),B?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?a.jsxs("div",{className:"flex gap-4 h-full",children:[a.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:ue.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:T?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>a.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:j.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]}),a.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&a.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),be.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m?.name||"",onChange:j=>{const z=be.find(W=>W.name===j.target.value);p(z||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[a.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),be.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):a.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&a.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),oe.length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:K?.fullName})}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:oe.map(j=>a.jsxs("button",{onClick:()=>{const z=j.hex_color.replace("#","").toUpperCase();y(z),b(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),a.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[jW.map(j=>a.jsx("button",{onClick:()=>{y(j.hex),b(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),a.jsx("button",{onClick:()=>M(!N),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EW.map(j=>a.jsx("button",{onClick:()=>{y(j.hex),b(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:j=>{const z=j.target.value;b(z);const W=DW(z);if(W)y(W);else{const q=z.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();q.length===6?y(q):q.length===3&&y(q.split("").map(de=>de+de).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&a.jsx("button",{onClick:()=>{y(""),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&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:ue.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:T?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>a.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:j.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&a.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),be.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m?.name||"",onChange:j=>{const z=be.find(W=>W.name===j.target.value);p(z||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[a.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),be.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):a.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&a.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),oe.length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:K?.fullName})}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:oe.map(j=>a.jsxs("button",{onClick:()=>{const z=j.hex_color.replace("#","").toUpperCase();y(z),b(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),a.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[jW.map(j=>a.jsx("button",{onClick:()=>{y(j.hex),b(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),a.jsx("button",{onClick:()=>M(!N),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EW.map(j=>a.jsx("button",{onClick:()=>{y(j.hex),b(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:j=>{const z=j.target.value;b(z);const W=DW(z);if(W)y(W);else{const q=z.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();q.length===6?y(q):q.length===3&&y(q.split("").map(de=>de+de).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&a.jsx("button",{onClick:()=>{y(""),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&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),a.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>le.mutate(),disabled:le.isPending||me.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:le.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):a.jsxs(a.Fragment,{children:[a.jsx(jo,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),a.jsx(Ie,{onClick:()=>me.mutate(),disabled:!Y,children:me.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):a.jsxs(a.Fragment,{children:[a.jsx(Nd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(me.isError||le.isError)&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:me.error?.message||le.error?.message})]})]})}function kae({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:i,validateFile:s,accept:o}){const{t:l}=Lt(),[c,d]=w.useState([]),[u,m]=w.useState(!1),[p,f]=w.useState(!1),[y,v]=w.useState(!0),[b,g]=w.useState(!1),[_,k]=w.useState(!0),[P,N]=w.useState(null),M=w.useRef(null),A=ue=>{ue.preventDefault(),m(!0)},T=ue=>{ue.preventDefault(),m(!1)},C=ue=>{ue.preventDefault(),m(!1),X(Array.from(ue.dataTransfer.files))},F=ue=>{ue.target.files&&X(Array.from(ue.target.files))},$=(ue,K)=>{d(ne=>ne.map(oe=>oe.file===ue?{...oe,...K}:oe))},I=async ue=>{f(!0);for(const K of ue)if(K.status==="pending"){$(K.file,{status:"uploading"});try{if(K.isZip){const ne=await pe.extractZipFile(K.file,t,y,b,_);$(K.file,{status:ne.errors.length>0&&ne.extracted===0?"error":"success",extractedCount:ne.extracted,error:ne.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ne.errors.length}):void 0})}else{const ne=await pe.uploadLibraryFile(K.file,t,_);$(K.file,{status:"success"});const oe=r?.(ne);if(oe){N(oe),d([]),f(!1);return}}}catch(ne){$(K.file,{status:"error",error:ne instanceof Error?ne.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},X=ue=>{if(N(null),s)for(const ne of ue){const oe=s(ne);if(oe){N(oe);return}}const K=ue.map(ne=>({file:ne,status:"pending",isZip:ne.name.toLowerCase().endsWith(".zip"),is3mf:ne.name.toLowerCase().endsWith(".3mf")}));d(ne=>[...ne,...K]),i&&ue.length>0&&I(K)},L=ue=>{d(K=>K.filter((ne,oe)=>oe!==ue))},te=c.some(ue=>ue.isZip&&ue.status==="pending"),ae=c.some(ue=>ue.file.name.toLowerCase().endsWith(".stl")&&ue.status==="pending"),ee=c.some(ue=>ue.is3mf&&ue.status==="pending"),me=c.filter(ue=>ue.status==="pending").length,le=c.length>0&&me===0&&!p;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:A,onDragLeave:T,onDrop:C,onClick:()=>M.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[a.jsx(Ca,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("p",{className:"text-white font-medium",children:l(u?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),a.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),a.jsx("input",{ref:M,type:"file",multiple:!0,accept:o,className:"hidden",onChange:F}),te&&a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Qs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),a.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:y,onChange:ue=>v(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:b,onChange:ue=>g(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),ee&&a.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Pr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),a.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(ae||te)&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Vu,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),a.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(te&&!ae?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:_,onChange:ue=>k(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((ue,K)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[ue.isZip?a.jsx(Qs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(_P,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ue.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(ue.file.size/1024/1024).toFixed(2)," MB",ue.isZip&&ue.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),ue.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:ue.extractedCount})]})]})]}),ue.status==="pending"&&a.jsx("button",{onClick:()=>L(K),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray"})}),ue.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),ue.status==="success"&&a.jsx(fr,{className:"w-4 h-4 text-green-500"}),ue.status==="error"&&a.jsx("span",{title:ue.error,children:a.jsx($a,{className:"w-4 h-4 text-red-500"})})]},K))}),P&&a.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx($a,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-sm text-red-300",children:P})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:l("common.cancel")}),!le&&a.jsx(Ie,{onClick:()=>I(c),disabled:me===0||p,children:p?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",me>0?`(${me})`:""]})})]})]})})}function FW(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ba(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const _Ve=[["PA-CF","PA12-CF","PAHT-CF"]],Nae={};for(const t of _Ve){const e=t[0];for(const n of t)Nae[n.toUpperCase()]=e.toUpperCase()}function wC(t){if(!t)return"";const e=t.toUpperCase();return Nae[e]??e}function pD(t,e){return wC(t)===wC(e)}function _d(t,e,n=40){const r=Ba(t),i=Ba(e);if(!r||!i||r.length<6||i.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),d=parseInt(i.substring(2,4),16),u=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=n}function uS(t,e,n,r){if(r)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`${i}${e+1}`}function Ux(t,e,n){return n?254+e:t>=128?t:t*4+e}function mx(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function Rk(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 RW(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function kVe(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(16).toUpperCase().padStart(8,"0")}function Su(t,e,n){return`${kVe(t)}${RW(e,4)}${RW(n,4)}`}function LW(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Qn(t)?.getTime()??0)>e}function NVe(t,e,n,r){let i=Cae(e,t.nozzle_id);r&&(i=[...i].sort((c,d)=>{const u=(c.remain??-1)>=0?c.remain??-1:101,m=(d.remain??-1)>=0?d.remain??-1:101;return u-m}));const s=i.find(c=>!n.has(c.globalTrayId)&&pD(c.type,t.type)&&Ba(c.color)===Ba(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&pD(c.type,t.type)&&_d(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&pD(c.type,t.type));return s??o??l}function Cae(t,e){return t.filter(n=>e==null||n.extruderId===e)}function mS(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=FW(o.tray_color);e.push({type:o.tray_type,color:l,colorName:Vl(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:uS(i.id,o.id,s,!1),globalTrayId:Ux(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=FW(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:Vl(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",traySubBrands:i.tray_sub_brands||"",extruderId:r?255-o:void 0,remain:i.remain??-1})}return e}function OW(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=mS(e);if(r.length===0)return;const i=new Set,s=t.filaments.map(c=>{const d=c.tray_info_idx||"";let u=r.filter(b=>!i.has(b.globalTrayId));c.nozzle_id!=null&&(u=u.filter(b=>b.extruderId===c.nozzle_id)),n&&(u=[...u].sort((b,g)=>{const _=b.remain>=0?b.remain:101,k=g.remain>=0?g.remain:101;return _-k}));let m,p,f,y;if(d){const b=u.filter(g=>g.trayInfoIdx===d);b.length===1?m=b[0]:b.length>1&&(n&&b.sort((g,_)=>{const k=g.remain>=0?g.remain:101,P=_.remain>=0?_.remain:101;return k-P}),p=b.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase()&&Ba(g.color)===Ba(c.color)),p||(f=b.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase()&&_d(g.color,c.color))),!p&&!f&&(y=b.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase())))}!m&&!p&&!f&&!y&&(p=u.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase()&&Ba(b.color)===Ba(c.color)),p||(f=u.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase()&&_d(b.color,c.color))),!p&&!f&&(y=u.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase())));const v=m||p||f||y||void 0;return v&&i.add(v.globalTrayId),{slot_id:c.slot_id,globalTrayId:v?.globalTrayId??-1}}),o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}function CVe(t){return w.useMemo(()=>mS(t),[t])}function Pae(t,e,n,r){const i=CVe(e),s=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const d=new Set(Object.values(n));return t.filaments.map(u=>{const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const A=n[m],T=i.find(C=>C.globalTrayId===A);if(T){const C=T.type?.toUpperCase()===u.type?.toUpperCase(),F=Ba(T.color)===Ba(u.color)||_d(T.color,u.color);let $;return C&&F?$="match":C?$="type_only":$="mismatch",{...u,loaded:T,hasFilament:!0,typeMatch:C,colorMatch:F,status:$,isManual:!0}}}const p=u.tray_info_idx||"";let f=i.filter(A=>!d.has(A.globalTrayId));u.nozzle_id!=null&&(f=f.filter(A=>A.extruderId===u.nozzle_id)),r&&(f=[...f].sort((A,T)=>{const C=A.remain>=0?A.remain:101,F=T.remain>=0?T.remain:101;return C-F}));let y,v,b,g;if(p){const A=f.filter(T=>T.trayInfoIdx===p);A.length===1?y=A[0]:A.length>1&&(r&&A.sort((T,C)=>{const F=T.remain>=0?T.remain:101,$=C.remain>=0?C.remain:101;return F-$}),v=A.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Ba(T.color)===Ba(u.color)),v||(b=A.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&_d(T.color,u.color))),!v&&!b&&(g=A.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())))}!y&&!v&&!b&&!g&&(v=f.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&Ba(A.color)===Ba(u.color)),v||(b=f.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&_d(A.color,u.color))),!v&&!b&&(g=f.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase())));const _=y||v||b||g||void 0;_&&d.add(_.globalTrayId);const k=!!_,P=k,N=!!y||!!v||!!b;let M;return y||v||b?M="match":g?M="type_only":M="mismatch",{...u,loaded:_,hasFilament:k,typeMatch:P,colorMatch:N,status:M,isManual:!1}})},[t,i,n,r]),o=w.useMemo(()=>{if(s.length===0)return;const d=Math.max(...s.map(m=>m.slot_id||0));if(d<=0)return;const u=new Array(d).fill(-1);return s.forEach(m=>{m.slot_id&&m.slot_id>0&&(u[m.slot_id-1]=m.loaded?.globalTrayId??-1)}),u},[s]),l=s.some(d=>d.status==="mismatch"),c=s.some(d=>d.status==="type_only");return{loadedFilaments:i,filamentComparison:s,amsMapping:o,hasTypeMismatch:l,hasColorMismatch:c}}function PVe(t,e,n,r){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let i=0,s=0,o=0;const l=new Set(Object.values(n));for(const u of t){const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const g=n[m],_=e.find(k=>k.globalTrayId===g);if(_){const k=_.type?.toUpperCase()===u.type?.toUpperCase(),P=Ba(_.color)===Ba(u.color)||_d(_.color,u.color);k&&P?i++:k?s++:o++;continue}}let p=e.filter(g=>!l.has(g.globalTrayId));if(u.nozzle_id!=null){const g=p.filter(_=>_.extruderId===u.nozzle_id);g.length>0&&(p=g)}r&&(p=[...p].sort((g,_)=>{const k=g.remain>=0?g.remain:101,P=_.remain>=0?_.remain:101;return k-P}));const f=p.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()&&Ba(g.color)===Ba(u.color)),y=f?void 0:p.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()&&_d(g.color,u.color)),v=f||y?void 0:p.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()),b=f??y??v;b&&l.add(b.globalTrayId),f||y?i++:v?s++:o++}const c=t.length;let d="full";return o>0?d="missing":s>0&&(d="partial"),{exactMatches:i,typeOnlyMatches:s,missingTypes:o,totalSlots:c,status:d}}function TVe(t,e,n,r){if(!t?.filaments||t.filaments.length===0)return;const i=mS(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(g=>g.extruderId===d.nozzle_id);b.length>0&&(m=b)}r&&(m=[...m].sort((b,g)=>{const _=b.remain>=0?b.remain:101,k=g.remain>=0?g.remain:101;return _-k}));const p=m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&Ba(b.color)===Ba(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&_d(b.color,d.color)),y=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??y;v&&s.add(v.globalTrayId),o.push({slot_id:u,globalTrayId:v?.globalTrayId??-1})}const l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}const IW={useDefault:!0,manualMappings:{},autoConfigured:!1};function AVe(t,e,n,r,i,s,o){const l=ep({queries:t.map(v=>({queryKey:["printer-status",v],queryFn:()=>pe.getPrinterStatus(v),enabled:t.length>0,staleTime:5e3}))}),c=w.useMemo(()=>t.map((v,b)=>{const g=l[b],_=g?.data,P=e?.find($=>$.id===v)?.name||`Printer ${v}`,N=mS(_),M=i[v]||IW,A=OW(n,_,o),T=M.useDefault?r:M.manualMappings,C=TVe(n,_,T,o),F=PVe(n?.filaments,N,T,o);return{printerId:v,printerName:P,status:_,isLoading:g?.isLoading??!1,loadedFilaments:N,autoMapping:A,finalMapping:C,matchStatus:F.status,exactMatches:F.exactMatches,typeOnlyMatches:F.typeOnlyMatches,missingTypes:F.missingTypes,totalSlots:F.totalSlots,config:M}}),[t,l,e,n,i,r,o]),d=l.some(v=>v.isLoading),u=(v,b)=>{s(g=>({...g,[v]:{...g[v]||IW,...b}}))},m=v=>{const b=c.find(k=>k.printerId===v);if(!b||!b.status||!n?.filaments)return;const g=OW(n,b.status,o);if(!g)return;const _={};g.forEach((k,P)=>{k!==-1&&(_[P+1]=k)}),u(v,{useDefault:!1,manualMappings:_,autoConfigured:!0})},p=()=>{for(const v of t)m(v)},f=v=>c.find(g=>g.printerId===v)?.finalMapping,y=c.every(v=>v.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:y}}const Tae={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function yo(t){return Tae[t.toUpperCase()]||t}const MVe=Object.entries(Tae).map(([t,e])=>({code:t,label:`${t} (${e})`}));function jVe({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Lt(),c=mn(),[d,u]=w.useState(!1),[m,p]=w.useState(o),{data:f}=et({queryKey:["printer-status",t],queryFn:()=>pe.getPrinterStatus(t),enabled:!!t}),{data:y}=et({queryKey:["spool-assignments",t],queryFn:()=>pe.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:b,hasTypeMismatch:g,hasColorMismatch:_}=Pae(e,f,n),k=w.useMemo(()=>{const I=new Map;for(const X of y||[]){const L=X.ams_id===255,te=Ux(X.ams_id,X.tray_id,L);I.set(te,X.spool?.cost_per_kg??null)}return I},[y]),P=w.useMemo(()=>{const I=new Map;for(const X of y||[]){const L=X.ams_id===255,te=Ux(X.ams_id,X.tray_id,L),ae=X.spool;if(!ae){I.set(te,null);continue}I.set(te,Math.max(0,Math.round((ae.label_weight??0)-(ae.weight_used??0))))}return I},[y]),N=w.useMemo(()=>{let I=0;for(const X of b){const L=X.loaded?.globalTrayId;if(L==null)continue;const ae=k.get(L)??null??s;ae>0&&(I+=X.used_grams/1e3*ae)}return I},[b,k,s]),M=w.useMemo(()=>Array.from(k.values()).some(I=>I!=null&&I>0),[k]),A=e?.filaments&&e.filaments.length>0,T=e?.filaments?.some(I=>I.nozzle_id!=null)??!1;if(!A||!f)return null;const C=g?"#f97316":_?"#facc15":"#00ae42",F=(I,X)=>{if(I>0)if(X===""){const L={...n};delete L[I],r(L)}else r({...n,[I]:parseInt(X,10)})},$=async()=>{u(!0);try{await pe.refreshPrinterStatus(t),await new Promise(I=>setTimeout(I,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(R0,{className:"w-4 h-4",fill:C,stroke:"none"}),a.jsx("span",{children:l("printModal.filamentMapping")}),g?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?a.jsx(Yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Fn,{className:"w-4 h-4 ml-auto"})]}),m&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:$,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[a.jsx(vr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),b.map((I,X)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${I.type} - ${Vl(I.color)}`,children:a.jsx(R0,{className:"w-3 h-3",fill:I.color,stroke:I.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[T&&I.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:I.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:I.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),I.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",I.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:I.loaded?.globalTrayId??"",onChange:L=>F(I.slot_id||0,L.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${I.status==="match"?"border-bambu-green/50 text-bambu-green":I.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${I.isManual?"ring-1 ring-blue-400/50":""}`,title:I.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(L=>I.nozzle_id==null||L.extruderId===I.nozzle_id).map(L=>{const te=P.get(L.globalTrayId),ae=te!=null?l("printModal.slotRemainingShort",{grams:te,defaultValue:` - ${te}g left`}):"";return a.jsxs("option",{value:L.globalTrayId,className:"bg-bambu-dark text-white",children:[L.label,": ",L.traySubBrands||L.type," (",L.colorName,")",ae]},L.globalTrayId)})]}),I.status==="match"?a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}):I.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Ln,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Ln,{className:"w-3 h-3 text-orange-400"})})]},X)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:N>0||M?`${i}${N.toFixed(2)}`:"N/A"})]}),g&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function EVe({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=Lt(),l=w.useMemo(()=>{const u={};for(const m of e){const p=wC(m.type);u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],r(p)}else{const[p,f]=m.split("|");r({...n,[u]:{type:p,color:f}})}};return a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:a.jsx("span",{children:o("printModal.filamentOverride")})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(u=>{const m=n[u.slot_id],p=!!m,f=l[wC(u.type)]||[],y=u.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===u.nozzle_id):f;return a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[a.jsx("span",{title:`${o("printModal.originalFilament")}: ${u.type} - ${Vl(u.color)}`,children:a.jsx(R0,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:v=>d(u.slot_id,v.target.value),disabled:y.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[a.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",u.type," (",Vl(u.color),")"]}),y.map((v,b)=>a.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",Vl(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${b}`))]}),p?a.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:a.jsx(jo,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]}),a.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[a.jsx("input",{type:"checkbox",checked:i?.[u.slot_id]??!1,onChange:v=>s?.(u.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),a.jsx(Dw,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function DVe({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:r,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=Lt();if(!e||t.length<=1)return null;const c=n.size===t.length;return a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(Ln,{className:"w-3 h-3"}),"Selection required"]}),o&&i&&s&&a.jsx("button",{type:"button",onClick:c?s:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(d=>{const u=n.has(d.index);return a.jsxs("button",{type:"button",onClick:()=>r(d.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(u?a.jsx(us,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):a.jsx(eo,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?a.jsx("img",{src:Ra(d.thumbnail_url),alt:`Plate ${d.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(ea,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:d.name||`Plate ${d.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[d.objects.length>0?d.objects.slice(0,3).join(", ")+(d.objects.length>3?"...":""):`${d.filaments.length} filament${d.filaments.length!==1?"s":""}`,d.print_time_seconds!=null?` • ${ls(d.print_time_seconds)}`:""]})]}),!o&&u&&a.jsx(Kr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const FVe=new Set(["IDLE","FINISH","FAILED"]);function RVe({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=mn(),[i,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await pe.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings)),b=r.getQueryData(["settings"]);p=NVe(d,t.loadedFilaments,v,b?.prefer_lowest_filament)}let y="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),b=Ba(p.color)===Ba(d.color)||_d(p.color,d.color);v&&b?y="match":v&&(y="type_only")}return{req:d,loaded:p,status:y,isManual:f}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(vr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:m,isManual:p},f)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${d.type} - ${Vl(d.color)}`,children:a.jsx(R0,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),a.jsxs("span",{className:"text-white truncate",children:[d.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?.globalTrayId??"",onChange:y=>o(d.slot_id||0,y.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),Cae(t.loadedFilaments,d.nozzle_id).map(y=>a.jsxs("option",{value:y.globalTrayId,className:"bg-bambu-dark text-white",children:[y.label,": ",y.traySubBrands||y.type," (",y.colorName,")"]},y.globalTrayId))]}),m==="match"?a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Ln,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Ln,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function LVe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:y,targetLocation:v,onTargetLocationChange:b,slicedForModel:g}){const[_,k]=w.useState(!1),P=s?t:t.filter(ne=>ne.is_active),N=ep({queries:P.map(ne=>({queryKey:["printerStatus",ne.id],queryFn:()=>pe.getPrinterStatus(ne.id),staleTime:5e3}))}),M=w.useMemo(()=>{const ne=new Map;return P.forEach((oe,be)=>{const _e=N[be];_e?.data&&ne.set(oe.id,_e.data)}),ne},[P,N]),A=ne=>{const oe=M.get(ne);return oe?oe.connected?!FVe.has(oe.state??""):!0:!1},T=ne=>{const oe=M.get(ne);if(!oe)return null;if(!oe.connected)return"Offline";const be=oe.state;return be?be==="RUNNING"?oe.stg_cur_name||"Printing":be==="PREPARE"?"Preparing":be==="PAUSE"?"Paused":be==="IDLE"?"Idle":be==="FINISH"?"Finished":be==="FAILED"?"Failed":be:null},C=w.useMemo(()=>{if(m!=="printer"||!g||_)return P;const ne=P.filter(oe=>oe.model===g);return ne.length>0?ne:P},[P,m,g,_]),F=P.length-C.length,$=w.useMemo(()=>{const ne=P.map(oe=>oe.model).filter(oe=>!!oe);return[...new Set(ne)].sort()},[P]),I=w.useMemo(()=>{if(!f)return[];const ne=P.filter(oe=>oe.model===f&&oe.location).map(oe=>oe.location).filter(oe=>!!oe);return[...new Set(ne)].sort()},[P,f]),X=p&&y&&$.length>0,L=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(C.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(qa,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const te=ne=>{o&&A(ne)||(i?e.includes(ne)?n(e.filter(oe=>oe!==ne)):n([...e,ne]):n([ne]))},ae=()=>{const ne=o?C.filter(oe=>!A(oe.id)):C;n(ne.map(oe=>oe.id))},ee=()=>{n([])},me=(ne,oe,be)=>{be.stopPropagation(),!(!d||!u)&&(oe?d(ne):u(ne,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},le=ne=>e.includes(ne),ue=e.length,K=ne=>l?.find(oe=>oe.printerId===ne);return a.jsxs("div",{className:"space-y-2 mb-6",children:[X&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{p("printer"),y(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Pr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const ne=g&&$.includes(g)?g:$[0];y(ne)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(_u,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),m==="model"&&X&&a.jsxs("div",{className:"space-y-3 mb-4",children:[!g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:ne=>{y(ne.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:[a.jsx("option",{value:"",children:"Select a model..."}),$.map(ne=>a.jsx("option",{value:ne,children:ne},ne))]})]}),f&&I.length>0&&b&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:v||"",onChange:ne=>b(ne.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),I.map(ne=>a.jsx("option",{value:ne,children:ne},ne))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&i&&C.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:ue===0?"Select printers":`${ue} printer${ue!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[ue<C.length&&a.jsx("button",{type:"button",onClick:ae,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),ue>0&&a.jsx("button",{type:"button",onClick:ee,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&C.map(ne=>{const oe=le(ne.id),be=K(ne.id),_e=be&&!be.config.useDefault,B=A(ne.id),Y=o&&B,D=T(ne.id);return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>te(ne.id),disabled:Y,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Y?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":oe?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ne.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${Y?"bg-bambu-dark-tertiary":oe?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Pr,{className:`w-5 h-5 ${Y?"text-bambu-gray/50":oe?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:`font-medium ${Y?"text-bambu-gray":"text-white"}`,children:[ne.name,!ne.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[ne.model||"Unknown model"," • ",ne.ip_address]})]}),D&&a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${B?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:D}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${Y?"border-bambu-gray/30":oe?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:oe&&a.jsx(Kr,{className:"w-3 h-3 text-white"})})]}),oe&&L&&be&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:j=>j.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:_e,onChange:j=>me(ne.id,j.target.checked,j),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${be.matchStatus==="full"?"text-bambu-green":be.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",be.exactMatches,"/",be.totalSlots," matched)"]}),be.isLoading&&a.jsx(vr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),_e&&a.jsxs("button",{type:"button",onClick:j=>{j.stopPropagation(),d(ne.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(NQ,{className:"w-3 h-3"}),"Auto"]})]}),_e&&a.jsx(RVe,{printerResult:be,filamentReqs:c.filaments,onUpdateConfig:j=>u(ne.id,j)})]})]},ne.id)}),m==="printer"&&F>0&&!_&&a.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:[a.jsx(Ln,{className:"w-3 h-3 text-yellow-400"}),F," other printer",F>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&g&&a.jsx("button",{type:"button",onClick:()=>k(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),m==="printer"&&ue===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const OVe=[{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 IVe({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Ow,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(Yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Fn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:OVe.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function zVe({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=Lt(),[d,u]=w.useState(""),[m,p]=w.useState(""),[f,y]=w.useState(!0),[v,b]=w.useState(!0),g=w.useRef(null),_=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){_.current=!1;return}if(!_.current){_.current=!0;let C;t.scheduledTime?(C=new Date(t.scheduledTime),isNaN(C.getTime())&&(C=new Date,C.setHours(C.getHours()+1,0,0,0))):(C=new Date,C.setHours(C.getHours()+1,0,0,0),e({...t,scheduledTime:G3(C)})),u(V3(C,n)),p(y6(C,r)),y(!0),b(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const k=C=>{e({...t,scheduleType:C})},P=(C,F)=>{const $=Vxe(C,n),I=Gxe(F);y(!!$),b(!!I),$&&I&&($.setHours(I.hours,I.minutes,0,0),$>new Date&&e({...t,scheduledTime:G3($)}))},N=C=>{u(C),P(C,m)},M=C=>{p(C),P(d,C)},A=C=>{const F=C.target.value;if(F){const $=new Date(F);isNaN($.getTime())||(u(V3($,n)),p(y6($,r)),y(!0),b(!0),e({...t,scheduledTime:F}))}},T=()=>{g.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>k("asap"),children:[a.jsx(rr,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>k("scheduled"),children:[a.jsx(Wr,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>k("manual"),children:[a.jsx(gQ,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${f?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:d,onChange:C=>N(C.target.value),placeholder:Hxe(n)}),a.jsx("button",{type:"button",onClick:T,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(Wr,{className:"w-4 h-4"})}),a.jsx("input",{ref:g,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})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${v?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:C=>M(C.target.value),placeholder:qxe(r)})})]}),(!f||!v)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:C=>e({...t,requirePreviousSuccess:C.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:C=>e({...t,autoOffAfter:C.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[a.jsx(im,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),l&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"gcodeInjection",checked:t.gcodeInjection,onChange:C=>e({...t,gcodeInjection:C.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"gcodeInjection",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(ey,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),s&&t.scheduleType!=="manual"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"staggerEnabled",checked:t.staggerEnabled,onChange:C=>e({...t,staggerEnabled:C.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"staggerEnabled",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(ea,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),t.staggerEnabled&&a.jsxs("div",{className:"ml-6 space-y-3",children:[a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerGroupSize","Group size")}),a.jsx("input",{type:"number",min:1,max:o,value:t.staggerGroupSize,onChange:C=>e({...t,staggerGroupSize:Math.max(1,parseInt(C.target.value)||1)}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerInterval","Interval (min)")}),a.jsx("input",{type:"number",min:1,max:60,value:t.staggerIntervalMinutes,onChange:C=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(C.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 C=Math.ceil(o/t.staggerGroupSize),F=o%t.staggerGroupSize,$=(C-1)*t.staggerIntervalMinutes;return a.jsxs("p",{className:"text-xs text-bambu-gray",children:[c("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:o,groups:C,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),F!==0&&t.staggerGroupSize<o?` (${c("printModal.staggerLastGroup","last group: {{count}}",{count:F})})`:"",C>1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:$})})`:""]})})()]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const yc={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},fD={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function kd({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l}){const{t:c}=Lt(),d=mn(),{showToast:u}=xn(),{hasPermission:m}=_r(),p=!!n&&!e,[f,y]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[v,b]=w.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),g=v.size===1?[...v][0]:null,[_,k]=w.useState(1),[P,N]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??yc.bed_levelling,flow_cali:i.flow_cali??yc.flow_cali,vibration_cali:i.vibration_cali??yc.vibration_cali,layer_inspect:i.layer_inspect??yc.layer_inspect,timelapse:i.timelapse??yc.timelapse}:yc),[M,A]=w.useState(()=>{if(t==="edit-queue-item"&&i){let ht="asap";i.manual_start?ht="manual":i.scheduled_time&&!LW(i.scheduled_time)&&(ht="scheduled");let Mt="";if(i.scheduled_time&&!LW(i.scheduled_time)){const Qt=Qn(i.scheduled_time)??new Date;Mt=G3(Qt)}return{scheduleType:ht,scheduledTime:Mt,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:fD.staggerGroupSize,staggerIntervalMinutes:fD.staggerIntervalMinutes}}return fD}),[T,C]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ht={};return i.ams_mapping.forEach((Mt,Qt)=>{Mt!==-1&&(ht[Qt+1]=Mt)}),ht}return{}}),[F,$]=w.useState({}),[I,X]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[L,te]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[ae,ee]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[me,le]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ht={};for(const Mt of i.filament_overrides)ht[Mt.slot_id]={type:Mt.type,color:Mt.color};return ht}return{}}),[ue,K]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ht={};for(const Mt of i.filament_overrides)ht[Mt.slot_id]=Mt.force_color_match===!0;return ht}return{}}),[ne]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[oe]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[be,_e]=w.useState(!1),[B,Y]=w.useState({current:0,total:0}),[D,j]=w.useState(null),[z,W]=w.useState(new Set),q=f.length,de=f.length>0?f[0]:null,{data:O}=et({queryKey:["settings"],queryFn:pe.getSettings}),G=w.useRef(!1);w.useEffect(()=>{!O||G.current||t==="edit-queue-item"||(G.current=!0,N({bed_levelling:O.default_bed_levelling??yc.bed_levelling,flow_cali:O.default_flow_cali??yc.flow_cali,vibration_cali:O.default_vibration_cali??yc.vibration_cali,layer_inspect:O.default_layer_inspect??yc.layer_inspect,timelapse:O.default_timelapse??yc.timelapse}))},[O,t]);const Q=w.useRef(!1);w.useEffect(()=>{!O||Q.current||t==="edit-queue-item"||(Q.current=!0,A(ht=>({...ht,staggerGroupSize:O.stagger_group_size??ht.staggerGroupSize,staggerIntervalMinutes:O.stagger_interval_minutes??ht.staggerIntervalMinutes})))},[O,t]);const V=yo(O?.currency||"USD"),J=O?.default_filament_cost??0,{data:ie,isLoading:he}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:fe}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&I==="printer"||p&&t==="reprint"}),{data:se}=et({queryKey:["archive",e],queryFn:()=>pe.getArchive(e),enabled:!!e&&!p}),{data:U}=et({queryKey:["library-file",n],queryFn:()=>pe.getLibraryFile(n),enabled:p&&!!n}),R=se?.sliced_for_model||U?.sliced_for_model||null,{data:re,isError:xe}=et({queryKey:["archive-plates",e],queryFn:()=>pe.getArchivePlates(e),enabled:!!e&&!p,retry:!1}),{data:we}=et({queryKey:["library-file-plates",n],queryFn:()=>pe.getLibraryFilePlates(n),enabled:p&&!!n}),ye=p?we:re,{data:Ae,isError:ve}=et({queryKey:["archive-filaments",e,g],queryFn:()=>pe.getArchiveFilamentRequirements(e,g??void 0),enabled:!!e&&!p&&(g!==null||!ye?.is_multi_plate),retry:!1}),{data:Te}=et({queryKey:["library-file-filaments",n,g],queryFn:()=>pe.getLibraryFileFilamentRequirements(n,g??void 0),enabled:p&&!!n&&(g!==null||!ye?.is_multi_plate)}),Fe=!p&&(xe||ve),Ee=p?Te:Ae,Se=w.useMemo(()=>{if(!(g===null||!ye?.plates?.length))return ye.plates.find(ht=>ht.index===g)?.name||void 0},[ye,g]),{data:je}=et({queryKey:["available-filaments",L,ae],queryFn:()=>pe.getAvailableFilaments(L,ae??void 0),enabled:I==="model"&&!!L}),{data:qe}=et({queryKey:["printer-status",de],queryFn:()=>pe.getPrinterStatus(de),enabled:!!de}),{amsMapping:Re}=Pae(Ee,qe,T,O?.prefer_lowest_filament),Ye=AVe(f,ie,Ee,T,F,$,O?.prefer_lowest_filament);w.useEffect(()=>{ye?.plates&&ye.plates.length>=1&&v.size===0&&b(new Set([ye.plates[0].index]))},[ye,v.size]),w.useEffect(()=>{if(t==="edit-queue-item")return;const ht=ie?.filter(Mt=>Mt.is_active)||[];ht.length===1&&f.length===0&&y([ht[0].id])},[t,ie,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(ne.sort())||g!==oe)&&(C({}),$({}),W(new Set)):(C({}),$({}),W(new Set))},[t,f,g,ne,oe]);const[ce,ze]=w.useState(L),[Ne,Ge]=w.useState(g);w.useEffect(()=>{(L!==ce||g!==Ne)&&(ze(L),Ge(g),(t!=="edit-queue-item"||ce!==null)&&(le({}),K({})))},[L,g,ce,Ne,t]),w.useEffect(()=>{if(!O?.per_printer_mapping_expanded||f.length<=1)return;const ht=f.filter(Mt=>{if(z.has(Mt))return!1;const Qt=Ye.printerResults.find(Wt=>Wt.printerId===Mt);return Qt&&Qt.status&&!Qt.isLoading});ht.length>0&&(W(Mt=>{const Qt=new Set(Mt);return ht.forEach(Wt=>Qt.add(Wt)),Qt}),ht.forEach(Mt=>{Ye.autoConfigurePrinter(Mt)}))},[O?.per_printer_mapping_expanded,f,z,Ye]),w.useEffect(()=>{const ht=Mt=>{Mt.key==="Escape"&&!be&&o()};return window.addEventListener("keydown",ht),()=>window.removeEventListener("keydown",ht)},[o,be]);const $e=ye?.is_multi_plate??!1,Pe=ye?.plates??[],Me=w.useMemo(()=>{const ht=new Map;return fe&&fe.forEach(Mt=>{const Qt=Mt.ams_id===255,Wt=Ux(Mt.ams_id,Mt.tray_id,Qt),Ue=ht.get(Mt.printer_id)??new Map;Ue.set(Wt,Mt),ht.set(Mt.printer_id,Ue)}),ht},[fe]),Ve=w.useMemo(()=>{if(!D||D.length===0)return"";const ht=D.map(Mt=>c("printModal.insufficientFilamentLine",{printer:Mt.printerName,slot:Mt.slotLabel,required:Math.round(Mt.requiredGrams),remaining:Math.round(Mt.remainingGrams)}));return[c("printModal.insufficientFilamentMessage"),...ht].join(`
  8157. `)},[D,c]),tt=lt({mutationFn:ht=>pe.addToQueue(ht)}),ut=lt({mutationFn:ht=>pe.updateQueueItem(i.id,ht),onSuccess:()=>{d.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),l?.(),o()},onError:ht=>{u(ht.message||"Failed to update queue item","error")}}),xt=M.staggerEnabled&&f.length>1,wt=async(ht,Mt)=>{if(ht?.preventDefault(),!Mt?.skipFilamentCheck&&!O?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&I==="printer"){const at=[],Ce=Ee?.filaments??[];if(Ce.length>0&&Me.size>0){const We=(Xe,Qe)=>!Number.isFinite(Xe)||Xe<=0||!Number.isFinite(Qe)||Qe<0?null:Math.max(0,Xe-Qe);for(const Xe of f){const Qe=f.length>1?Ye.getFinalMapping(Xe):Re;if(!Qe)continue;const Ze=f.length>1?Ye.printerResults.find(He=>He.printerId===Xe)?.status:qe,rt=mS(Ze),bt=new Map(rt.map(He=>[He.globalTrayId,He.label])),Pt=Me.get(Xe),vt=ie?.find(He=>He.id===Xe)?.name??`Printer ${Xe}`;Pt&&Ce.forEach(He=>{if(!He.slot_id||He.slot_id<=0)return;const St=Qe[He.slot_id-1];if(!Number.isFinite(St)||St<0)return;const Zt=Pt.get(St)?.spool;if(!Zt)return;const Jt=We(Zt.label_weight,Zt.weight_used);Jt!==null&&(Jt>=He.used_grams||at.push({printerName:vt,slotLabel:bt.get(St)??`Slot ${He.slot_id}`,requiredGrams:He.used_grams,remainingGrams:Jt}))})}}if(at.length>0){j(at);return}}if(I==="printer"&&f.length===0){u("Please select at least one printer","error");return}if(I==="model"&&!L){u("Please select a target printer model","error");return}_e(!0);const Qt=v.size>1?Pe.filter(at=>v.has(at.index)):[null],Wt=I==="model"?Qt.length:f.length*Qt.length;Y({current:0,total:Wt});const Ue={success:0,failed:0,errors:[]},dt=at=>{if(f.length>1){const Ce=F[at];if(Ce&&!Ce.useDefault)return Ye.getFinalMapping(at)}return Re},De=(()=>{const at=[];if(Ee?.filaments)for(const Ce of Ee.filaments){const We=me[Ce.slot_id],Xe=ue[Ce.slot_id]??!1,Qe=We?.type??Ce.type,Ze=We?.color??Ce.color;(We||Xe)&&at.push({slot_id:Ce.slot_id,type:Qe,color:Ze,color_name:Vl(Ze),force_color_match:Xe})}else for(const[Ce,{type:We,color:Xe}]of Object.entries(me)){const Qe=parseInt(Ce,10),Ze=ue[Qe]??!1;at.push({slot_id:Qe,type:We,color:Xe,color_name:Vl(Xe),force_color_match:Ze})}return at.length>0?at:void 0})(),Le=(at,Ce)=>({printer_id:I==="printer"?at:null,target_model:I==="model"?L:null,target_location:I==="model"?ae:null,filament_overrides:I==="model"?De:void 0,archive_id:p?void 0:e,library_file_id:p?n:void 0,require_previous_success:M.requirePreviousSuccess,auto_off_after:M.autoOffAfter,gcode_injection:M.gcodeInjection,manual_start:M.scheduleType==="manual",ams_mapping:at?dt(at):void 0,plate_id:Ce!==void 0?Ce:g,scheduled_time:M.scheduleType==="scheduled"&&M.scheduledTime?new Date(M.scheduledTime).toISOString():void 0,...P});if(I==="model"){if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),_e(!1);return}let at=0;for(const Ce of Qt){at++,Y({current:at,total:Wt});const We=Ce?Ce.index:g;try{if(t==="edit-queue-item"&&!Ce){const Xe={printer_id:null,target_model:L,target_location:ae,filament_overrides:De||null,require_previous_success:M.requirePreviousSuccess,auto_off_after:M.autoOffAfter,gcode_injection:M.gcodeInjection,manual_start:M.scheduleType==="manual",ams_mapping:void 0,plate_id:We,scheduled_time:M.scheduleType==="scheduled"&&M.scheduledTime?new Date(M.scheduledTime).toISOString():null,...P};await ut.mutateAsync(Xe)}else{const Xe=Le(null,We);Kt>1&&(Xe.quantity=Kt),await tt.mutateAsync(Xe)}Ue.success++}catch(Xe){Ue.failed++;const Qe=Ce?Ce.name||`Plate ${Ce.index}`:"";Ue.errors.push(Qe?`${Qe}: ${Xe.message}`:Xe.message)}}}else{const at=M.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&f.length>1,Ce=at?M.scheduleType==="scheduled"&&M.scheduledTime?new Date(M.scheduledTime).getTime():Date.now():0;let We=0;for(const Xe of Qt){const Qe=Xe?Xe.index:g;for(let Ze=0;Ze<f.length;Ze++){const rt=f[Ze];We++,Y({current:We,total:Wt});try{if(t==="reprint"&&!at){const bt=dt(rt);if(p?await pe.printLibraryFile(n,rt,{plate_id:g??void 0,plate_name:Se,ams_mapping:bt,...P}):await pe.reprintArchive(e,rt,{plate_id:g??void 0,plate_name:Se,ams_mapping:bt,...P}),Kt>1){const Pt=Le(rt,Qe);Pt.quantity=Kt-1,await tt.mutateAsync(Pt)}}else if(t==="edit-queue-item"&&We===1){const bt=dt(rt),Pt={printer_id:rt,target_model:null,target_location:null,require_previous_success:M.requirePreviousSuccess,auto_off_after:M.autoOffAfter,gcode_injection:M.gcodeInjection,manual_start:M.scheduleType==="manual",ams_mapping:bt,plate_id:Qe,scheduled_time:M.scheduleType==="scheduled"&&M.scheduledTime?new Date(M.scheduledTime).toISOString():null,...P};await ut.mutateAsync(Pt)}else{const bt=Le(rt,Qe);if(Kt>1&&(bt.quantity=Kt),at){const Pt=Math.floor(Ze/M.staggerGroupSize);if(Pt>0){const vt=Pt*M.staggerIntervalMinutes*6e4;bt.scheduled_time=new Date(Ce+vt).toISOString()}}await tt.mutateAsync(bt)}Ue.success++}catch(bt){Ue.failed++;const Pt=ie?.find(St=>St.id===rt)?.name||`Printer ${rt}`,vt=Xe?Xe.name||`Plate ${Xe.index}`:"",He=vt?`${Pt} (${vt})`:Pt;Ue.errors.push(`${He}: ${bt.message}`)}}}}_e(!1),Ue.failed===0?(t==="reprint"&&xt?u(c("queue.itemsQueued",{count:Ue.success})):t!=="reprint"&&(t==="edit-queue-item"?u("Queue item updated"):Ue.success===1?u(I==="model"?`Queued for any ${L}`:c("queue.printQueued")):u(c("queue.itemsQueued",{count:Ue.success}))),d.invalidateQueries({queryKey:["queue"]}),l?.(),o()):Ue.success===0?u(`Failed: ${Ue.errors[0]}`,"error"):(u(`${Ue.success} succeeded, ${Ue.failed} failed`,"error"),d.invalidateQueries({queryKey:["queue"]}))},Ht=be||ut.isPending,Xt=w.useMemo(()=>!(Ht||I==="printer"&&f.length===0||I==="model"&&!L||I==="model"&&t==="reprint"||$e&&v.size===0),[f.length,I,L,t,$e,v.size,Ht]),Kt=I==="printer"&&f.length>1?1:_,en=(()=>{const ht=f.length;if(t==="reprint"){const Mt=xt&&ht>1;let Qt=Mt?c("printModal.staggerToPrinters",{count:ht,defaultValue:"Stagger to {{count}} printers"}):ht>1?c("queue.printToPrinters",{count:ht}):c("queue.print");return Kt>1&&(Qt=`${Qt} ×${Kt}`),{title:c(p?"queue.print":"queue.reprint"),icon:Pr,submitText:Qt,submitIcon:Mt?Wr:Pr,loadingText:B.total>1?c("queue.sendingProgress",{current:B.current,total:B.total}):c("queue.sending")}}if(t==="add-to-queue"){let Mt=c("queue.addToQueue");return v.size>1?Mt=c("queue.queueSelectedPlates",{count:v.size}):ht>1&&(Mt=c("queue.queueToPrinters",{count:ht})),Kt>1&&(Mt=`${Mt} ×${Kt}`),{title:c("queue.schedulePrint"),icon:Wr,submitText:Mt,submitIcon:Wr,loadingText:B.total>1?c("queue.addingProgress",{current:B.current,total:B.total}):c("queue.adding")}}return{title:c("queue.editQueueItem"),icon:Za,submitText:c("common.save"),submitIcon:Za,loadingText:B.total>1?c("queue.savingProgress",{current:B.current,total:B.total}):c("common.saving")}})(),Ke=en.icon,Ft=en.submitIcon,Nt=de&&v.size<=1&&(p||($e?g!==null:!0));return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:be?void 0:o,children:[a.jsx(Dt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:ht=>ht.stopPropagation(),children:a.jsxs(Rt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ke,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:en.title})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:o,disabled:be,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:wt,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to"," ",s?.length===1&&ie?a.jsx("span",{className:"text-white",children:ie.find(ht=>ht.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(DVe,{plates:Pe,isMultiPlate:$e,selectedPlates:v,onToggle:ht=>{b(Mt=>{const Qt=new Set(Mt);return t==="add-to-queue"?Qt.has(ht)?Qt.delete(ht):Qt.add(ht):(Qt.clear(),Qt.add(ht)),Qt})},onSelectAll:t==="add-to-queue"?()=>b(new Set(Pe.map(ht=>ht.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>b(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&a.jsx(LVe,{printers:ie||[],selectedPrinterIds:f,onMultiSelect:y,isLoading:he,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:Ye.printerResults,filamentReqs:Ee,onAutoConfigurePrinter:Ye.autoConfigurePrinter,onUpdatePrinterConfig:Ye.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":I,onAssignmentModeChange:t!=="reprint"?X:void 0,targetModel:L,onTargetModelChange:t!=="reprint"?te:void 0,targetLocation:ae,onTargetLocationChange:t!=="reprint"?ee:void 0,slicedForModel:R}),I==="model"&&L&&Ee&&je&&je.length>0&&a.jsx(EVe,{filamentReqs:Ee,availableFilaments:je,overrides:me,onChange:le,forceColorMatch:ue,onForceColorMatchChange:(ht,Mt)=>K(Qt=>({...Qt,[ht]:Mt}))}),R&&I==="printer"&&f.length===1&&(()=>{const ht=ie?.find(Mt=>Mt.id===f[0]);return ht&&ht.model&&R!==ht.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",R,", but printing on ",ht.model]})]}):null})(),Fe&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(qa,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Nt&&!Fe&&f.length===1&&a.jsx(jVe,{printerId:de,filamentReqs:Ee,manualMappings:T,onManualMappingChange:C,defaultExpanded:!!s?.length||(O?.per_printer_mapping_expanded??!1),currencySymbol:V,defaultCostPerKg:J}),(t==="reprint"||q>0||I==="model"&&L)&&a.jsx(IVe,{options:P,onChange:N,defaultExpanded:!!s?.length}),t!=="edit-queue-item"&&(I==="model"||f.length<=1)&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("label",{htmlFor:"printQuantity",className:"text-sm text-bambu-gray whitespace-nowrap",children:c("queue.quantity","Quantity")}),a.jsx("input",{id:"printQuantity",type:"number",min:1,max:999,value:_,onChange:ht=>k(Math.max(1,Math.min(999,parseInt(ht.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"}),_>1&&a.jsx("span",{className:"text-xs text-bambu-gray",children:c("queue.quantityHint","Creates {{count}} queue items",{count:_})})]}),t==="reprint"&&I==="printer"&&f.length>1&&a.jsxs("div",{className:"space-y-2 pb-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"staggerEnabledReprint",checked:M.staggerEnabled,onChange:ht=>A({...M,staggerEnabled:ht.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"staggerEnabledReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(ea,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),M.staggerEnabled&&(()=>{const ht=M.staggerGroupSize,Mt=M.staggerIntervalMinutes,Qt=Math.ceil(f.length/ht),Wt=(Qt-1)*Mt;return a.jsxs("p",{className:"ml-6 text-xs text-bambu-gray",children:[c("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:f.length,groups:Qt,size:ht,interval:Mt}),Qt>1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:Wt})})`:""]})})()]}),t!=="reprint"&&a.jsx(zVe,{options:M,onChange:A,dateFormat:O?.date_format||"system",timeFormat:O?.time_format||"system",canControlPrinter:m("printers:control"),showStagger:t==="add-to-queue"&&I==="printer"&&f.length>1,printerCount:f.length,hasGcodeSnippets:!!O?.gcode_snippets}),t==="reprint"&&!!O?.gcode_snippets&&Kt>1&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:M.gcodeInjection,onChange:ht=>A({...M,gcodeInjection:ht.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"gcodeInjectionReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(ey,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),ut.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ut.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:be,children:"Cancel"}),a.jsx(Ie,{type:"submit",disabled:!Xt,className:"flex-1",children:Ht?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),en.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(Ft,{className:"w-4 h-4"}),en.submitText]})})]})]})]})}),D&&D.length>0&&a.jsx(kn,{title:c("printModal.insufficientFilamentTitle"),message:Ve,confirmText:c("printModal.printAnyway"),cancelText:c("common.cancel"),variant:"warning",onConfirm:()=>{j(null),wt(void 0,{skipFilamentCheck:!0})},onCancel:()=>j(null)})]})}function zW({value:t}){const{t:e}=Lt(),[n,r]=w.useState(!1),i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),2e3)}catch{}};return a.jsx("button",{onClick:i,className:"ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:e(n?"printers.copied":"printers.copyToClipboard"),children:n?a.jsx(Kr,{className:"w-3.5 h-3.5 text-bambu-green"}):a.jsx(Mo,{className:"w-3.5 h-3.5"})})}function UVe({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:i}=Lt();w.useEffect(()=>{const o=l=>{l.key==="Escape"&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[r]);const s=[];if(s.push({label:i("printers.model"),value:t.model??"—"}),s.push({label:i("common.status"),value:a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${e?.connected?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?.connected?"bg-bambu-green":"bg-red-400"}`}),e?.connected?i("printers.status.available"):i("printers.status.offline")]})}),e?.state){const o={IDLE:"printers.status.idle",RUNNING:"printers.status.printing",PAUSE:"printers.status.paused",FINISH:"printers.status.finished",FAILED:"printers.status.error"};s.push({label:i("printers.state"),value:i(o[e.state]??"printers.status.unknown")})}if(s.push({label:i("printers.ipAddress"),value:a.jsxs("span",{className:"flex items-center",children:[a.jsx("span",{className:"font-mono",children:t.ip_address}),a.jsx(zW,{value:t.ip_address})]})}),s.push({label:i("printers.serialNumber"),value:a.jsxs("span",{className:"flex items-center",children:[a.jsx("span",{className:"font-mono truncate",children:t.serial_number}),a.jsx(zW,{value:t.serial_number})]})}),e?.wired_network)s.push({label:i("printers.networkLabel","Network"),value:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(cO,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-bambu-green",children:i("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=iJ(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(wQ,{className:`w-4 h-4 ${o.color}`}),a.jsx("span",{className:o.color,children:i(o.labelKey)}),a.jsxs("span",{className:"text-bambu-gray text-xs",children:["(",e.wifi_signal," dBm)"]})]})})}return s.push({label:i("printers.firmware"),value:e?.firmware_version??"—"}),e?.developer_mode!=null&&s.push({label:i("printers.developerMode"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.developer_mode?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.developer_mode?i("printers.enabled"):i("printers.disabled")})}),s.push({label:i("printers.nozzleCount"),value:t.nozzle_count}),e?.sdcard!=null&&s.push({label:i("printers.sdCard"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.sdcard?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.sdcard?i("printers.inserted"):i("printers.notInserted")})}),s.push({label:i("printers.autoArchive"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.auto_archive?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:t.auto_archive?i("printers.enabled"):i("printers.disabled")})}),n!=null&&n>0&&s.push({label:i("printers.totalPrintHours"),value:`${Math.round(n)}h`}),t.location&&s.push({label:i("printers.sort.location"),value:t.location}),s.push({label:i("printers.addedOn"),value:Uf(t.created_at)}),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:r,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:a.jsxs(Rt,{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"flex justify-center mb-4",children:a.jsx("img",{src:aJ(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),a.jsx("div",{className:"space-y-0",children:s.map((o,l)=>a.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[a.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),a.jsx("span",{className:"text-sm text-white text-right",children:o.value})]},l))})]})})})}function BVe(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*r)/255>.6}function gD({trayColor:t,trayType:e,isEmpty:n,slotNumber:r}){return a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center",style:{backgroundColor:t?`#${t}`:e?"#333":"transparent",borderColor:n?"#666":"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:a.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&BVe(t)?"#000":"#fff"},children:r})})}const UW={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},HVe={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function BW(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function bD(t){if(!t)return null;if(UW[t])return UW[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return HVe[n]||null}function xD(t){return(t??.02).toFixed(3)}function HW({side:t}){const{mode:e}=cg(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return a.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function Aae(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 Mae(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function jae({slot:t,index:e,activeStatus:n,filamentName:r,children:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,y=t.stat===1;w.useEffect(()=>{if(o&&u.current&&m.current){const P=u.current.getBoundingClientRect(),N=m.current.offsetHeight,A=P.top-56,T=window.innerHeight-P.bottom;A<N+12&&T>A?d("bottom"):d("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},b=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const g=J4(t.filament_color),_=Aae(t.nozzle_type,s),k=Mae(t.nozzle_type,s);return a.jsxs("div",{ref:u,className:"relative",onMouseEnter:v,onMouseLeave:b,children:[i,o&&a.jsxs("div",{ref:m,className:`
  8158. absolute left-1/2 -translate-x-1/2 z-50
  8159. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8160. animate-in fade-in-0 zoom-in-95 duration-150
  8161. `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsx("div",{className:"w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:f?a.jsxs("div",{className:"px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap",children:["Slot ",e+1," — Empty"]}):a.jsxs("div",{className:"p-2.5 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.nozzle_diameter," mm"]})]}),_&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleType")}),a.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[100px]",children:_})]}),k&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFlow")}),a.jsx("span",{className:"text-xs text-white font-semibold",children:k})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleStatus")}),a.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${n||y?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(n?"printers.nozzleActive":y?"printers.nozzleMounted":"printers.nozzleDocked")})]}),t.wear!=null&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.wear,"%"]})]}),t.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.max_temp,"°C"]})]}),t.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate max-w-[80px]",children:t.serial_number})]}),(g||t.filament_type)&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFilament")}),a.jsxs("div",{className:"flex items-center gap-1",children:[g&&a.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:g}}),a.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:r||t.filament_type||t.filament_id||""})]})]})]})}),a.jsx("div",{className:`
  8162. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8163. border-l-[6px] border-l-transparent
  8164. border-r-[6px] border-r-transparent
  8165. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8166. `})]})]})}function qVe({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:r,children:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null);w.useEffect(()=>{if(o&&u.current&&m.current){const b=u.current.getBoundingClientRect(),g=m.current.offsetHeight,k=b.top-56,P=window.innerHeight-b.bottom;k<g+12&&P>k?d("bottom"):d("top")}},[o]);const f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},y=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};if(w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),!t&&!e)return a.jsx(a.Fragment,{children:i});const v=(b,g)=>{const _=n===g,k=Aae(b.nozzle_type,s),P=Mae(b.nozzle_type,s),N=J4(b.filament_color),M=b.filament_id?r?.[b.filament_id]?.name:void 0;return a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${_?"text-amber-400":"text-bambu-gray"}`,children:s(g==="L"?"common.left":"common.right")}),b.nozzle_diameter&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.nozzle_diameter," mm"]})]}),k&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:k})]}),P&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:P})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),a.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${_?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(_?"printers.nozzleActive":"printers.nozzleIdle")})]}),b.wear!=null&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.wear,"%"]})]}),g==="R"&&b.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.max_temp,"°C"]})]}),g==="R"&&b.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono",children:b.serial_number})]}),(N||b.filament_type||b.filament_id)&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),a.jsxs("div",{className:"flex items-center gap-1",children:[N&&a.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:N}}),a.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:M||b.filament_type||b.filament_id||""})]})]})]})};return a.jsxs("div",{ref:u,className:"relative flex-1",onMouseEnter:f,onMouseLeave:y,children:[i,o&&a.jsxs("div",{ref:m,className:`
  8167. absolute left-1/2 -translate-x-1/2 z-50
  8168. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8169. animate-in fade-in-0 zoom-in-95 duration-150
  8170. `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsx("div",{className:"w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:a.jsxs("div",{className:"p-2.5 flex gap-3",children:[t&&v(t,"L"),t&&e&&a.jsx("div",{className:"w-px bg-bambu-dark-tertiary/50"}),e&&v(e,"R")]})}),a.jsx("div",{className:`
  8171. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8172. border-l-[6px] border-l-transparent
  8173. border-r-[6px] border-r-transparent
  8174. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8175. `})]})]})}function $Ve({slots:t,filamentInfo:e}){const{t:n}=Lt(),r=t.filter(l=>l.id>=2),i=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:i},(l,c)=>r.find(d=>d.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return a.jsxs("div",{className:"text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),a.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const d=!l.nozzle_diameter&&!l.nozzle_type,u=d?null:J4(l.filament_color),m=u?vae(l.filament_color):!1;return a.jsx(jae,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:a.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${d?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:u?{backgroundColor:u}:void 0,children:a.jsx("span",{className:`text-[10px] font-semibold ${d?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:u&&!m?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:d?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function qW({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function VVe({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),a.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function GVe({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),a.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function WVe({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function KVe({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function YVe({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function yD({className:t,color:e,isHeating:n}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return n?a.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"})]}):a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function $W({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof n=="number"?n:60;let c,d;isNaN(s)?(c="#C3C2C1",d="Unknown"):s<=o?(c="#22a352",d="Good"):s<=l?(c="#d4a017",d="Fair"):(c="#c62828",d="Bad");let u;return isNaN(s)||s<=o?u=qW:s<=l?u=VVe:u=GVe,a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${d}${r?" (click for history)":""}`,children:[a.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function VW({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:i}){const s=typeof e=="number"?e:28,o=typeof n=="number"?n:35;let l,c,d;return t<=s?(l="#22a352",c="Good",d=WVe):t<=o?(l="#d4a017",c="Fair",d=KVe):(l="#c62828",c="Bad",d=YVe),a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${r?" (click for history)":""}`,children:[a.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Cl(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,i=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function vD(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function XVe({url:t,printName:e}){const{t:n}=Lt(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!1),d=w.useMemo(()=>{if(!t)return null;const u=t.includes("?")?"&":"?";return Ra(`${t}${u}v=${encodeURIComponent(e||Date.now().toString())}`)},[t,e]);return w.useEffect(()=>{i(!1),o(!1)},[d]),a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&r?"cursor-pointer":""}`,onClick:()=>d&&r&&c(!0),children:d&&!s?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:d,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!r&&a.jsx(si,{className:"w-8 h-8 text-bambu-gray"})]}):a.jsx(si,{className:"w-8 h-8 text-bambu-gray"})}),l&&d&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:a.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[a.jsx("img",{src:d,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&a.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function QVe({printers:t}){const{t:e}=Lt(),n=mn(),[r,i]=w.useState(0);w.useEffect(()=>{let c=!1;const d=n.getQueryCache().subscribe(()=>{c||(c=!0,requestAnimationFrame(()=>{i(u=>u+1),c=!1}))});return()=>d()},[n]);const{counts:s,nextFinish:o}=w.useMemo(()=>{let c=0,d=0,u=0,m=0,p=0,f=0,y=0,v=null,b=null,g=0;return t?.forEach(_=>{const k=n.getQueryData(["printerStatus",_.id]);if(k===void 0)f++;else if(!k.connected)p++;else switch(k.hms_errors&&Tu(k.hms_errors).length>0&&y++,k.state){case"RUNNING":c++,k.remaining_time!=null&&k.remaining_time>0&&(b===null||k.remaining_time<b)&&(b=k.remaining_time,v=_.name,g=k.progress||0);break;case"PAUSE":d++;break;case"FINISH":u++;break;case"FAILED":y++;break;default:m++;break}}),{counts:{printing:c,paused:d,finished:u,idle:m,offline:p,loading:f,error:y,total:t?.length||0},nextFinish:v&&b?{name:v,remainingMin:b,progress:g}:null}},[t,n,r]);if(!t?.length)return null;const l=[{count:s.printing,dot:"bg-bambu-green animate-pulse",label:e("printers.status.printing").toLowerCase()},{count:s.paused,dot:"bg-status-warning",label:e("printers.status.paused","paused").toLowerCase()},{count:s.finished,dot:"bg-blue-400",label:e("printers.status.finished","finished").toLowerCase()},{count:s.idle,dot:s.idle>0?"bg-bambu-green":"bg-gray-500",label:e("printers.status.available").toLowerCase()},{count:s.error,dot:"bg-status-error",label:e("printers.status.problem").toLowerCase()},{count:s.offline,dot:"bg-gray-400",label:e("printers.status.offline").toLowerCase()}];return a.jsxs("div",{className:"flex flex-wrap items-center gap-4 gap-y-2 text-sm",children:[l.map(({count:c,dot:d,label:u})=>c>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${d}`}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:c})," ",u]})]},u)),o&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),a.jsx("span",{className:"text-white font-medium",children:o.name})]}),a.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[a.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),a.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",ls(o.remainingMin*60),")"]})]})]})]})]})}function wD(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 p0(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function GW({ams:t,printerId:e,label:n,amsLabels:r,canEdit:i,onSaved:s,children:o}){const{t:l}=Lt(),[c,d]=w.useState(!1),[u,m]=w.useState("top"),[p,f]=w.useState(""),[y,v]=w.useState(!1),[b,g]=w.useState(null),[_,k]=w.useState(!1),P=w.useRef(null),N=w.useRef(null),M=w.useRef(null);w.useEffect(()=>{c&&(f(r?.[t.id]??""),g(null),requestAnimationFrame(()=>{if(P.current&&N.current){const $=P.current.getBoundingClientRect(),I=$.top-56,X=window.innerHeight-$.bottom;m(I<N.current.offsetHeight+12&&X>I?"bottom":"top")}}))},[c,r,t.id]);const A=()=>{M.current&&clearTimeout(M.current),M.current=setTimeout(()=>d(!0),80)},T=()=>{M.current&&clearTimeout(M.current),_||(M.current=setTimeout(()=>d(!1),200))};w.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const C=async()=>{if(i){v(!0),g(null);try{const $=p.trim();$?await pe.saveAmsLabel(e,t.id,$,t.serial_number):await pe.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch($){g($ instanceof Error?$.message:String($))}finally{v(!1)}}},F=async()=>{if(i){v(!0),g(null);try{await pe.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch($){g($ instanceof Error?$.message:String($))}finally{v(!1)}}};return a.jsxs("div",{ref:P,className:"relative inline-block",onMouseEnter:A,onMouseLeave:T,children:[o,c&&a.jsx("div",{ref:N,className:`
  8176. absolute left-0 z-50
  8177. ${u==="top"?"bottom-full mb-2":"top-full mt-2"}
  8178. animate-in fade-in-0 zoom-in-95 duration-150
  8179. `,style:{maxWidth:"calc(100vw - 24px)"},onMouseEnter:A,onMouseLeave:T,children:a.jsxs("div",{className:"w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm p-2.5 space-y-2",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:n}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.serialNumber")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.serial_number||"—"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.firmwareVersion")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.sw_ver||"—"})]}),a.jsx("div",{className:"h-px bg-bambu-dark-tertiary/50"}),a.jsxs("div",{className:"space-y-1",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray font-medium block",children:l("printers.amsPopup.friendlyName")}),a.jsx("input",{type:"text",value:p,onChange:$=>i&&f($.target.value),onKeyDown:$=>$.key==="Enter"&&C(),onFocus:()=>k(!0),onBlur:()=>{k(!1),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>d(!1),200)},placeholder:i?l("printers.amsPopup.friendlyNamePlaceholder"):r?.[t.id]||"—",disabled:!i,title:i?void 0:l("printers.amsPopup.noEditPermission"),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-xs text-white placeholder-bambu-gray/60 focus:outline-none focus:border-bambu-green disabled:opacity-50 disabled:cursor-not-allowed",maxLength:100}),i&&a.jsxs("div",{className:"space-y-1",children:[b&&a.jsx("p",{className:"text-[10px] text-red-400 break-words",children:b}),a.jsxs("div",{className:"flex gap-1 justify-end",children:[a.jsx("button",{onClick:C,disabled:y,className:"px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50",children:l("printers.amsPopup.save")}),r?.[t.id]&&a.jsx("button",{onClick:F,disabled:y,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 eL={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 WW({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:r="expanded",cardSize:i=2,amsThresholds:s,spoolmanEnabled:o=!1,linkedSpools:l,spoolmanUrl:c,spoolmanSyncMode:d,onGetAssignment:u,onUnassignSpool:m,timeFormat:p="system",cameraViewMode:f="window",onOpenEmbeddedCamera:y,checkPrinterFirmware:v=!0,dryingPresets:b=eL,requirePlateClear:g=!0,selectionMode:_=!1,isSelected:k=!1,onToggleSelect:P}){const{t:N}=Lt(),M=mn(),A=Eo(),{showToast:T}=xn(),{hasPermission:C}=_r(),[F,$]=w.useState(!1),[I,X]=w.useState(!1),[L,te]=w.useState(!0),[ae,ee]=w.useState(!1),[me,le]=w.useState(!1),[ue,K]=w.useState(!1),[ne,oe]=w.useState(!1),[be,_e]=w.useState(!1),[B,Y]=w.useState(!1),[D,j]=w.useState(!1),[z,W]=w.useState(!1),[q,de]=w.useState(null),[O,G]=w.useState(!1),[Q,V]=w.useState(!1),[J,ie]=w.useState(!1),[he,fe]=w.useState(!1),se=w.useCallback(()=>fe(!1),[]),[U,R]=w.useState(null),[re,xe]=w.useState(null),[we,ye]=w.useState("n3f"),[Ae,ve]=w.useState("PLA"),[Te,Fe]=w.useState(50),[Ee,Se]=w.useState(4),[je,qe]=w.useState(!1),[Re,Ye]=w.useState(null),[ce,ze]=w.useState(!1),[Ne,Ge]=w.useState(!1),$e=w.useRef(0),[Pe,Me]=w.useState(null),[Ve,tt]=w.useState(null),[ut,xt]=w.useState(null),[wt,Ht]=w.useState(null),[Xt,Kt]=w.useState(!1),[Ut,en]=w.useState(null),[Ke,Ft]=w.useState(!1),[Nt,ht]=w.useState(!1),[Mt,Qt]=w.useState(null),[Wt,Ue]=w.useState(!1),[dt,pt]=w.useState(!1),{data:De}=et({queryKey:["printerStatus",t.id],queryFn:()=>pe.getPrinterStatus(t.id),refetchInterval:3e4}),{data:Le}=et({queryKey:["firmwareUpdate",t.id],queryFn:()=>yk.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:v&&C("firmware:read")}),at=w.useMemo(()=>{const gt=new Set;if(De?.ams)for(const ge of De.ams)for(const mt of ge.tray||[])mt.tray_info_idx&&gt.add(mt.tray_info_idx);for(const ge of De?.vt_tray??[])ge.tray_info_idx&&gt.add(ge.tray_info_idx);if(De?.nozzle_rack)for(const ge of De.nozzle_rack)ge.filament_id&&gt.add(ge.filament_id);return Array.from(gt)},[De?.ams,De?.vt_tray,De?.nozzle_rack]),Ce=w.useMemo(()=>{const gt=new Set;if(De?.ams)for(const ge of De.ams)for(const mt of ge.tray||[])mt.tray_type&&gt.add(mt.tray_type.toUpperCase());for(const ge of De?.vt_tray??[])ge.tray_type&&gt.add(ge.tray_type.toUpperCase());return gt},[De?.ams,De?.vt_tray]),We=w.useMemo(()=>{const gt=new Set;if(De?.ams){for(const ge of De.ams)for(const mt of ge.tray||[])if(mt.tray_type&&mt.tray_color){const Je=mt.tray_color.replace("#","").toLowerCase().slice(0,6);gt.add(`${mt.tray_type.toUpperCase()}:${Je}`)}}for(const ge of De?.vt_tray??[])if(ge.tray_type&&ge.tray_color){const mt=ge.tray_color.replace("#","").toLowerCase().slice(0,6);gt.add(`${ge.tray_type.toUpperCase()}:${mt}`)}return gt},[De?.ams,De?.vt_tray]),{data:Xe}=et({queryKey:["filamentInfo",at],queryFn:()=>pe.getFilamentInfo(at),enabled:at.length>0,staleTime:300*1e3}),{data:Qe}=et({queryKey:["slotPresets",t.id],queryFn:()=>pe.getSlotPresets(t.id),staleTime:120*1e3}),{data:Ze,refetch:rt}=et({queryKey:["amsLabels",t.id],queryFn:()=>pe.getAmsLabels(t.id),staleTime:300*1e3}),[bt,Pt]=w.useState(null);w.useEffect(()=>{De?.wifi_signal!=null&&Pt(De.wifi_signal)},[De?.wifi_signal]);const vt=De?.wifi_signal??bt,He=w.useRef(void 0);w.useEffect(()=>{De?.connected!==void 0&&(He.current=De.connected)},[De?.connected]);const St=De?.connected??He.current,Ct=w.useRef({});w.useEffect(()=>{De?.ams_extruder_map&&Object.keys(De.ams_extruder_map).length>0&&(Ct.current=De.ams_extruder_map)},[De?.ams_extruder_map]);const Zt=De?.ams_extruder_map&&Object.keys(De.ams_extruder_map).length>0?De.ams_extruder_map:Ct.current,Jt=w.useRef([]);w.useEffect(()=>{De?.ams&&De.ams.length>0&&(Jt.current=De.ams)},[De?.ams]);const Nn=De?.ams&&De.ams.length>0?De.ams:Jt.current,vn=w.useRef(void 0),yn=De?.tray_now;yn!==void 0&&yn!==255?vn.current=yn:yn===255&&(vn.current=void 0);const an=yn!==void 0&&yn!==255?yn:vn.current,{data:rn}=et({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>pe.getSmartPlugByPrinter(t.id)}),{data:bn}=et({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>pe.getScriptPlugsByPrinter(t.id)}),{data:Gn}=et({queryKey:["smartPlugStatus",rn?.id],queryFn:()=>rn?pe.getSmartPlugStatus(rn.id):null,enabled:!!rn,refetchInterval:1e4}),{data:ar}=et({queryKey:["queue",t.id,"pending"],queryFn:()=>pe.getQueue(t.id,"pending")}),On=w.useMemo(()=>ar?.length?sJ(ar,Ce,We).length:0,[ar,Ce,We]),{data:mi}=et({queryKey:["queue",t.id,"printing"],queryFn:()=>pe.getQueue(t.id,"printing"),enabled:De?.state==="RUNNING"}),{data:Rn}=et({queryKey:["currentPrintUser",t.id],queryFn:()=>pe.getCurrentPrintUser(t.id),enabled:De?.state==="RUNNING"}),na=mi?.[0]?.created_by_username||Rn?.username,{data:ra}=et({queryKey:["archives",t.id,"last"],queryFn:()=>pe.getArchives(t.id,1,0),enabled:De?.connected&&De?.state!=="RUNNING"}),jr=ra?.[0],In=e&&St===!1,Bi=lt({mutationFn:gt=>pe.deletePrinter(t.id,gt.deleteArchives),onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),M.invalidateQueries({queryKey:["archives"]}),M.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:gt=>T(gt.message||N("printers.toast.failedToDelete"),"error")}),Hi=lt({mutationFn:()=>pe.connectPrinter(t.id),onSuccess:()=>{M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),Ci=lt({mutationFn:gt=>pe.unlinkSpool(gt),onSuccess:gt=>{T(N("spoolman.unlinkSuccess")||gt?.message,"success"),M.invalidateQueries({queryKey:["linked-spools"]}),M.invalidateQueries({queryKey:["unlinked-spools"]})},onError:gt=>{T(gt.message||N("spoolman.unlinkFailed"),"error")}}),Hc=lt({mutationFn:({amsId:gt,temp:ge,duration:mt,filament:Je,rotateTray:$t})=>pe.startDrying(t.id,gt,ge,mt,Je,$t),onSuccess:()=>{xe(null),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>T(gt.message||N("printers.toast.failedToSendCommand"),"error")}),pa=lt({mutationFn:gt=>pe.stopDrying(t.id,gt),onSuccess:()=>{M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>T(gt.message||N("printers.toast.failedToSendCommand"),"error")}),jt=lt({mutationFn:gt=>rn?pe.controlSmartPlug(rn.id,gt):Promise.reject("No plug"),onSuccess:()=>{M.invalidateQueries({queryKey:["smartPlugStatus",rn?.id]})}}),Wn=lt({mutationFn:gt=>rn?pe.updateSmartPlug(rn.id,{auto_off:gt}):Promise.reject("No plug"),onSuccess:()=>{M.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),M.invalidateQueries({queryKey:["smart-plugs"]})}}),En=lt({mutationFn:({id:gt,action:ge})=>pe.controlSmartPlug(gt,ge),onSuccess:()=>{T(N("printers.toast.scriptTriggered"))},onError:gt=>T(gt.message||N("printers.toast.failedToRunScript"),"error")}),Vt=lt({mutationFn:()=>pe.stopPrint(t.id),onSuccess:()=>{T(N("printers.toast.printStopped")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>T(gt.message||N("printers.toast.failedToStopPrint"),"error")}),sc=lt({mutationFn:()=>pe.pausePrint(t.id),onSuccess:()=>{T(N("printers.toast.printPaused")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>T(gt.message||N("printers.toast.failedToPausePrint"),"error")}),mm=lt({mutationFn:()=>pe.resumePrint(t.id),onSuccess:()=>{T(N("printers.toast.printResumed")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>T(gt.message||N("printers.toast.failedToResumePrint"),"error")}),hs=lt({mutationFn:gt=>pe.setChamberLight(t.id,gt),onMutate:async gt=>{await M.cancelQueries({queryKey:["printerStatus",t.id]});const ge=M.getQueryData(["printerStatus",t.id]);return M.setQueryData(["printerStatus",t.id],mt=>({...mt,chamber_light:gt})),{previousStatus:ge}},onSuccess:(gt,ge)=>{T(`Chamber light ${ge?"on":"off"}`)},onError:(gt,ge,mt)=>{mt?.previousStatus&&M.setQueryData(["printerStatus",t.id],mt.previousStatus),T(gt.message||N("printers.toast.failedToControlChamberLight"),"error")}}),qc=lt({mutationFn:gt=>pe.setPrintSpeed(t.id,gt),onMutate:async gt=>{await M.cancelQueries({queryKey:["printerStatus",t.id]});const ge=M.getQueryData(["printerStatus",t.id]);return M.setQueryData(["printerStatus",t.id],mt=>({...mt,speed_level:gt})),{previousStatus:ge}},onError:(gt,ge,mt)=>{mt?.previousStatus&&M.setQueryData(["printerStatus",t.id],mt.previousStatus),T(gt.message||N("printers.toast.failedToSetSpeed"),"error")}}),Lo=lt({mutationFn:gt=>pe.updatePrinter(t.id,{plate_detection_enabled:gt}),onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),T(Lo.variables?N("printers.toast.plateCheckEnabled"):N("printers.toast.plateCheckDisabled"))},onError:gt=>T(gt.message||N("printers.toast.failedToUpdateSetting"),"error")}),$c=(De?.state==="RUNNING"||De?.state==="PAUSE")&&(De?.printable_objects_count??0)>=2,{data:Is}=et({queryKey:["printableObjects",t.id],queryFn:()=>pe.getPrintableObjects(t.id),enabled:Q||$c,refetchInterval:Q?5e3:$c?3e4:!1}),[ps,qi]=w.useState(null),Id=w.useRef(!1),Pi=w.useRef(null),lo=w.useRef(!1),hm=lt({mutationFn:({amsId:gt,slotId:ge})=>pe.refreshAmsSlot(t.id,gt,ge),onMutate:({amsId:gt,slotId:ge})=>{Pi.current&&clearTimeout(Pi.current),Id.current=!1,lo.current=!1,qi({amsId:gt,slotId:ge}),setTimeout(()=>{lo.current=!0},2e3),Pi.current=setTimeout(()=>{qi(null)},3e4)},onSuccess:gt=>{T(gt.message||N("printers.toast.rfidRereadInitiated"))},onError:gt=>{T(gt.message||N("printers.toast.failedToRereadRfid"),"error"),Pi.current&&clearTimeout(Pi.current),qi(null)}}),[zs,pm]=w.useState(null),[$i,Oo]=w.useState(null),oc=async()=>{try{const gt=await pe.getPlateReferences(t.id);pm(gt)}catch{}},ja=()=>{Lo.mutate(!t.plate_detection_enabled)},Us=async()=>{Ft(!0),en(null);const gt=De?.chamber_light===!1;pt(gt),gt&&(await pe.setChamberLight(t.id,!0),await new Promise(ge=>setTimeout(ge,2500)));try{const ge=await pe.checkPlateEmpty(t.id,{includeDebugImage:!0});en(ge),oc()}catch(ge){T(ge instanceof Error?ge.message:N("printers.toast.failedToCheckPlate"),"error"),gt&&(await pe.setChamberLight(t.id,!1),pt(!1))}finally{Ft(!1)}},fs=w.useCallback(async()=>{en(null),dt&&(await pe.setChamberLight(t.id,!1),pt(!1))},[dt,t.id]),Io=async gt=>{ht(!0);try{const ge=await pe.calibratePlateDetection(t.id,{label:gt});if(ge.success){T(ge.message||N("printers.toast.calibrationSaved"),"success"),oc();const mt=await pe.checkPlateEmpty(t.id,{includeDebugImage:!0});en(mt)}else T(ge.message||N("printers.toast.calibrationFailed"),"error")}catch(ge){T(ge instanceof Error?ge.message:N("printers.toast.calibrationFailed"),"error")}finally{ht(!1)}},up=async(gt,ge)=>{try{await pe.updatePlateReferenceLabel(t.id,gt,ge),Oo(null),oc()}catch(mt){T(mt instanceof Error?mt.message:N("printers.toast.failedToUpdateLabel"),"error")}},zd=async gt=>{try{await pe.deletePlateReference(t.id,gt),T(N("printers.toast.referenceDeleted"),"success"),oc();const ge=await pe.checkPlateEmpty(t.id,{includeDebugImage:!0});en(ge)}catch(ge){T(ge instanceof Error?ge.message:N("printers.toast.failedToDeleteReference"),"error")}},fm=async()=>{if(Mt){Ue(!0);try{await pe.updatePrinter(t.id,{plate_detection_roi:Mt}),T(N("printers.toast.detectionAreaSaved"),"success"),Qt(null);const gt=await pe.checkPlateEmpty(t.id,{includeDebugImage:!0});en(gt)}catch(gt){T(gt instanceof Error?gt.message:N("printers.toast.failedToSaveDetectionArea"),"error")}finally{Ue(!1)}}};w.useEffect(()=>{const gt=ge=>{ge.key==="Escape"&&Ut&&fs()};return window.addEventListener("keydown",gt),()=>window.removeEventListener("keydown",gt)},[Ut,fs]);const cn=w.useRef(null);w.useEffect(()=>{if(!ps)return;const gt=De?.ams_status_main??0;return gt!==0&&(Id.current=!0,cn.current&&(clearTimeout(cn.current),cn.current=null)),Id.current&&gt===0&&(lo.current?(Pi.current&&clearTimeout(Pi.current),qi(null)):cn.current||(cn.current=setTimeout(()=>{Pi.current&&clearTimeout(Pi.current),qi(null)},2e3))),()=>{cn.current&&clearTimeout(cn.current)}},[De?.ams_status_main,ps]);const[gs,ul]=w.useState(null);if(In)return null;const gg=()=>{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"}},mp=()=>{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"}},bg=()=>{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"}},Vc=St&&De?.state!=="RUNNING"&&De?.state!=="PAUSE"&&C("printers:control"),hp=gt=>{gt.preventDefault(),$e.current++,$e.current===1&&ze(!0)},_y=gt=>{gt.preventDefault(),gt.dataTransfer.dropEffect=Vc?"copy":"none"},gm=gt=>{gt.preventDefault(),$e.current--,$e.current===0&&ze(!1)},pp=async gt=>{if(gt.preventDefault(),$e.current=0,ze(!1),!Vc)return;const mt=Array.from(gt.dataTransfer.files)[0];if(!mt)return;const Je=mt.name.toLowerCase();if(!Je.endsWith(".gcode")&&!Je.includes(".gcode.")){T(N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed"),"error");return}Ge(!0);try{const $t=await pe.uploadLibraryFile(mt,null),tn=$t.metadata?.sliced_for_model,fn=p0(t.model);if(tn&&fn&&tn.toLowerCase()!==fn.toLowerCase()){await pe.deleteLibraryFile($t.id).catch(()=>{}),T(N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:tn,printerModel:fn}),"error");return}R({id:$t.id,filename:$t.filename})}catch{T(N("common.uploadFailed","Upload failed"),"error")}finally{Ge(!1)}};return a.jsxs(Dt,{className:`relative ${k?"ring-2 ring-bambu-green":""} ${_?"cursor-pointer":""}`,onDragEnter:hp,onDragOver:_y,onDragLeave:gm,onDrop:pp,children:[_&&a.jsx("div",{className:"absolute inset-0 z-20 flex items-start p-2",onClick:gt=>{gt.stopPropagation(),P?.(t.id)},children:k?a.jsx(us,{className:"w-5 h-5 text-bambu-green"}):a.jsx(eo,{className:"w-5 h-5 text-bambu-gray"})}),(ce||Ne)&&a.jsx("div",{className:`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${Ne?"bg-bambu-green/10 border-bambu-green/50":Vc?"bg-bambu-green/10 border-bambu-green":"bg-red-500/10 border-red-500/50"}`,children:a.jsx("div",{className:"text-center",children:Ne?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-sm font-medium text-bambu-green",children:N("common.uploading","Uploading...")})]}):Vc?a.jsxs(a.Fragment,{children:[a.jsx(Pr,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green"}),a.jsx("p",{className:"text-sm font-medium text-bambu-green",children:N("printers.dropToPrint","Drop to print")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Bt,{className:"w-8 h-8 mx-auto mb-2 text-red-400"}),a.jsx("p",{className:"text-sm font-medium text-red-400",children:N("printers.cannotPrint","Printer busy")})]})})}),a.jsxs(Rt,{className:i>=3?"p-5":"",children:[a.jsxs("div",{className:bg(),children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("img",{src:aJ(t.model),alt:t.model||N("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${gg()}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-semibold text-white ${mp()}`,children:t.name}),r==="compact"&&(()=>{const gt=De?.connected&&De.hms_errors?Tu(De.hms_errors):[],ge=gt.some(tn=>tn.severity<=2),mt=gt.length>0,Je=De?.connected?ge?"bg-status-error":mt?"bg-status-warning":"bg-status-ok":"bg-status-error",$t=De?.connected?mt?`${gt.length} HMS ${gt.length===1?"error":"errors"}`:N("printers.connection.connected"):N("printers.connection.offline");return a.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Je}`,title:$t})})()]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",r==="expanded"&&De?.nozzles&&De.nozzles[0]?.nozzle_diameter&&a.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:De.nozzles[0].nozzle_type||"Nozzle",children:["• ",De.nozzles[0].nozzle_diameter,"mm"]}),r==="expanded"&&n&&n.total_print_hours>0&&a.jsxs("span",{className:"ml-2 text-bambu-gray",children:[a.jsx(rr,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),a.jsxs("div",{className:"relative flex-shrink-0",children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>$(!F),children:a.jsx(Mh,{className:"w-4 h-4"})}),F&&a.jsxs("div",{className:"absolute right-0 mt-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20",children:[a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${C("printers:update")?"hover:bg-bambu-dark-tertiary":"opacity-50 cursor-not-allowed"}`,onClick:()=>{C("printers:update")&&(ee(!0),$(!1))},title:C("printers:update")?void 0:N("printers.permission.noEdit"),children:[a.jsx(Za,{className:"w-4 h-4"}),N("common.edit")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{fe(!0),$(!1)},children:[a.jsx(Ks,{className:"w-4 h-4"}),N("printers.printerInformation")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{Hi.mutate(),$(!1)},children:[a.jsx(vr,{className:"w-4 h-4"}),N("printers.reconnect")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{K(!0),$(!1)},children:[a.jsx(kQ,{className:"w-4 h-4"}),N("printers.mqttDebug")]}),a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${C("printers:delete")?"text-red-400 hover:bg-bambu-dark-tertiary":"text-red-400/50 cursor-not-allowed"}`,onClick:()=>{C("printers:delete")&&(X(!0),$(!1))},title:C("printers:delete")?void 0:N("printers.permission.noDelete"),children:[a.jsx(un,{className:"w-4 h-4"}),N("common.delete")]})]})]})]}),r==="expanded"&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[a.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${De?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[De?.connected?a.jsx(ny,{className:"w-3 h-3"}):a.jsx(qh,{className:"w-3 h-3"}),De?.connected?N("printers.connection.connected"):N("printers.connection.offline")]}),De?.connected&&De?.wired_network&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok",title:N("printers.connection.ethernet","Ethernet"),children:[a.jsx(cO,{className:"w-3 h-3"}),N("printers.connection.ethernet","Ethernet")]}),De?.connected&&!De?.wired_network&&vt!=null&&a.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${vt>=-50||vt>=-60?"bg-status-ok/20 text-status-ok":vt>=-70?"bg-status-warning/20 text-status-warning":vt>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${vt} dBm - ${N(iJ(vt).labelKey)}`,children:[a.jsx(wQ,{className:"w-3 h-3"}),vt,"dBm"]}),De?.connected&&(()=>{const gt=De.hms_errors?Tu(De.hms_errors):[];return a.jsxs("button",{onClick:()=>Y(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${gt.length>0?gt.some(ge=>ge.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:N("printers.clickToViewHmsErrors"),children:[a.jsx(Ln,{className:"w-3 h-3"}),gt.length>0?gt.length:"OK"]})})(),n&&a.jsxs("button",{onClick:()=>A("/maintenance"),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${n.due_count>0?"bg-status-error/20 text-status-error":n.warning_count>0?"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:n.due_count>0||n.warning_count>0?`${n.due_count>0?`${n.due_count} maintenance due`:""}${n.due_count>0&&n.warning_count>0?", ":""}${n.warning_count>0?`${n.warning_count} due soon`:""} - Click to view`:N("printers.maintenanceUpToDate"),children:[a.jsx(zf,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),On>0&&a.jsxs("button",{onClick:()=>A("/queue"),className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-purple-500/20 text-purple-400 hover:opacity-80 transition-opacity",title:N("printers.queue.inQueue",{count:On}),children:[a.jsx(ea,{className:"w-3 h-3"}),On]}),v&&Le?.current_version&&Le?.latest_version?a.jsxs("button",{onClick:()=>Kt(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${Le.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:Le.update_available?N("printers.firmwareUpdateAvailable",{current:Le.current_version,latest:Le.latest_version}):N("printers.firmwareUpToDate",{version:Le.current_version}),children:[Le.update_available?a.jsx(va,{className:"w-3 h-3"}):a.jsx(fr,{className:"w-3 h-3"}),Le.current_version]}):De?.firmware_version?a.jsx("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray",children:De.firmware_version}):null]})]}),I&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(Dt,{className:"w-full max-w-md mx-4",children:a.jsxs(Rt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:a.jsx(Ln,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:N("printers.confirm.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:N("printers.confirm.deleteMessage",{name:t.name})})]})]}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:a.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:L,onChange:gt=>te(gt.target.checked),className:"mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:N("printers.deleteArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:N(L?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>{X(!1),te(!0)},children:N("common.cancel")}),a.jsx(Ie,{variant:"danger",onClick:()=>{Bi.mutate({deleteArchives:L}),X(!1),te(!0)},children:"Delete"})]})]})})}),De?.connected&&a.jsxs(a.Fragment,{children:[r==="compact"?a.jsx("div",{className:"mt-2",children:De.state==="RUNNING"||De.state==="PAUSE"?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:`${De.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-1.5 rounded-full transition-all`,style:{width:`${De.progress||0}%`}})}),a.jsxs("span",{className:"text-xs text-white",children:[Math.round(De.progress||0),"%"]})]}):a.jsx("p",{className:"text-xs text-bambu-gray",children:wD(De.state,De.stg_cur_name)})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[a.jsxs("button",{onClick:()=>V(!0),disabled:!(De.state==="RUNNING"||De.state==="PAUSE")||(De.printable_objects_count??0)<2||!C("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(De.state==="RUNNING"||De.state==="PAUSE")&&(De.printable_objects_count??0)>=2&&C("printers:control")?"text-bambu-gray hover:text-white hover:bg-white/10":"text-bambu-gray/30 cursor-not-allowed"}`,title:C("printers:control")?De.state==="RUNNING"||De.state==="PAUSE"?(De.printable_objects_count??0)>=2?N("printers.skipObjects.tooltip"):N("printers.skipObjects.requiresMultiple"):N("printers.skipObjects.onlyWhilePrinting"):N("printers.permission.noControl"),children:[a.jsx(zP,{className:"w-4 h-4"}),Is&&Is.skipped_count>0&&a.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full",children:Is.skipped_count})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(XVe,{url:De.state==="RUNNING"||De.state==="PAUSE"?De.cover_url:null,printName:(De.state==="RUNNING"||De.state==="PAUSE")&&BW(De.subtask_name||De.current_print||null,De.gcode_file,N)||void 0}),a.jsx("div",{className:"flex-1 min-w-0",children:De.current_print&&(De.state==="RUNNING"||De.state==="PAUSE")?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:wD(De.state,De.stg_cur_name)}),a.jsx("p",{className:"text-white text-sm mb-2 truncate",children:BW(De.subtask_name||De.current_print||null,De.gcode_file,N)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:`${De.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-2 rounded-full transition-all`,style:{width:`${De.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(De.progress||0),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[De.remaining_time!=null&&De.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(De.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:N("printers.estimatedCompletion"),children:["ETA ",vO(De.remaining_time,p,N)]})]}),De.layer_num!=null&&De.total_layers!=null&&De.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ea,{className:"w-3 h-3"}),De.layer_num,"/",De.total_layers]}),na&&a.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${na}`,children:[a.jsx(Wu,{className:"w-3 h-3"}),na]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:N("printers.sort.status")}),a.jsx("p",{className:"text-white text-sm mb-2",children:wD(De.state,De.stg_cur_name)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),a.jsx("span",{className:"text-bambu-gray",children:"—"})]}),jr?a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:jr.print_name||jr.filename,children:["Last: ",jr.print_name||jr.filename,jr.completed_at&&a.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",Uf(jr.completed_at,{month:"short",day:"numeric"})]})]}):a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.readyToPrint")})]})})]})]}),a.jsx(cje,{printerId:t.id,printerModel:t.model,printerState:De.state,plateCleared:De.plate_cleared,requirePlateClear:g,loadedFilamentTypes:Ce,loadedFilaments:We})]}),De.temperatures&&r==="expanded"&&(()=>{const gt=De.temperatures.nozzle_heating||De.temperatures.nozzle_2_heating||!1,ge=De.temperatures.bed_heating||!1,mt=De.temperatures.chamber_heating||!1,Je=t.nozzle_count===2||De.temperatures.nozzle_2!==void 0,$t=De.active_extruder===1?"L":"R",tn=De.nozzle_rack?.find(Kn=>Kn.id===1),fn=De.nozzle_rack?.find(Kn=>Kn.id===0),gr=fn||tn;return a.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(yD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:gt}),De.temperatures.nozzle_2!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(De.temperatures.nozzle||0),"° / ",Math.round(De.temperatures.nozzle_2||0),"°"]})]}):gr?a.jsx(jae,{slot:gr,index:0,activeStatus:!0,filamentName:gr.filament_id?Xe?.[gr.filament_id]?.name:void 0,children:a.jsxs("div",{className:"cursor-default",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(De.temperatures.nozzle||0),"°C"]})]})}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(De.temperatures.nozzle||0),"°C"]})]})]}),a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(yD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:ge}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.bed")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(De.temperatures.bed||0),"°C"]})]}),De.temperatures.chamber!==void 0&&a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(yD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:mt}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.chamber")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(De.temperatures.chamber||0),"°C"]})]}),Je&&a.jsx(qVe,{leftSlot:tn,rightSlot:fn,activeNozzle:$t,filamentInfo:Xe,children:a.jsxs("div",{className:"text-center px-3 py-1.5 bg-bambu-dark rounded-lg h-full flex flex-col justify-center items-center cursor-default",title:N("printers.activeNozzle",{nozzle:N($t==="L"?"common.left":"common.right")}),children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`text-[11px] font-bold ${$t==="L"?"text-amber-400":"text-gray-500"}`,children:["L",tn?.nozzle_diameter?` ${tn.nozzle_diameter}`:""]}),a.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),a.jsxs("span",{className:`text-[11px] font-bold ${$t==="R"?"text-amber-400":"text-gray-500"}`,children:["R",fn?.nozzle_diameter?` ${fn.nozzle_diameter}`:""]})]}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")})]})}),De.nozzle_rack&&De.nozzle_rack.some(Kn=>Kn.id>=2)&&a.jsx($Ve,{slots:De.nozzle_rack,filamentInfo:Xe})]})})(),r==="expanded"&&(()=>{const gt=De.state==="RUNNING",ge=De.state==="PAUSE",mt=gt||ge,Je=Vt.isPending||sc.isPending||mm.isPending,$t=De.cooling_fan_speed,tn=De.big_fan1_speed,fn=De.big_fan2_speed;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.controls")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 max-[550px]:items-start",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 max-[550px]:flex-wrap max-[550px]:items-start max-[550px]:gap-1.5",children:[a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${$t&&$t>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:N("printers.fans.partCooling"),children:[a.jsx(hQ,{className:`w-3.5 h-3.5 ${$t&&$t>0?"text-cyan-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${$t&&$t>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[$t??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${tn&&tn>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:N("printers.fans.auxiliary"),children:[a.jsx(PQ,{className:`w-3.5 h-3.5 ${tn&&tn>0?"text-blue-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${tn&&tn>0?"text-blue-400":"text-bambu-gray/50"}`,children:[tn??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${fn&&fn>0?"bg-green-500/10":"bg-bambu-dark"}`,title:N("printers.fans.chamber"),children:[a.jsx(qhe,{className:`w-3.5 h-3.5 ${fn&&fn>0?"text-green-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${fn&&fn>0?"text-green-400":"text-bambu-gray/50"}`,children:[fn??0,"%"]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-gray/30"}),(()=>{const Kn={1:"50%",2:"100%",3:"124%",4:"166%"}[De.speed_level]||"100%";return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>de(q===t.id?null:t.id),disabled:!mt||!C("printers:control"),className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${mt?"bg-amber-500/10 hover:bg-amber-500/20":"bg-bambu-dark cursor-not-allowed"}`,title:mt?N("printers.speed.title"):void 0,children:[a.jsx(Aw,{className:`w-3.5 h-3.5 ${mt?"text-amber-400":"text-bambu-gray/50"}`}),a.jsx("span",{className:`text-[10px] ${mt?"text-amber-400":"text-bambu-gray/50"}`,children:Kn})]}),q===t.id&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>de(null)}),a.jsx("div",{className:"absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg py-1 min-w-[130px]",children:[{mode:1,label:N("printers.speed.silent")},{mode:2,label:N("printers.speed.standard")},{mode:3,label:N("printers.speed.sport")},{mode:4,label:N("printers.speed.ludicrous")}].map(({mode:sn,label:Mn})=>a.jsx("button",{onClick:()=>{qc.mutate(sn),de(null)},className:`w-full text-left px-3 py-1.5 text-xs transition-colors ${De.speed_level===sn?"text-bambu-green bg-bambu-green/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:Mn},sn))})]})]})})()]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 max-[550px]:self-start",children:[a.jsxs("button",{onClick:()=>j(!0),disabled:!mt||Je||!C("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. ${mt&&C("printers:control")?"bg-red-500/20 text-red-400 hover:bg-red-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}
  8183. `,title:C("printers:control")?N("printers.stop"):N("printers.permission.noControl"),children:[a.jsx(eo,{className:"w-3 h-3"}),N("printers.stop")]}),a.jsxs("button",{onClick:()=>ge?G(!0):W(!0),disabled:!mt||Je||!C("printers:control"),className:`
  8184. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  8185. transition-colors
  8186. ${mt&&C("printers:control")?ge?"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"}
  8187. `,title:C("printers:control")?N(ge?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[ge?a.jsx(Ds,{className:"w-3 h-3"}):a.jsx(Fw,{className:"w-3 h-3"}),N(ge?"printers.resume":"printers.pause")]})]})]})]})})(),(Nn?.length>0||De.vt_tray.length>0)&&r==="expanded"&&(()=>{const gt=Nn.filter(Je=>Je.tray.length>1),ge=Nn.filter(Je=>Je.tray.length===1),mt=t.nozzle_count===2||De?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[gt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:gt.map(Je=>{const $t=Zt[String(Je.id)],tn=Je.id>=128?Je.id-128:Je.id,fn=$t!==void 0?$t:tn,gr=fn===1,Kn=fn===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(GW,{ams:Je,printerId:t.id,label:Cl(Je.id,Je.tray.length),amsLabels:Ze,canEdit:C("printers:update"),onSaved:rt,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Ze?.[Je.id]||Cl(Je.id,Je.tray.length)})}),mt&&(gr||Kn)&&a.jsx(HW,{side:gr?"L":"R"})]}),(Je.humidity!=null||Je.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[Je.humidity!=null&&a.jsx($W,{humidity:Je.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Me({amsId:Je.id,amsLabel:Cl(Je.id,Je.tray.length),mode:"humidity"}),compact:!0}),Je.temp!=null&&a.jsx(VW,{temp:Je.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Me({amsId:Je.id,amsLabel:Cl(Je.id,Je.tray.length),mode:"temperature"}),compact:!0}),De.supports_drying&&(Je.module_type==="n3f"||Je.module_type==="n3s")&&C("printers:control")&&a.jsx("button",{disabled:!!(Je.dry_sf_reason?.length&&Je.dry_time===0),onClick:sn=>{if(Je.dry_time>0)pa.mutate(Je.id);else if(re===Je.id)xe(null);else{const bs=(Je.tray.find(hl=>hl.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),xs=b[bs]||b.PLA,ml=Je.module_type;ve(bs),Fe(xs[ml]||xs.n3f),Se(ml==="n3s"?xs.n3s_hours:xs.n3f_hours),qe(!1),ye(Je.module_type),xe(Je.id);const lc=sn.currentTarget.getBoundingClientRect();Ye({top:lc.bottom+4,left:Math.max(8,lc.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${Je.dry_time>0?"bg-amber-500/20 text-amber-400":Je.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:Je.dry_time>0?N("printers.drying.stop"):Je.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Qp,{className:"w-3 h-3"})})]})]}),Je.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:Je.dry_time>=60?`${Math.floor(Je.dry_time/60)}h ${Je.dry_time%60}m`:`${Je.dry_time}m`})}),a.jsx("button",{onClick:()=>pa.mutate(Je.id),disabled:pa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(sn=>{const Mn=Je.tray[sn]||Je.tray.find(Cn=>Cn.id===sn),bs=Mn?.tray_type&&Mn.remain>=0,xs=!Mn?.tray_type,ml=Je.id*4+sn,lc=an===ml,hl=Mn?.tray_info_idx?Xe?.[Mn.tray_info_idx]:null,_a=Qe?.[ml],Vi=(Mn?.tray_uuid||Mn?.tag_uid||Su(t.serial_number,Je.id,sn))?.toUpperCase(),cc=Vi?l?.[Vi]:void 0,ys=Rk(cc),Bs=u?.(t.id,Je.id,sn),co=(()=>{const Cn=Bs?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),la=co===0&&bs&&Mn.remain>0?null:co,uo=ys??la??(bs?Mn.remain:null),xg=ys!==null?"spoolman":la!==null?"inventory":bs?"ams":void 0,aa=Mn?.tray_type?{vendor:vD(Mn)?"Bambu Lab":"Generic",profile:_a?.preset_name||hl?.name||Bs?.spool?.slicer_filament_name||Mn.tray_sub_brands||Mn.tray_type,colorName:bD(Mn.tray_id_name)||Vl(Mn.tray_color||""),colorHex:Mn.tray_color||null,kFactor:xD(Mn.k),fillLevel:uo,trayUuid:Mn.tray_uuid||null,tagUid:Mn.tag_uid||null,fillSource:xg}:null,Gc=ps?.amsId===Je.id&&ps?.slotId===sn,bm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${xs?"opacity-50":""} ${lc?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(gD,{trayColor:Mn?.tray_color,trayType:Mn?.tray_type,isEmpty:xs,slotNumber:sn+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Mn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:uo!==null&&uo>=0&&!xs&&Mn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${uo}%`,backgroundColor:mx(uo)}})})]});return a.jsxs("div",{className:"relative group",children:[Gc&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),De?.state!=="RUNNING"&&a.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),ul(gs?.amsId===Je.id&&gs?.slotId===sn?null:{amsId:Je.id,slotId:sn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),De?.state!=="RUNNING"&&gs?.amsId===Je.id&&gs?.slotId===sn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),C("printers:ams_rfid")&&(hm.mutate({amsId:Je.id,slotId:sn}),ul(null))},disabled:Gc||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${Gc?"animate-spin":""}`}),N("printers.rfid.reread")]})}),aa?a.jsx(mD,{data:aa,spoolman:{enabled:o,linkedSpoolId:Vi?l?.[Vi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Cn=(aa.trayUuid||aa.tagUid||Su(t.serial_number,Je.id,sn)).toUpperCase();tt({tagUid:aa.tagUid||Cn,trayUuid:aa.trayUuid||"",printerId:t.id,amsId:Je.id,trayId:sn})}:void 0,onUnlinkSpool:cc?.id?()=>Ci.mutate(cc.id):void 0},inventory:o?void 0:(()=>{const Cn=u?.(t.id,Je.id,sn);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:aa.vendor!=="Bambu Lab"?()=>xt({printerId:t.id,amsId:Je.id,trayId:sn,trayInfo:{type:Mn?.tray_type||aa.profile,material:Mn?.tray_type??void 0,profile:aa.profile,color:aa.colorHex||"",location:`${Cl(Je.id,Je.tray.length)} Slot ${sn+1}`}}):void 0,onUnassignSpool:Cn&&aa.vendor!=="Bambu Lab"?()=>m?.(t.id,Je.id,sn):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:Je.id,trayId:sn,trayCount:Je.tray.length,trayType:Mn?.tray_type||void 0,trayColor:Mn?.tray_color||void 0,traySubBrands:Mn?.tray_sub_brands||void 0,trayInfoIdx:Mn?.tray_info_idx||void 0,extruderId:$t,caliIdx:Mn?.cali_idx,savedPresetId:_a?.preset_id})},children:bm}):a.jsx(hD,{configureSlot:Mn?.state===10?{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:Je.id,trayId:sn,trayCount:Je.tray.length,extruderId:$t})}:void 0,inventory:Mn?.state===10&&!o?{onAssignSpool:()=>xt({printerId:t.id,amsId:Je.id,trayId:sn,trayInfo:{type:"",color:"",location:`${Cl(Je.id,Je.tray.length)} Slot ${sn+1}`}})}:void 0,children:bm})]},sn)})})]},Je.id)})}),(ge.length>0||De.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[ge.map(Je=>{const $t=Zt[String(Je.id)],tn=Je.id>=128?Je.id-128:Je.id,fn=$t!==void 0?$t:tn,gr=fn===1,Kn=fn===0,sn=Je.tray[0],Mn=sn?.tray_type&&sn.remain>=0,bs=!sn?.tray_type,xs=Ux(Je.id,sn?.id??0,!1),ml=an===xs,lc=sn?.tray_info_idx?Xe?.[sn.tray_info_idx]:null,hl=Qe?.[xs],_a=sn?.id??0,Vi=(sn?.tray_uuid||sn?.tag_uid||Su(t.serial_number,Je.id,_a))?.toUpperCase(),cc=Vi?l?.[Vi]:void 0,ys=Rk(cc),Bs=u?.(t.id,Je.id,_a),co=(()=>{const Cn=Bs?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),la=co===0&&Mn&&sn.remain>0?null:co,uo=ys??la??(Mn?sn.remain:null),xg=ys!==null?"spoolman":la!==null?"inventory":Mn?"ams":void 0,aa=sn?.tray_type?{vendor:vD(sn)?"Bambu Lab":"Generic",profile:hl?.preset_name||lc?.name||Bs?.spool?.slicer_filament_name||sn.tray_sub_brands||sn.tray_type,colorName:bD(sn.tray_id_name)||Vl(sn.tray_color||""),colorHex:sn.tray_color||null,kFactor:xD(sn.k),fillLevel:uo,trayUuid:sn.tray_uuid||null,tagUid:sn.tag_uid||null,fillSource:xg}:null,Gc=ps?.amsId===Je.id&&ps?.slotId===_a,bm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${bs?"opacity-50":""} ${ml?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(gD,{trayColor:sn?.tray_color,trayType:sn?.tray_type,isEmpty:bs,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:sn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:uo!==null&&uo>=0&&!bs&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${uo}%`,backgroundColor:mx(uo)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(GW,{ams:Je,printerId:t.id,label:Cl(Je.id,Je.tray.length),amsLabels:Ze,canEdit:C("printers:update"),onSaved:rt,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Ze?.[Je.id]||Cl(Je.id,Je.tray.length)})}),mt&&(gr||Kn)&&a.jsx(HW,{side:gr?"L":"R"}),De.supports_drying&&(Je.module_type==="n3f"||Je.module_type==="n3s")&&C("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:Cn=>{if(Je.dry_time>0)pa.mutate(Je.id);else if(re===Je.id)xe(null);else{const vS=(Je.tray.find(fp=>fp.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),yg=b[vS]||b.PLA,ky=Je.module_type;ve(vS),Fe(yg[ky]||yg.n3f),Se(ky==="n3s"?yg.n3s_hours:yg.n3f_hours),qe(!1),ye(Je.module_type),xe(Je.id);const Ny=Cn.currentTarget.getBoundingClientRect();Ye({top:Ny.bottom+4,left:Math.max(8,Ny.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${Je.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:Je.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Qp,{className:"w-3 h-3"})})})]}),Je.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:Je.dry_time>=60?`${Math.floor(Je.dry_time/60)}h ${Je.dry_time%60}m`:`${Je.dry_time}m`}),a.jsx("button",{onClick:()=>pa.mutate(Je.id),disabled:pa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Gc&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),De?.state!=="RUNNING"&&a.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),ul(gs?.amsId===Je.id&&gs?.slotId===_a?null:{amsId:Je.id,slotId:_a})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),De?.state!=="RUNNING"&&gs?.amsId===Je.id&&gs?.slotId===_a&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),C("printers:ams_rfid")&&(hm.mutate({amsId:Je.id,slotId:_a}),ul(null))},disabled:Gc||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${Gc?"animate-spin":""}`}),N("printers.rfid.reread")]})}),aa?a.jsx(mD,{data:aa,spoolman:{enabled:o,linkedSpoolId:Vi?l?.[Vi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Cn=(aa.trayUuid||aa.tagUid||Su(t.serial_number,Je.id,_a)).toUpperCase();tt({tagUid:aa.tagUid||Cn,trayUuid:aa.trayUuid||"",printerId:t.id,amsId:Je.id,trayId:_a})}:void 0,onUnlinkSpool:cc?.id?()=>Ci.mutate(cc.id):void 0},inventory:o?void 0:(()=>{const Cn=u?.(t.id,Je.id,_a);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:aa.vendor!=="Bambu Lab"?()=>xt({printerId:t.id,amsId:Je.id,trayId:_a,trayInfo:{type:sn?.tray_type||aa.profile,material:sn?.tray_type??void 0,profile:aa.profile,color:aa.colorHex||"",location:Cl(Je.id,Je.tray.length)}}):void 0,onUnassignSpool:Cn&&aa.vendor!=="Bambu Lab"?()=>m?.(t.id,Je.id,_a):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:Je.id,trayId:_a,trayCount:Je.tray.length,trayType:sn?.tray_type||void 0,trayColor:sn?.tray_color||void 0,traySubBrands:sn?.tray_sub_brands||void 0,trayInfoIdx:sn?.tray_info_idx||void 0,extruderId:$t,caliIdx:sn?.cali_idx,savedPresetId:hl?.preset_id})},children:bm}):a.jsx(hD,{configureSlot:sn?.state===10?{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:Je.id,trayId:_a,trayCount:Je.tray.length,extruderId:$t})}:void 0,inventory:sn?.state===10&&!o?{onAssignSpool:()=>xt({printerId:t.id,amsId:Je.id,trayId:_a,trayInfo:{type:"",color:"",location:Cl(Je.id,Je.tray.length)}})}:void 0,children:bm})]}),(Je.humidity!=null||Je.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[Je.temp!=null&&a.jsx(VW,{temp:Je.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Me({amsId:Je.id,amsLabel:Cl(Je.id,Je.tray.length),mode:"temperature"}),compact:!0}),Je.humidity!=null&&a.jsx($W,{humidity:Je.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Me({amsId:Je.id,amsLabel:Cl(Je.id,Je.tray.length),mode:"humidity"}),compact:!0})]})]})]},Je.id)}),De.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${De.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${De.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...De.vt_tray].sort((Je,$t)=>(Je.id??254)-($t.id??254)).map(Je=>{const $t=Je.id??254,tn=mt&&an===254?$t===254&&De.active_extruder===1||$t===255&&De.active_extruder===0:an===$t,fn=$t-254,gr=mt?N($t===254?"printers.extL":"printers.extR"):"",Kn=Je.tray_info_idx?Xe?.[Je.tray_info_idx]:null,sn=Qe?.[1020+fn],Mn=(Je.tray_uuid||Je.tag_uid||Su(t.serial_number,255,fn))?.toUpperCase(),bs=Mn?l?.[Mn]:void 0,xs=Rk(bs),ml=u?.(t.id,255,fn),lc=(()=>{const la=ml?.spool;return la&&la.label_weight>0&&la.weight_used!=null?Math.round(Math.max(0,la.label_weight-la.weight_used)/la.label_weight*100):null})(),hl=Je.tray_type&&Je.remain>=0,_a=lc===0&&hl&&Je.remain>0?null:lc,Vi=xs??_a??(hl?Je.remain:null),cc=xs!==null?"spoolman":_a!==null?"inventory":hl?"ams":void 0,ys={vendor:vD(Je)?"Bambu Lab":"Generic",profile:sn?.preset_name||Kn?.name||ml?.spool?.slicer_filament_name||Je.tray_sub_brands||Je.tray_type||"Unknown",colorName:bD(Je.tray_id_name)||Vl(Je.tray_color||""),colorHex:Je.tray_color||null,kFactor:xD(Je.k),fillLevel:Vi,trayUuid:Je.tray_uuid||null,tagUid:Je.tag_uid||null,fillSource:cc},Bs=!Je.tray_type,co=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Bs?"opacity-50":""} ${tn?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(gD,{trayColor:Je.tray_color,trayType:Je.tray_type,isEmpty:Bs,slotNumber:fn+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Bs?"text-white/40":"text-white"}`,children:Je.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Vi!==null&&Vi>=0&&!Bs&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Vi}%`,backgroundColor:mx(Vi)}})}),gr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:gr})]});return a.jsx("div",{className:"relative group",children:Bs?a.jsx(hD,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:255,trayId:fn,trayCount:1,extruderId:mt?$t===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>xt({printerId:t.id,amsId:255,trayId:fn,trayInfo:{type:"",color:"",location:gr||N("printers.external")}})},children:co}):a.jsx(mD,{data:ys,spoolman:{enabled:o,linkedSpoolId:Mn?l?.[Mn]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const la=(ys.trayUuid||ys.tagUid||Su(t.serial_number,255,fn)).toUpperCase();tt({tagUid:ys.tagUid||la,trayUuid:ys.trayUuid||"",printerId:t.id,amsId:255,trayId:fn})}:void 0,onUnlinkSpool:bs?.id?()=>Ci.mutate(bs.id):void 0},inventory:o?void 0:(()=>{const la=u?.(t.id,255,fn);return{assignedSpool:la?.spool?{id:la.spool.id,material:la.spool.material,brand:la.spool.brand,color_name:la.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(la.spool.label_weight-la.spool.weight_used))}:null,onAssignSpool:()=>xt({printerId:t.id,amsId:255,trayId:fn,trayInfo:{type:Je.tray_type||ys.profile,material:Je.tray_type??void 0,profile:ys.profile,color:ys.colorHex||"",location:gr||N("printers.external")}}),onUnassignSpool:la?()=>m?.(t.id,255,fn):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>Ht({amsId:255,trayId:fn,trayCount:1,trayType:Je.tray_type||void 0,trayColor:Je.tray_color||void 0,traySubBrands:Je.tray_sub_brands||void 0,trayInfoIdx:Je.tray_info_idx||void 0,extruderId:mt?$t===254?1:0:void 0,caliIdx:Je.cali_idx,savedPresetId:sn?.preset_id})},children:co})},$t)})})]})]})]})]})})()]}),rn&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Xl,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:rn.name}),Gn&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Gn.state==="ON"?"bg-bambu-green/20 text-bambu-green":Gn.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Gn.state||"?",Gn.state==="ON"&&Gn.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Gn.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>oe(!0),disabled:jt.isPending||Gn?.state==="ON"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Gn?.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:C("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(im,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>_e(!0),disabled:jt.isPending||Gn?.state==="OFF"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Gn?.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:C("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Rw,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${rn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:rn.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Wn.mutate(!rn.auto_off),disabled:Wn.isPending||rn.auto_off_executed||!C("smart_plugs:control"),title:C("smart_plugs:control")?rn.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${C("smart_plugs:control")?rn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":rn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${rn.auto_off||rn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),bn&&bn.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Mw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:bn.map(gt=>{const ge=gt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>En.mutate({id:gt.id,action:ge?"on":"toggle"}),disabled:En.isPending,title:`${ge?"Run":"Toggle"} ${gt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(Ds,{className:"w-2.5 h-2.5"}),gt.name]},gt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>hs.mutate(!De?.chamber_light),disabled:!De?.connected||hs.isPending||!C("printers:control"),title:C("printers:control")?De?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:De?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(YO,{on:De?.chamber_light??!1,className:`w-4 h-4 ${De?.chamber_light?"text-yellow-400":""}`})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&y)y(t.id,t.name);else{const gt=localStorage.getItem("cameraWindowState"),ge=gt?JSON.parse(gt):{width:640,height:400},mt=[`width=${ge.width}`,`height=${ge.height}`,ge.left!==void 0?`left=${ge.left}`:"",ge.top!==void 0?`top=${ge.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,mt)}},disabled:!De?.connected||!C("camera:view"),title:C("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(gO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:ja,disabled:!De?.connected||Lo.isPending||!C("printers:update"),title:C("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Lo.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(iN,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:Us,disabled:!De?.connected||Ke||!C("printers:update"),title:C("printers:update")?N("printers.plateDetection.manageCalibration"):N("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Ke?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):a.jsx(Fn,{className:"w-3 h-3"})})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>le(!0),disabled:!St||!C("printers:files"),title:C("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(ty,{className:"w-4 h-4"}),N("printers.files")]}),St&&De?.state!=="RUNNING"&&De?.state!=="PAUSE"&&a.jsxs(Ie,{size:"sm",onClick:()=>ie(!0),disabled:!C("printers:control"),title:C("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Pr,{className:"w-4 h-4"}),N("common.print")]})]})]}),me&&a.jsx(nje,{printerId:t.id,printerName:t.name,onClose:()=>le(!1)}),J&&a.jsx(kae,{folderId:null,onClose:()=>ie(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:gt=>{const ge=gt.name.toLowerCase();if(!ge.endsWith(".gcode")&&!ge.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:gt=>{const ge=gt.metadata?.sliced_for_model,mt=p0(t.model);if(ge&&mt&&ge.toLowerCase()!==mt.toLowerCase())return pe.deleteLibraryFile(gt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:ge,printerModel:mt});R({id:gt.id,filename:gt.filename})}}),U&&a.jsx(kd,{mode:"reprint",libraryFileId:U.id,archiveName:U.filename,initialSelectedPrinterIds:[t.id],onClose:()=>R(null),onSuccess:()=>R(null)}),ue&&a.jsx(lje,{printerId:t.id,printerName:t.name,onClose:()=>K(!1)}),he&&a.jsx(UVe,{printer:t,status:De,totalPrintHours:n?.total_print_hours,onClose:se}),Ut&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>fs(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:gt=>gt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[Ut.needs_calibration?a.jsx(iN,{className:"w-5 h-5 text-blue-500"}):Ut.is_empty?a.jsx(fr,{className:"w-5 h-5 text-green-500"}):a.jsx($a,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Ut.reference_count!==void 0&&Ut.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Ut.reference_count,"/",Ut.max_references," refs"]})]}),a.jsx("button",{onClick:()=>fs(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Ut.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${Ut.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${Ut.is_empty?"text-green-400":"text-yellow-400"}`,children:Ut.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(Ut.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",Ut.difference_percent.toFixed(1),"%"]})]}),Ut.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:Ut.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Ut.message})]}),zs&&zs.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:zs.references.length,max:zs.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:zs.references.map(gt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:pe.getPlateReferenceThumbnailUrl(t.id,gt.index),alt:gt.label||`Reference ${gt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>zd(gt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:N("printers.plateDetection.deleteReference"),children:a.jsx(Bt,{className:"w-3 h-3 text-white"})}),$i?.index===gt.index?a.jsx("input",{type:"text",value:$i.label,onChange:ge=>Oo({...$i,label:ge.target.value}),onBlur:()=>up(gt.index,$i.label),onKeyDown:ge=>{ge.key==="Enter"&&up(gt.index,$i.label),ge.key==="Escape"&&Oo(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Oo({index:gt.index,label:gt.label}),title:gt.label?N("printers.plateDetection.clickToEdit",{label:gt.label}):N("printers.plateDetection.clickToAddLabel"),children:gt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:gt.timestamp?Qn(gt.timestamp)?.toLocaleDateString()??"":""})]},gt.index))})]}),!Ut.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),Mt?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>Qt(null),disabled:Wt,children:N("common.cancel")}),a.jsx(Ie,{size:"sm",onClick:fm,disabled:Wt,children:Wt?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>Qt(Ut.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Za,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),Mt?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:Mt.x,onChange:gt=>Qt({...Mt,x:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Mt.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:Mt.y,onChange:gt=>Qt({...Mt,y:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Mt.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:Mt.w,onChange:gt=>Qt({...Mt,w:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Mt.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:Mt.h,onChange:gt=>Qt({...Mt,h:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Mt.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Ut.roi?.x||.15)*100),"%, Y=",Math.round((Ut.roi?.y||.35)*100),"%, W=",Math.round((Ut.roi?.w||.7)*100),"%, H=",Math.round((Ut.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Ut.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",onClick:()=>fs(),children:N("common.cancel")}),a.jsx(Ie,{onClick:()=>Io(),disabled:Nt,children:Nt?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",onClick:()=>Io(),disabled:Nt,children:Nt?"Adding...":`Add Reference (${zs?.references.length||0}/${zs?.max_references||5})`}),a.jsx(Ie,{onClick:()=>fs(),children:"Close"})]})})]})}),ne&&rn&&a.jsx(kn,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{jt.mutate("on"),oe(!1)},onCancel:()=>oe(!1)}),be&&rn&&a.jsx(kn,{title:N("printers.confirm.powerOffTitle"),message:De?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{jt.mutate("off"),_e(!1)},onCancel:()=>_e(!1)}),D&&a.jsx(kn,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Vt.mutate(),j(!1)},onCancel:()=>j(!1)}),z&&a.jsx(kn,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{sc.mutate(),W(!1)},onCancel:()=>W(!1)}),O&&a.jsx(kn,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{mm.mutate(),G(!1)},onCancel:()=>G(!1)}),a.jsx(XO,{printerId:t.id,isOpen:Q,onClose:()=>V(!1)}),B&&a.jsx(aye,{printerName:t.name,errors:De?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:C}),Pe&&a.jsx(xVe,{isOpen:!!Pe,onClose:()=>Me(null),printerId:t.id,printerName:t.name,amsId:Pe.amsId,amsLabel:Pe.amsLabel,initialMode:Pe.mode,thresholds:s}),Ve&&a.jsx(wae,{isOpen:!!Ve,onClose:()=>tt(null),tagUid:Ve.tagUid,trayUuid:Ve.trayUuid,printerId:Ve.printerId,amsId:Ve.amsId,trayId:Ve.trayId}),ut&&a.jsx(Sae,{isOpen:!!ut,onClose:()=>xt(null),printerId:ut.printerId,amsId:ut.amsId,trayId:ut.trayId,trayInfo:ut.trayInfo}),wt&&a.jsx(_ae,{isOpen:!!wt,onClose:()=>Ht(null),printerId:t.id,slotInfo:wt,printerModel:p0(t.model)||void 0,onSuccess:()=>{M.invalidateQueries({queryKey:["slotPresets",t.id]}),M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ae&&a.jsx(eGe,{printer:t,onClose:()=>ee(!1)}),Xt&&Le&&a.jsx(JVe,{printer:t,firmwareInfo:Le,onClose:()=>Kt(!1)}),gs&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>ul(null)}),re!==null&&Re&&(()=>{const gt=we==="n3s"?85:65,ge=35,mt=gt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>xe(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:Re.top,left:Re.left},onClick:Je=>Je.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Qp,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:Ae,onChange:Je=>{const $t=Je.target.value;ve($t);const tn=b[$t];tn&&(Fe(tn[we==="n3s"?"n3s":"n3f"]),Se(we==="n3s"?tn.n3s_hours:tn.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(b).map(Je=>a.jsx("option",{value:Je,children:Je},Je))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:gt,value:Te,onChange:Je=>Fe(Math.min(gt,Math.max(45,Number(Je.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:ge,max:mt,value:Te,onChange:Je=>Fe(Math.min(gt,Math.max(45,Number(Je.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[gt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:Ee,onChange:Je=>Se(Math.min(24,Math.max(1,Number(Je.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:Ee,onChange:Je=>Se(Number(Je.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:je,onChange:Je=>qe(Je.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{re!==null&&Hc.mutate({amsId:re,temp:Te,duration:Ee,filament:Ae,rotateTray:je})},disabled:Hc.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:Hc.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function ZVe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Lt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState([]),[_,k]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{Qc.getInfo().then(C=>{v(C.is_docker),C.subnets.length>0&&(g(C.subnets),k(C.subnets[0]))}).catch(()=>{})},[]);const M=c.filter(C=>!n.includes(C.serial)),A=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(y){await Qc.startSubnetScan(_);const C=setInterval(async()=>{try{const F=await Qc.getScanStatus();N({scanned:F.scanned,total:F.total});const $=await Qc.getDiscoveredPrinters();d($),F.running||(clearInterval(C),l(!1),f(!0))}catch(F){console.error("Failed to get scan status:",F)}},500)}else{await Qc.startDiscovery(10);const C=setInterval(async()=>{try{const F=await Qc.getDiscoveredPrinters();d(F)}catch(F){console.error("Failed to get discovered printers:",F)}},1e3);setTimeout(async()=>{clearInterval(C);try{await Qc.stopDiscovery()}catch{}l(!1),f(!0);try{const F=await Qc.getDiscoveredPrinters();d(F)}catch(F){console.error("Failed to get final discovered printers:",F)}},1e4)}}catch(C){console.error("Failed to start discovery:",C),m(C instanceof Error?C.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},T=C=>{const F=C.serial.startsWith("unknown-")?"":C.serial;s({...i,name:C.name||"",serial_number:F,ip_address:C.ip_address,model:p0(C.model)}),d([])};return w.useEffect(()=>()=>{Qc.stopDiscovery().catch(()=>{}),Qc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const C=F=>{F.key==="Escape"&&t()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:C=>C.stopPropagation(),children:a.jsxs(Rt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[y&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:C=>k(C.target.value),disabled:o,children:b.map(C=>a.jsx("option",{value:C,children:C},C))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:C=>k(C.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Ie,{type:"button",variant:"secondary",onClick:A,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),y&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Sr,{className:"w-4 h-4"}),r(y?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),M.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:M.map(C=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>T(C),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:C.name||C.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[p0(C.model)||r("printers.discovery.unknown")," • ",C.ip_address,C.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},C.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&M.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:C=>{C.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:C=>s({...i,name:C.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:C=>s({...i,ip_address:C.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:C=>s({...i,serial_number:C.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:C=>s({...i,access_code:C.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:C=>s({...i,model:C.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:C=>s({...i,location:C.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:C=>s({...i,auto_archive:C.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Ie,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function JVe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Lt(),i=mn(),{showToast:s}=xn(),{hasPermission:o}=_r(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),{data:y,isLoading:v}=et({queryKey:["firmwarePrepare",t.id],queryFn:()=>yk.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),b=lt({mutationFn:()=>yk.startUpload(t.id),onSuccess:()=>{m(!0);const _=setInterval(async()=>{try{const k=await yk.getUploadStatus(t.id);d(k),(k.status==="complete"||k.status==="error")&&(clearInterval(_),f(null),m(!1),k.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const g=()=>{d(null),b.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(Dt,{className:"w-full max-w-md mx-4",children:a.jsxs(Rt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(va,{className:"w-5 h-5 text-orange-400"}):a.jsx(fr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):y&&!u&&!c?a.jsx("div",{className:"mb-4",children:y.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(si,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:y.errors.map((_,k)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(qa,{className:"w-4 h-4 flex-shrink-0"}),_]},k))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ie,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),y?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(Ie,{onClick:g,disabled:b.isPending,children:b.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function eGe({printer:t,onClose:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=lt({mutationFn:d=>pe.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:a.jsxs(Rt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Ie,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function tGe(t){const{data:e}=et({queryKey:["printerStatus",t],queryFn:()=>pe.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function nGe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=tGe(t.id),{data:s}=et({queryKey:["smartPlugStatus",e.id],queryFn:()=>pe.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(im,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function rGe(){const{t}=Lt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,y]=w.useState(()=>{const ce=localStorage.getItem("printerCardSize");return ce?parseInt(ce,10):2}),v=f===1?"compact":"expanded",[b,g]=w.useState(""),[_,k]=w.useState("all"),[P,N]=w.useState("all"),[M,A]=w.useState(0),T=mn(),{showToast:C}=xn(),{hasPermission:F}=_r(),[$,I]=w.useState(()=>{const ce=localStorage.getItem("openEmbeddedCameras");if(ce)try{const ze=JSON.parse(ce);return new Map(ze.map(Ne=>[Ne.id,Ne]))}catch{return new Map}return new Map});w.useEffect(()=>{const ce=Array.from($.values());ce.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ce)):localStorage.removeItem("openEmbeddedCameras")},[$]);const{data:X,isLoading:L}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:te}=et({queryKey:["settings"],queryFn:pe.getSettings}),ae=w.useMemo(()=>{if(te?.drying_presets)try{const ce=JSON.parse(te.drying_presets);if(typeof ce=="object"&&ce!==null&&Object.keys(ce).length>0)return{...eL,...ce}}catch{}return eL},[te?.drying_presets]);w.useEffect(()=>{te?.camera_view_mode==="window"&&$.size>0&&I(new Map)},[te?.camera_view_mode,$.size]);const{data:ee}=et({queryKey:["smart-plugs"],queryFn:pe.getSmartPlugs}),{data:me}=et({queryKey:["maintenanceOverview"],queryFn:pe.getMaintenanceOverview,staleTime:60*1e3}),{data:le}=et({queryKey:["spoolman-status"],queryFn:pe.getSpoolmanStatus,staleTime:60*1e3}),ue=le?.enabled&&le?.connected,{data:K}=et({queryKey:["spoolman-settings"],queryFn:pe.getSpoolmanSettings,enabled:!!ue,staleTime:60*1e3}),ne=K?.spoolman_sync_mode,{data:oe}=et({queryKey:["unlinked-spools"],queryFn:pe.getUnlinkedSpools,enabled:!!ue,staleTime:30*1e3}),be=oe&&oe.length>0,{data:_e}=et({queryKey:["linked-spools"],queryFn:pe.getLinkedSpools,enabled:!!ue,staleTime:30*1e3}),B=_e?.linked,{data:Y}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),enabled:F("inventory:view_assignments"),staleTime:30*1e3}),D=lt({mutationFn:({printerId:ce,amsId:ze,trayId:Ne})=>pe.unassignSpool(ce,ze,Ne),onSuccess:()=>{T.invalidateQueries({queryKey:["spool-assignments"]})}}),j=(ce,ze,Ne)=>Y?.find(Ge=>Ge.printer_id===ce&&Ge.ams_id===Number(ze)&&Ge.tray_id===Number(Ne)),z=me?.reduce((ce,ze)=>(ce[ze.printer_id]={due_count:ze.due_count,warning_count:ze.warning_count,total_print_hours:ze.total_print_hours},ce),{})||{},W=ee?.reduce((ce,ze)=>(ze.printer_id&&(ce[ze.printer_id]=ze),ce),{})||{},q=lt({mutationFn:pe.createPrinter,onSuccess:()=>{T.invalidateQueries({queryKey:["printers"]}),T.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:ce=>C(ce.message||t("printers.toast.failedToAdd"),"error")}),de=lt({mutationFn:ce=>pe.controlSmartPlug(ce,"on"),onSuccess:()=>{T.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[O,G]=w.useState(new Set),[Q,V]=w.useState(!1),[J,ie]=w.useState(null),[he,fe]=w.useState(!1),se=Q||O.size>0,U=w.useCallback(ce=>{G(ze=>{const Ne=new Set(ze);return Ne.has(ce)?Ne.delete(ce):Ne.add(ce),Ne})},[]),R=w.useCallback(()=>{G(new Set),V(!1)},[]);w.useEffect(()=>{const ce=ze=>{ze.key==="Escape"&&se&&R()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[se,R]);const re=w.useCallback(async ce=>{fe(!0);const Ne=Array.from(O).filter(Ve=>{const tt=T.getQueryData(["printerStatus",Ve]);if(!tt?.connected)return!1;switch(ce){case"stop":return tt.state==="RUNNING"||tt.state==="PAUSE";case"pause":return tt.state==="RUNNING";case"resume":return tt.state==="PAUSE";case"clearPlate":return(tt.state==="FINISH"||tt.state==="FAILED")&&!tt.plate_cleared;case"clearHMS":return tt.hms_errors&&Tu(tt.hms_errors).length>0;default:return!1}});if(Ne.length===0){C(t("printers.bulk.noneApplicable"),"error"),fe(!1),ie(null);return}const Ge={stop:pe.stopPrint,pause:pe.pausePrint,resume:pe.resumePrint,clearPlate:pe.clearPlate,clearHMS:pe.clearHMSErrors}[ce],$e=await Promise.allSettled(Ne.map(Ve=>Ge(Ve))),Pe=$e.filter(Ve=>Ve.status==="fulfilled").length,Me=$e.filter(Ve=>Ve.status==="rejected").length;Me===0?C(t("printers.bulk.success",{action:t(`printers.bulk.actions.${ce}`),count:Pe})):C(t("printers.bulk.partial",{succeeded:Pe,failed:Me}),"error"),Ne.forEach(Ve=>{T.invalidateQueries({queryKey:["printerStatus",Ve]})}),fe(!1),ie(null)},[O,T,C,t]),xe=w.useCallback(ce=>{ce==="stop"||ce==="pause"||ce==="clearPlate"?ie(ce):re(ce)},[re]),we=()=>{const ce=!r;i(ce),localStorage.setItem("hideDisconnectedPrinters",String(ce))},ye=ce=>{u(ce),localStorage.setItem("printerSortBy",ce)},Ae=()=>{const ce=!m;p(ce),localStorage.setItem("printerSortAsc",String(ce))},ve=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},Te=["S","M","L","XL"];w.useEffect(()=>T.getQueryCache().subscribe(ze=>{ze.type==="updated"&&Array.isArray(ze.query.queryKey)&&ze.query.queryKey[0]==="printerStatus"&&A(Ne=>Ne+1)}),[T]);const Fe=w.useMemo(()=>{if(!X)return[];let ce=X;if(b.trim()){const ze=b.trim().toLowerCase();ce=ce.filter(Ne=>Ne.name.toLowerCase().includes(ze)||(Ne.model||"").toLowerCase().includes(ze)||(Ne.location||"").toLowerCase().includes(ze)||(Ne.serial_number||"").toLowerCase().includes(ze))}return P!=="all"&&(ce=ce.filter(ze=>(ze.location||"")===P)),_!=="all"&&(ce=ce.filter(ze=>{const Ne=T.getQueryData(["printerStatus",ze.id]);if(!Ne?.connected)return _==="offline";const Ge=Ne.hms_errors?Tu(Ne.hms_errors):[];switch(_){case"printing":return Ne.state==="RUNNING";case"paused":return Ne.state==="PAUSE";case"finished":return Ne.state==="FINISH";case"error":return Ne.state==="FAILED"||Ge.length>0;case"idle":return Ne.state!=="RUNNING"&&Ne.state!=="PAUSE"&&Ne.state!=="FINISH"&&Ne.state!=="FAILED"&&Ge.length===0;case"offline":return!1;default:return!0}})),ce},[X,b,_,P,T,M]),Ee=w.useMemo(()=>X?[...new Set(X.map(ce=>ce.location||"").filter(Boolean))].sort():[],[X]),Se=w.useMemo(()=>{const ce=[...Fe];switch(d){case"name":ce.sort((ze,Ne)=>ze.name.localeCompare(Ne.name));break;case"model":ce.sort((ze,Ne)=>(ze.model||"").localeCompare(Ne.model||""));break;case"location":ce.sort((ze,Ne)=>{const Ge=ze.location||"",$e=Ne.location||"";return!Ge&&$e?1:Ge&&!$e?-1:Ge.localeCompare($e)||ze.name.localeCompare(Ne.name)});break;case"status":ce.sort((ze,Ne)=>{const Ge=T.getQueryData(["printerStatus",ze.id]),$e=T.getQueryData(["printerStatus",Ne.id]),Pe=Me=>Me?.connected?(Me.hms_errors?Tu(Me.hms_errors):[]).length>0?0:Me.state==="RUNNING"?1:2:3;return Pe(Ge)-Pe($e)});break}return m||ce.reverse(),ce},[Fe,d,m,T]),je=w.useCallback(()=>{G(new Set(Se.map(ce=>ce.id))),V(!0)},[Se]),qe=w.useCallback(ce=>{G(ze=>{const Ne=new Set(ze);return Se.forEach(Ge=>{const $e=T.getQueryData(["printerStatus",Ge.id]);if($e)switch(ce){case"printing":$e.connected&&$e.state==="RUNNING"&&Ne.add(Ge.id);break;case"paused":$e.connected&&$e.state==="PAUSE"&&Ne.add(Ge.id);break;case"finished":$e.connected&&$e.state==="FINISH"&&Ne.add(Ge.id);break;case"idle":$e.connected&&$e.state!=="RUNNING"&&$e.state!=="PAUSE"&&$e.state!=="FINISH"&&$e.state!=="FAILED"&&Ne.add(Ge.id);break;case"error":$e.connected&&($e.state==="FAILED"||$e.hms_errors&&Tu($e.hms_errors).length>0)&&Ne.add(Ge.id);break;case"offline":$e.connected||Ne.add(Ge.id);break}}),Ne}),V(!0)},[Se,T]),Re=w.useCallback(ce=>{G(ze=>{const Ne=new Set(ze);return Se.filter(Ge=>(Ge.location||"")===ce).forEach(Ge=>Ne.add(Ge.id)),Ne}),V(!0)},[Se]),Ye=w.useMemo(()=>{if(d!=="location")return null;const ce={};return Se.forEach(ze=>{const Ne=ze.location||"Ungrouped";ce[Ne]||(ce[Ne]=[]),ce[Ne].push(ze)}),ce},[d,Se]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(QVe,{printers:X}),X&&X.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:b,onChange:ce=>g(ce.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>g(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:ce=>ye(ce.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ae,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(Lf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(bx,{className:"w-4 h-4 text-bambu-gray"})})]}),X&&X.length>0&&a.jsxs("select",{value:_,onChange:ce=>k(ce.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),X&&X.length>0&&Ee.length>0&&a.jsxs("select",{value:P,onChange:ce=>N(ce.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Ee.map(ce=>a.jsx("option",{value:ce,children:ce},ce))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:Te.map((ce,ze)=>{const Ne=ze+1,Ge=f===Ne;return a.jsx("button",{onClick:()=>{y(Ne),localStorage.setItem("printerCardSize",String(Ne))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${ze===0?"rounded-l-lg":""} ${ze===Te.length-1?"rounded-r-lg":""} ${Ge?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(ce==="S"?"printers.cardSize.small":ce==="M"?"printers.cardSize.medium":ce==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:ce},ce)})}),a.jsx("button",{onClick:()=>{se?R():V(!0)},className:`p-1.5 rounded-lg transition-colors ${se?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!F("printers:control"),children:a.jsx(us,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:we,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(W).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(im,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),X?.filter(ce=>W[ce.id]).map(ce=>a.jsx(nGe,{printer:ce,plug:W[ce.id],onPowerOn:ze=>{c(ze),de.mutate(ze)},isPowering:l===W[ce.id]?.id},ce.id)),X?.filter(ce=>W[ce.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Ie,{onClick:()=>n(!0),disabled:!F("printers:create"),title:F("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ur,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),L?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):X?.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Ie,{onClick:()=>n(!0),disabled:!F("printers:create"),title:F("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ur,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Se.length===0&&(b.trim()||_!=="all"||P!=="all")?a.jsx(Dt,{children:a.jsx(Rt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Ye?a.jsx("div",{className:"space-y-6",children:Object.entries(Ye).map(([ce,ze])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),ce,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",ze.length,")"]}),se&&a.jsx("button",{onClick:()=>Re(ce==="Ungrouped"?"":ce),className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ve()}`,children:ze.map(Ne=>a.jsx(WW,{printer:Ne,hideIfDisconnected:r,maintenanceInfo:z[Ne.id],viewMode:v,cardSize:f,amsThresholds:te?{humidityGood:Number(te.ams_humidity_good)||40,humidityFair:Number(te.ams_humidity_fair)||60,tempGood:Number(te.ams_temp_good)||28,tempFair:Number(te.ams_temp_fair)||35}:void 0,spoolmanEnabled:ue,hasUnlinkedSpools:be,linkedSpools:B,spoolmanUrl:le?.url,spoolmanSyncMode:ne,onGetAssignment:j,onUnassignSpool:(Ge,$e,Pe)=>D.mutate({printerId:Ge,amsId:$e,trayId:Pe}),timeFormat:te?.time_format||"system",cameraViewMode:te?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ge,$e)=>I(Pe=>new Map(Pe).set(Ge,{id:Ge,name:$e})),checkPrinterFirmware:te?.check_printer_firmware!==!1,dryingPresets:ae,requirePlateClear:te?.require_plate_clear!==!1,selectionMode:se,isSelected:O.has(Ne.id),onToggleSelect:U},Ne.id))})]},ce))}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ve()}`,children:Se.map(ce=>a.jsx(WW,{printer:ce,hideIfDisconnected:r,maintenanceInfo:z[ce.id],viewMode:v,cardSize:f,spoolmanEnabled:ue,hasUnlinkedSpools:be,linkedSpools:B,spoolmanUrl:le?.url,spoolmanSyncMode:ne,onGetAssignment:j,onUnassignSpool:(ze,Ne,Ge)=>D.mutate({printerId:ze,amsId:Ne,trayId:Ge}),amsThresholds:te?{humidityGood:Number(te.ams_humidity_good)||40,humidityFair:Number(te.ams_humidity_fair)||60,tempGood:Number(te.ams_temp_good)||28,tempFair:Number(te.ams_temp_fair)||35}:void 0,timeFormat:te?.time_format||"system",cameraViewMode:te?.camera_view_mode||"window",onOpenEmbeddedCamera:(ze,Ne)=>I(Ge=>new Map(Ge).set(ze,{id:ze,name:Ne})),checkPrinterFirmware:te?.check_printer_firmware!==!1,dryingPresets:ae,requirePlateClear:te?.require_plate_clear!==!1,selectionMode:se,isSelected:O.has(ce.id),onToggleSelect:U},ce.id))}),e&&a.jsx(ZVe,{onClose:()=>n(!1),onAdd:ce=>q.mutate(ce),existingSerials:X?.map(ce=>ce.serial_number)||[]}),se&&X&&a.jsx(sye,{selectedIds:O,printers:X,onClose:R,onSelectAll:je,onSelectByLocation:Re,onSelectByState:qe,onAction:xe,actionPending:he}),J==="stop"&&a.jsx(kn,{title:t("printers.bulk.confirm.stopTitle",{count:O.size}),message:t("printers.bulk.confirm.stopMessage",{count:O.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:he,onConfirm:()=>re("stop"),onCancel:()=>ie(null)}),J==="pause"&&a.jsx(kn,{title:t("printers.bulk.confirm.pauseTitle",{count:O.size}),message:t("printers.bulk.confirm.pauseMessage",{count:O.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:he,onConfirm:()=>re("pause"),onCancel:()=>ie(null)}),J==="clearPlate"&&a.jsx(kn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:O.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:O.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:he,onConfirm:()=>re("clearPlate"),onCancel:()=>ie(null)}),Array.from($.values()).map((ce,ze)=>a.jsx(oje,{printerId:ce.id,printerName:ce.name,viewerIndex:ze,onClose:()=>I(Ne=>{const Ge=new Map(Ne);return Ge.delete(ce.id),Ge})},ce.id))]})}function aGe(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function pf(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:aGe()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const KW=768;function Eae(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<KW:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${KW-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function ez({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Lt(),{data:o}=et({queryKey:["settings"],queryFn:pe.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!0),[v,b]=w.useState(null),[g,_]=w.useState(!1),[k,P]=w.useState(null),[N,M]=w.useState(0),[A,T]=w.useState(!1),[C,F]=w.useState(null),[$,I]=w.useState(!1),[X,L]=w.useState(!1),te=w.useRef(null),ae=w.useRef(null),ee=10,me=160,le=240,ue=.35;w.useEffect(()=>{const fe=se=>{se.key==="Escape"&&i()};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[i]),w.useEffect(()=>{if(y(!0),c){const fe=(r||"").toLowerCase(),se=fe==="3mf"||fe==="stl",U=fe==="gcode"||fe==="3mf";p({has_model:se,has_gcode:U,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(se?"3d":U?"gcode":null),y(!1);return}if(!t){p(null),u(null),y(!1);return}pe.getArchiveCapabilities(t).then(fe=>{p(fe),fe.has_model?u("3d"):fe.has_gcode&&u("gcode"),y(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),y(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),P(null),M(0),c){const fe=(r||"").toLowerCase();if(!e||fe!=="3mf"){b(null),_(!1);return}pe.getLibraryFilePlates(e).then(se=>b(se)).catch(()=>b(null)).finally(()=>_(!1));return}if(!t){b(null),_(!1);return}pe.getArchivePlates(t).then(fe=>b(fe)).catch(()=>b(null)).finally(()=>_(!1))},[t,r,c,e]);const K=w.useMemo(()=>v?.plates??[],[v]),ne=(v?.is_multi_plate??!1)&&K.length>1,oe=A&&ne,be=k==null?null:K.find(fe=>fe.index===k)??null,_e=fe=>fe.object_count??fe.objects?.length??0,B=K.reduce((fe,se)=>fe+_e(se),0),Y=be?_e(be):B,D=be?s("modelViewer.plateNumber",{number:be.index}):s("modelViewer.allPlates"),j=K.length>0,z=w.useRef(null),W=w.useRef(null),[q,de]=w.useState(10),[O,G]=w.useState(3),Q=K.length>q,V=Math.max(1,Math.ceil(K.length/q)),J=Q?K.slice(N*q,(N+1)*q):K;w.useEffect(()=>{if(!oe){de(10),G(3);return}const fe=z.current,se=W.current;if(!fe||!se)return;let U=0;const R=()=>{const we=se.clientWidth,Ae=Math.floor(we/210),ve=Math.max(3,Math.min(5,Ae||3));G(ce=>ce===ve?ce:ve);const Te=window.getComputedStyle(fe),Fe=Number.parseFloat(Te.rowGap||"0"),Se=fe.querySelector("button")?.getBoundingClientRect().height??44,je=se.clientHeight,Re=Math.max(1,Math.floor((je+Fe)/(Se+Fe)))*ve,Ye=Math.max(1,Re-1);de(ce=>ce===Ye?ce:Ye)},re=()=>{U&&cancelAnimationFrame(U),U=requestAnimationFrame(R)};re();const xe=new ResizeObserver(re);return xe.observe(se),xe.observe(fe),()=>{U&&cancelAnimationFrame(U),xe.disconnect()}},[oe,K.length]),w.useEffect(()=>{if(!Q){M(0);return}M(fe=>Math.min(fe,V-1))},[K.length,Q,V]),w.useEffect(()=>{if(!Q||k==null)return;const fe=K.findIndex(U=>U.index===k);if(fe<0)return;const se=Math.floor(fe/q);M(U=>U===se?U:se)},[K,q,k,Q]),w.useEffect(()=>{if(!oe){F(null),L(!1);return}if(X)return;const fe=te.current,se=ae.current;if(!fe||!se)return;const U=fe.clientHeight;if(!U)return;const R=Math.max(le,U*ue),re=Math.max(me,U-ee-R),xe=Math.min(se.scrollHeight,re);F(Math.max(me,xe))},[oe,X,K.length,N,ee,me,le,ue]),w.useEffect(()=>{if(!$)return;const fe=U=>{const R=te.current;if(!R)return;const re=R.getBoundingClientRect(),xe=re.height;if(!xe)return;const we=Math.max(le,xe*ue),ye=Math.max(me,xe-ee-we),Ae=Math.min(ye,Math.max(me,U.clientY-re.top));F(Ae)},se=()=>{I(!1),L(!0)};return document.addEventListener("mousemove",fe),document.addEventListener("mouseup",se),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",se),document.body.style.cursor="",document.body.style.userSelect=""}},[$,ee,me,le,ue]);const ie=c?(r||"").toLowerCase()==="3mf":!0,he=async()=>{if(!ie)return;const fe=n||"model";try{if(c){const{token:se}=await pe.createLibrarySlicerToken(e),U=pe.getLibrarySlicerDownloadUrl(e,se,fe);pf(`${window.location.origin}${U}`,l)}else{const{token:se}=await pe.createArchiveSlicerToken(t),U=pe.getArchiveSlicerDownloadUrl(t,se,fe);pf(`${window.location.origin}${U}`,l)}}catch{if(c){const se=`${window.location.origin}${pe.getLibraryFileDownloadUrl(e)}`;pf(se,l)}else{const se=`${window.location.origin}${pe.getArchiveForSlicer(t,fe)}`;pf(se,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${A?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${A?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:fe=>fe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[D,": ",s("modelViewer.objectCount",{count:Y})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:he,disabled:!ie,children:[a.jsx(sa,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>T(fe=>!fe),title:A?"Exit fullscreen":"Enter fullscreen",children:A?a.jsx(hO,{className:"w-4 h-4"}):a.jsx(NP,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),m&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(si,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Xpe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?a.jsxs("div",{ref:te,className:`w-full h-full flex flex-col ${oe?"gap-0 min-h-0":"gap-3"}`,children:[ne&&a.jsxs("div",{ref:ae,style:oe&&C!=null?{height:C}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${oe?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(ea,{className:"w-4 h-4"}),s("modelViewer.plates"),g&&a.jsx(ct,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:oe?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:W,className:oe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:z,className:oe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:oe?{gridTemplateColumns:`repeat(${O}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>P(null),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"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:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ea,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:K.length})})]}),k==null&&a.jsx(Kr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),J.map(fe=>a.jsxs("button",{type:"button",onClick:()=>P(fe.index),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${k===fe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[fe.has_thumbnail&&fe.thumbnail_url?a.jsx("img",{src:fe.thumbnail_url,alt:`Plate ${fe.index}`,className:`${oe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ea,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:fe.name||s("modelViewer.plateNumber",{number:fe.index})}),a.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:fe.object_count??fe.objects?.length??0})})]}),k===fe.index&&a.jsx(Kr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},fe.index))]})}),(be||Q)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[be&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:be.index})}),be.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(be.print_time_seconds/60)})}),be.filament_used_grams!=null&&a.jsxs("span",{children:[be.filament_used_grams.toFixed(1)," g"]}),be.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:be.filaments.length})})]}),Q&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${be?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:N+1,total:V})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>M(fe=>Math.max(fe-1,0)),disabled:N===0,className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let se=Math.max(0,N-Math.floor(2.5));const U=Math.min(V,se+5);U-se<5&&(se=Math.max(0,U-5));const R=Array.from({length:U-se},(re,xe)=>se+xe);return a.jsxs(a.Fragment,{children:[se>0&&a.jsx("button",{type:"button",onClick:()=>M(0),className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),se>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(re=>a.jsx("button",{type:"button",onClick:()=>M(re),className:`px-2 py-1 rounded border text-xs ${N===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)),U<V-1&&a.jsx("span",{className:"px-1",children:"…"}),U<V&&a.jsx("button",{type:"button",onClick:()=>M(V-1),className:`px-2 py-1 rounded border text-xs ${N===V-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:V})]})})(),a.jsx("button",{type:"button",onClick:()=>M(fe=>Math.min(fe+1,V-1)),disabled:N>=V-1,className:`px-2 py-1 rounded border text-xs ${N>=V-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")})]})]})]})]})]}),oe&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:fe=>{fe.preventDefault(),I(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${$?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${oe?"min-h-0":""}`,children:a.jsx(wZ,{url:c?pe.getLibraryFileDownloadUrl(e):m.has_source?pe.getSource3mfDownloadUrl(t):pe.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:k,className:"w-full h-full"})})]}):d==="gcode"&&m?a.jsx(rJ,{gcodeUrl:c?pe.getLibraryFileGcodeUrl(e):pe.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function iGe({onClose:t,initialFiles:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=lt({mutationFn:N=>pe.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(M=>M.map(A=>{const T=N.results.find(F=>F.filename===A.file.name),C=N.errors.find(F=>F.filename===A.file.name);return T?{...A,status:"success",archiveId:T.id}:C?{...A,status:"error",error:C.error}:A})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(M=>({...M,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),y=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const M=Array.from(N.dataTransfer.files).filter(A=>A.name.endsWith(".3mf"));M.length>0&&l(A=>[...A,...M.map(T=>({file:T,status:"pending"}))])},[]),b=w.useCallback(N=>{const M=Array.from(N.target.files||[]).filter(A=>A.name.endsWith(".3mf"));M.length>0&&l(A=>[...A,...M.map(T=>({file:T,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(N=>{l(M=>M.filter((A,T)=>T!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(M=>M.status==="pending");N.length!==0&&(l(M=>M.map(A=>A.status==="pending"?{...A,status:"uploading"}:A)),p.mutate(N.map(M=>M.file)))},k=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:y,onDrop:v,children:[a.jsx(Ca,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Ie,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,M)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(_P,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>g(M),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Bt,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(fr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(qa,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${M}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(Ie,{onClick:_,disabled:k===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ca,{className:"w-4 h-4"}),n("uploadModal.upload")," ",k>0&&`(${k})`]})})]})]})})})}const sGe=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],oGe=["completed","failed","aborted","printing"];function Dae({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Lt();w.useEffect(()=>{const j=z=>{z.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=mn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,y]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[k,P]=w.useState(t.quantity??1),[N,M]=w.useState(t.photos||[]),[A,T]=w.useState(t.external_url||""),[C,F]=w.useState(!1),[$,I]=w.useState(!1),X=w.useRef(null),L=w.useRef(null),te=w.useRef(null),{data:ae}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:ee}=et({queryKey:["projects"],queryFn:()=>pe.getProjects()}),{data:me}=et({queryKey:["tags"],queryFn:pe.getTags,enabled:n.length===0}),le=n.length>0?n:me?.map(j=>j.name)||[],ue=f.split(",").map(j=>j.trim()).filter(Boolean),K=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=le.filter(j=>!ue.includes(j)&&(K===""||j.toLowerCase().includes(K))),oe=j=>{let z;if(K&&!le.includes(K)?z=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(W=>W.trim()).filter(Boolean):[]:z=ue,!z.includes(j)){const W=[...z,j].join(", ");y(W)}te.current!==null&&clearTimeout(te.current),X.current?.focus()},be=j=>{const z=ue.filter(W=>W!==j).join(", ");y(z)},_e=lt({mutationFn:j=>pe.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),B=async j=>{const z=j.target.files?.[0];if(z){F(!0);try{const W=await pe.uploadArchivePhoto(t.id,z);M(W.photos),i.invalidateQueries({queryKey:["archives"]})}catch(W){console.error("Failed to upload photo:",W)}finally{F(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const z=await pe.deleteArchivePhoto(t.id,j);M(z.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(z){console.error("Failed to delete photo:",z)}},D=j=>{j.preventDefault();const z={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};g!==t.status&&(z.status=g),g==="failed"||g==="aborted"?z.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(z.failure_reason=null),_e.mutate(z)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:D,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ae?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(js,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),ee?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(sge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:k,onChange:j=>P(Math.max(1,parseInt(j.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(ny,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:A,onChange:j=>T(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),ue.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ue.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(Gu,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>be(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:X,type:"text",value:f,onChange:j=>y(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),I(!0)},onBlur:()=>{te.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:ue.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),$&&ne.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[K?r("editArchive.matchingTags",{query:K}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(j=>a.jsx("button",{type:"button",onClick:()=>oe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:g,onChange:j=>{_(j.target.value),j.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:oGe.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(g==="failed"||g==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),sGe.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(yx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:pe.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(un,{className:"w-3 h-3 text-white"})})]},j)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:B,className:"hidden",disabled:C}),C?a.jsx(ct,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(ur,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ie,{type:"submit",disabled:_e.isPending,className:"flex-1",children:[a.jsx(cs,{className:"w-4 h-4"}),_e.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Fae({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=k=>{i.current&&!i.current.contains(k.target)&&r()},g=k=>{k.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,k=8;let P=t,N=e;t+b.width>g-k&&(P=Math.max(k,g-b.width-k)),P<k&&(P=k),e+b.height>_-k&&(N=Math.max(k,_-b.height-k)),N<k&&(N=k);const M=180,A=g-P-b.width,T=P;m(A<M&&T>M),d({x:P,y:N,visible:!0})}},[t,e]);const y=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),k=window.innerHeight,P=300,A=k-_.top-8<P&&_.top>P;f(T=>({...T,[b]:A?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((b,g)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:k=>_&&y(g,k.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:k=>_&&y(g,k.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},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===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),_&&a.jsx(Va,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((k,P)=>a.jsxs("button",{onClick:()=>{k.disabled||(k.onClick(),r())},disabled:k.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${k.disabled?"text-bambu-gray cursor-not-allowed":k.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[k.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:k.icon}),k.label]},P))})]},g)})})}function lGe({selectedIds:t,existingTags:e,onClose:n}){const r=mn(),{showToast:i}=xn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=lt({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await pe.getArchive(g),k=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...k,...v])]:P=k.filter(N=>!l.has(N)),await pe.updateArchive(g,{tags:P.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},y=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-md",children:a.jsxs(Rt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(Ie,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:y}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(ur,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Bt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ie,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Ie,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Gu,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function cGe({selectedIds:t,onClose:e}){const n=mn(),{showToast:r}=xn(),{data:i,isLoading:s}=et({queryKey:["projects"],queryFn:()=>pe.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=lt({mutationFn:async u=>(await pe.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=lt({mutationFn:async()=>{for(const u of t)await pe.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(js,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx($a,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(js,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function dGe(t,e){return new Date(t,e+1,0).getDate()}function uGe(t,e){return new Date(t,e,1).getDay()}const mGe=["January","February","March","April","May","June","July","August","September","October","November","December"],hGe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function pGe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(M=>{const A=Qn(M.completed_at||M.created_at)||new Date,T=`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`,C=N.get(T)||[];C.push(M),N.set(T,C)}),N},[t]),f=dGe(o,i),y=uGe(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N<y;N++)_.push(null);for(let N=1;N<=f;N++)_.push(N);const k=c?p.get(c)||[]:[],P=N=>{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ol,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[mGe[i]," ",o]}),a.jsx("button",{onClick:g,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Va,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:hGe.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,M)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${M}`);const A=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,T=p.get(A)||[],C=T.length>0,F=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),$=A===c,I=T.filter(L=>L.status==="completed").length,X=T.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P($?null:A),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${$?"bg-bambu-green text-white":F?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":C?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${F&&!$?"text-bambu-green":""}`,children:N}),C&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${X>0&&I===0?"bg-red-400":X>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:T.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const M=Qn(N.completed_at||N.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const M=Qn(N.completed_at||N.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const M=Qn(N.completed_at||N.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),k.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:k.map(N=>{const M=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${M?"":"hover:bg-bambu-dark-tertiary"}`,style:M?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:pe.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((A,T)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:A}},T))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Rae({archiveId:t,archiveName:e,onClose:n}){const r=pe.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Ie,{onClick:i,className:"w-full",children:[a.jsx(va,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Lae({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=y=>{y.key==="Escape"&&r(),y.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),y.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=pe.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(va,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Ie,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ol,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),s<n.length-1&&a.jsx("button",{onClick:()=>o(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Va,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,y)=>a.jsx("button",{onClick:()=>o(y),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${y===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:pe.getArchivePhotoUrl(t,f),alt:`Thumbnail ${y+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(kn,{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:Oae,setPrototypeOf:YW,isFrozen:fGe,getPrototypeOf:gGe,getOwnPropertyDescriptor:bGe}=Object;let{freeze:ro,seal:nc,create:Lk}=Object,{apply:tL,construct:nL}=typeof Reflect<"u"&&Reflect;ro||(ro=function(e){return e});nc||(nc=function(e){return e});tL||(tL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];return e.apply(n,i)});nL||(nL=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});const Y1=ao(Array.prototype.forEach),xGe=ao(Array.prototype.lastIndexOf),XW=ao(Array.prototype.pop),Fv=ao(Array.prototype.push),yGe=ao(Array.prototype.splice),Ok=ao(String.prototype.toLowerCase),SD=ao(String.prototype.toString),_D=ao(String.prototype.match),Rv=ao(String.prototype.replace),vGe=ao(String.prototype.indexOf),wGe=ao(String.prototype.trim),Xo=ao(Object.prototype.hasOwnProperty),$s=ao(RegExp.prototype.test),Lv=SGe(TypeError);function ao(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return tL(t,e,r)}}function SGe(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return nL(t,n)}}function or(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ok;YW&&YW(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(fGe(e)||(e[r]=s),i=s)}t[i]=!0}return t}function _Ge(t){for(let e=0;e<t.length;e++)Xo(t,e)||(t[e]=null);return t}function ad(t){const e=Lk(null);for(const[n,r]of Oae(t))Xo(t,n)&&(Array.isArray(r)?e[n]=_Ge(r):r&&typeof r=="object"&&r.constructor===Object?e[n]=ad(r):e[n]=r);return e}function Ov(t,e){for(;t!==null;){const r=bGe(t,e);if(r){if(r.get)return ao(r.get);if(typeof r.value=="function")return ao(r.value)}t=gGe(t)}function n(){return null}return n}const QW=ro(["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"]),kD=ro(["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"]),ND=ro(["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"]),kGe=ro(["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"]),CD=ro(["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"]),NGe=ro(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ZW=ro(["#text"]),JW=ro(["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"]),PD=ro(["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"]),eK=ro(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),X1=ro(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),CGe=nc(/\{\{[\w\W]*|[\w\W]*\}\}/gm),PGe=nc(/<%[\w\W]*|[\w\W]*%>/gm),TGe=nc(/\$\{[\w\W]*/gm),AGe=nc(/^data-[\-\w.\u00B7-\uFFFF]+$/),MGe=nc(/^aria-[\-\w]+$/),Iae=nc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),jGe=nc(/^(?:\w+script|data):/i),EGe=nc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zae=nc(/^html$/i),DGe=nc(/^[a-z][.\w]*(-[.\w]+)+$/i);var tK=Object.freeze({__proto__:null,ARIA_ATTR:MGe,ATTR_WHITESPACE:EGe,CUSTOM_ELEMENT:DGe,DATA_ATTR:AGe,DOCTYPE_NAME:zae,ERB_EXPR:PGe,IS_ALLOWED_URI:Iae,IS_SCRIPT_OR_DATA:jGe,MUSTACHE_EXPR:CGe,TMPLIT_EXPR:TGe});const Iv={element:1,text:3,progressingInstruction:7,comment:8,document:9},FGe=function(){return typeof window>"u"?null:window},RGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},nK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Uae(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:FGe();const e=De=>Uae(De);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Iv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,y=c.prototype,v=Ov(y,"cloneNode"),b=Ov(y,"remove"),g=Ov(y,"nextSibling"),_=Ov(y,"childNodes"),k=Ov(y,"parentNode");if(typeof o=="function"){const De=n.createElement("template");De.content&&De.content.ownerDocument&&(n=De.content.ownerDocument)}let P,N="";const{implementation:M,createNodeIterator:A,createDocumentFragment:T,getElementsByTagName:C}=n,{importNode:F}=r;let $=nK();e.isSupported=typeof Oae=="function"&&typeof k=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:X,TMPLIT_EXPR:L,DATA_ATTR:te,ARIA_ATTR:ae,IS_SCRIPT_OR_DATA:ee,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:le}=tK;let{IS_ALLOWED_URI:ue}=tK,K=null;const ne=or({},[...QW,...kD,...ND,...CD,...ZW]);let oe=null;const be=or({},[...JW,...PD,...eK,...X1]);let _e=Object.seal(Lk(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}})),B=null,Y=null;const D=Object.seal(Lk(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,z=!0,W=!1,q=!0,de=!1,O=!0,G=!1,Q=!1,V=!1,J=!1,ie=!1,he=!1,fe=!0,se=!1;const U="user-content-";let R=!0,re=!1,xe={},we=null;const ye=or({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ae=null;const ve=or({},["audio","video","img","source","image","track"]);let Te=null;const Fe=or({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Se="http://www.w3.org/2000/svg",je="http://www.w3.org/1999/xhtml";let qe=je,Re=!1,Ye=null;const ce=or({},[Ee,Se,je],SD);let ze=or({},["mi","mo","mn","ms","mtext"]),Ne=or({},["annotation-xml"]);const Ge=or({},["title","style","font","a","script"]);let $e=null;const Pe=["application/xhtml+xml","text/html"],Me="text/html";let Ve=null,tt=null;const ut=n.createElement("form"),xt=function(Le){return Le instanceof RegExp||Le instanceof Function},wt=function(){let Le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(tt&&tt===Le)){if((!Le||typeof Le!="object")&&(Le={}),Le=ad(Le),$e=Pe.indexOf(Le.PARSER_MEDIA_TYPE)===-1?Me:Le.PARSER_MEDIA_TYPE,Ve=$e==="application/xhtml+xml"?SD:Ok,K=Xo(Le,"ALLOWED_TAGS")?or({},Le.ALLOWED_TAGS,Ve):ne,oe=Xo(Le,"ALLOWED_ATTR")?or({},Le.ALLOWED_ATTR,Ve):be,Ye=Xo(Le,"ALLOWED_NAMESPACES")?or({},Le.ALLOWED_NAMESPACES,SD):ce,Te=Xo(Le,"ADD_URI_SAFE_ATTR")?or(ad(Fe),Le.ADD_URI_SAFE_ATTR,Ve):Fe,Ae=Xo(Le,"ADD_DATA_URI_TAGS")?or(ad(ve),Le.ADD_DATA_URI_TAGS,Ve):ve,we=Xo(Le,"FORBID_CONTENTS")?or({},Le.FORBID_CONTENTS,Ve):ye,B=Xo(Le,"FORBID_TAGS")?or({},Le.FORBID_TAGS,Ve):ad({}),Y=Xo(Le,"FORBID_ATTR")?or({},Le.FORBID_ATTR,Ve):ad({}),xe=Xo(Le,"USE_PROFILES")?Le.USE_PROFILES:!1,j=Le.ALLOW_ARIA_ATTR!==!1,z=Le.ALLOW_DATA_ATTR!==!1,W=Le.ALLOW_UNKNOWN_PROTOCOLS||!1,q=Le.ALLOW_SELF_CLOSE_IN_ATTR!==!1,de=Le.SAFE_FOR_TEMPLATES||!1,O=Le.SAFE_FOR_XML!==!1,G=Le.WHOLE_DOCUMENT||!1,J=Le.RETURN_DOM||!1,ie=Le.RETURN_DOM_FRAGMENT||!1,he=Le.RETURN_TRUSTED_TYPE||!1,V=Le.FORCE_BODY||!1,fe=Le.SANITIZE_DOM!==!1,se=Le.SANITIZE_NAMED_PROPS||!1,R=Le.KEEP_CONTENT!==!1,re=Le.IN_PLACE||!1,ue=Le.ALLOWED_URI_REGEXP||Iae,qe=Le.NAMESPACE||je,ze=Le.MATHML_TEXT_INTEGRATION_POINTS||ze,Ne=Le.HTML_INTEGRATION_POINTS||Ne,_e=Le.CUSTOM_ELEMENT_HANDLING||{},Le.CUSTOM_ELEMENT_HANDLING&&xt(Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&xt(Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&typeof Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(_e.allowCustomizedBuiltInElements=Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),de&&(z=!1),ie&&(J=!0),xe&&(K=or({},ZW),oe=Lk(null),xe.html===!0&&(or(K,QW),or(oe,JW)),xe.svg===!0&&(or(K,kD),or(oe,PD),or(oe,X1)),xe.svgFilters===!0&&(or(K,ND),or(oe,PD),or(oe,X1)),xe.mathMl===!0&&(or(K,CD),or(oe,eK),or(oe,X1))),Xo(Le,"ADD_TAGS")||(D.tagCheck=null),Xo(Le,"ADD_ATTR")||(D.attributeCheck=null),Le.ADD_TAGS&&(typeof Le.ADD_TAGS=="function"?D.tagCheck=Le.ADD_TAGS:(K===ne&&(K=ad(K)),or(K,Le.ADD_TAGS,Ve))),Le.ADD_ATTR&&(typeof Le.ADD_ATTR=="function"?D.attributeCheck=Le.ADD_ATTR:(oe===be&&(oe=ad(oe)),or(oe,Le.ADD_ATTR,Ve))),Le.ADD_URI_SAFE_ATTR&&or(Te,Le.ADD_URI_SAFE_ATTR,Ve),Le.FORBID_CONTENTS&&(we===ye&&(we=ad(we)),or(we,Le.FORBID_CONTENTS,Ve)),Le.ADD_FORBID_CONTENTS&&(we===ye&&(we=ad(we)),or(we,Le.ADD_FORBID_CONTENTS,Ve)),R&&(K["#text"]=!0),G&&or(K,["html","head","body"]),K.table&&(or(K,["tbody"]),delete B.tbody),Le.TRUSTED_TYPES_POLICY){if(typeof Le.TRUSTED_TYPES_POLICY.createHTML!="function")throw Lv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Le.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Lv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Le.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=RGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));ro&&ro(Le),tt=Le}},Ht=or({},[...kD,...ND,...kGe]),Xt=or({},[...CD,...NGe]),Kt=function(Le){let at=k(Le);(!at||!at.tagName)&&(at={namespaceURI:qe,tagName:"template"});const Ce=Ok(Le.tagName),We=Ok(at.tagName);return Ye[Le.namespaceURI]?Le.namespaceURI===Se?at.namespaceURI===je?Ce==="svg":at.namespaceURI===Ee?Ce==="svg"&&(We==="annotation-xml"||ze[We]):!!Ht[Ce]:Le.namespaceURI===Ee?at.namespaceURI===je?Ce==="math":at.namespaceURI===Se?Ce==="math"&&Ne[We]:!!Xt[Ce]:Le.namespaceURI===je?at.namespaceURI===Se&&!Ne[We]||at.namespaceURI===Ee&&!ze[We]?!1:!Xt[Ce]&&(Ge[Ce]||!Ht[Ce]):!!($e==="application/xhtml+xml"&&Ye[Le.namespaceURI]):!1},Ut=function(Le){Fv(e.removed,{element:Le});try{k(Le).removeChild(Le)}catch{b(Le)}},en=function(Le,at){try{Fv(e.removed,{attribute:at.getAttributeNode(Le),from:at})}catch{Fv(e.removed,{attribute:null,from:at})}if(at.removeAttribute(Le),Le==="is")if(J||ie)try{Ut(at)}catch{}else try{at.setAttribute(Le,"")}catch{}},Ke=function(Le){let at=null,Ce=null;if(V)Le="<remove></remove>"+Le;else{const Qe=_D(Le,/^[\r\n\t ]+/);Ce=Qe&&Qe[0]}$e==="application/xhtml+xml"&&qe===je&&(Le='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Le+"</body></html>");const We=P?P.createHTML(Le):Le;if(qe===je)try{at=new p().parseFromString(We,$e)}catch{}if(!at||!at.documentElement){at=M.createDocument(qe,"template",null);try{at.documentElement.innerHTML=Re?N:We}catch{}}const Xe=at.body||at.documentElement;return Le&&Ce&&Xe.insertBefore(n.createTextNode(Ce),Xe.childNodes[0]||null),qe===je?C.call(at,G?"html":"body")[0]:G?at.documentElement:Xe},Ft=function(Le){return A.call(Le.ownerDocument||Le,Le,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Nt=function(Le){return Le instanceof m&&(typeof Le.nodeName!="string"||typeof Le.textContent!="string"||typeof Le.removeChild!="function"||!(Le.attributes instanceof u)||typeof Le.removeAttribute!="function"||typeof Le.setAttribute!="function"||typeof Le.namespaceURI!="string"||typeof Le.insertBefore!="function"||typeof Le.hasChildNodes!="function")},ht=function(Le){return typeof l=="function"&&Le instanceof l};function Mt(De,Le,at){Y1(De,Ce=>{Ce.call(e,Le,at,tt)})}const Qt=function(Le){let at=null;if(Mt($.beforeSanitizeElements,Le,null),Nt(Le))return Ut(Le),!0;const Ce=Ve(Le.nodeName);if(Mt($.uponSanitizeElement,Le,{tagName:Ce,allowedTags:K}),O&&Le.hasChildNodes()&&!ht(Le.firstElementChild)&&$s(/<[/\w!]/g,Le.innerHTML)&&$s(/<[/\w!]/g,Le.textContent)||Le.nodeType===Iv.progressingInstruction||O&&Le.nodeType===Iv.comment&&$s(/<[/\w]/g,Le.data))return Ut(Le),!0;if(!(D.tagCheck instanceof Function&&D.tagCheck(Ce))&&(!K[Ce]||B[Ce])){if(!B[Ce]&&Ue(Ce)&&(_e.tagNameCheck instanceof RegExp&&$s(_e.tagNameCheck,Ce)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ce)))return!1;if(R&&!we[Ce]){const We=k(Le)||Le.parentNode,Xe=_(Le)||Le.childNodes;if(Xe&&We){const Qe=Xe.length;for(let Ze=Qe-1;Ze>=0;--Ze){const rt=v(Xe[Ze],!0);rt.__removalCount=(Le.__removalCount||0)+1,We.insertBefore(rt,g(Le))}}}return Ut(Le),!0}return Le instanceof c&&!Kt(Le)||(Ce==="noscript"||Ce==="noembed"||Ce==="noframes")&&$s(/<\/no(script|embed|frames)/i,Le.innerHTML)?(Ut(Le),!0):(de&&Le.nodeType===Iv.text&&(at=Le.textContent,Y1([I,X,L],We=>{at=Rv(at,We," ")}),Le.textContent!==at&&(Fv(e.removed,{element:Le.cloneNode()}),Le.textContent=at)),Mt($.afterSanitizeElements,Le,null),!1)},Wt=function(Le,at,Ce){if(Y[at]||fe&&(at==="id"||at==="name")&&(Ce in n||Ce in ut))return!1;if(!(z&&!Y[at]&&$s(te,at))){if(!(j&&$s(ae,at))){if(!(D.attributeCheck instanceof Function&&D.attributeCheck(at,Le))){if(!oe[at]||Y[at]){if(!(Ue(Le)&&(_e.tagNameCheck instanceof RegExp&&$s(_e.tagNameCheck,Le)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Le))&&(_e.attributeNameCheck instanceof RegExp&&$s(_e.attributeNameCheck,at)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(at,Le))||at==="is"&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&$s(_e.tagNameCheck,Ce)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(Ce))))return!1}else if(!Te[at]){if(!$s(ue,Rv(Ce,me,""))){if(!((at==="src"||at==="xlink:href"||at==="href")&&Le!=="script"&&vGe(Ce,"data:")===0&&Ae[Le])){if(!(W&&!$s(ee,Rv(Ce,me,"")))){if(Ce)return!1}}}}}}}return!0},Ue=function(Le){return Le!=="annotation-xml"&&_D(Le,le)},dt=function(Le){Mt($.beforeSanitizeAttributes,Le,null);const{attributes:at}=Le;if(!at||Nt(Le))return;const Ce={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:oe,forceKeepAttr:void 0};let We=at.length;for(;We--;){const Xe=at[We],{name:Qe,namespaceURI:Ze,value:rt}=Xe,bt=Ve(Qe),Pt=rt;let vt=Qe==="value"?Pt:wGe(Pt);if(Ce.attrName=bt,Ce.attrValue=vt,Ce.keepAttr=!0,Ce.forceKeepAttr=void 0,Mt($.uponSanitizeAttribute,Le,Ce),vt=Ce.attrValue,se&&(bt==="id"||bt==="name")&&(en(Qe,Le),vt=U+vt),O&&$s(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,vt)){en(Qe,Le);continue}if(bt==="attributename"&&_D(vt,"href")){en(Qe,Le);continue}if(Ce.forceKeepAttr)continue;if(!Ce.keepAttr){en(Qe,Le);continue}if(!q&&$s(/\/>/i,vt)){en(Qe,Le);continue}de&&Y1([I,X,L],St=>{vt=Rv(vt,St," ")});const He=Ve(Le.nodeName);if(!Wt(He,bt,vt)){en(Qe,Le);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ze)switch(f.getAttributeType(He,bt)){case"TrustedHTML":{vt=P.createHTML(vt);break}case"TrustedScriptURL":{vt=P.createScriptURL(vt);break}}if(vt!==Pt)try{Ze?Le.setAttributeNS(Ze,Qe,vt):Le.setAttribute(Qe,vt),Nt(Le)?Ut(Le):XW(e.removed)}catch{en(Qe,Le)}}Mt($.afterSanitizeAttributes,Le,null)},pt=function De(Le){let at=null;const Ce=Ft(Le);for(Mt($.beforeSanitizeShadowDOM,Le,null);at=Ce.nextNode();)Mt($.uponSanitizeShadowNode,at,null),Qt(at),dt(at),at.content instanceof s&&De(at.content);Mt($.afterSanitizeShadowDOM,Le,null)};return e.sanitize=function(De){let Le=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},at=null,Ce=null,We=null,Xe=null;if(Re=!De,Re&&(De="<!-->"),typeof De!="string"&&!ht(De))if(typeof De.toString=="function"){if(De=De.toString(),typeof De!="string")throw Lv("dirty is not a string, aborting")}else throw Lv("toString is not a function");if(!e.isSupported)return De;if(Q||wt(Le),e.removed=[],typeof De=="string"&&(re=!1),re){if(De.nodeName){const rt=Ve(De.nodeName);if(!K[rt]||B[rt])throw Lv("root node is forbidden and cannot be sanitized in-place")}}else if(De instanceof l)at=Ke("<!---->"),Ce=at.ownerDocument.importNode(De,!0),Ce.nodeType===Iv.element&&Ce.nodeName==="BODY"||Ce.nodeName==="HTML"?at=Ce:at.appendChild(Ce);else{if(!J&&!de&&!G&&De.indexOf("<")===-1)return P&&he?P.createHTML(De):De;if(at=Ke(De),!at)return J?null:he?N:""}at&&V&&Ut(at.firstChild);const Qe=Ft(re?De:at);for(;We=Qe.nextNode();)Qt(We),dt(We),We.content instanceof s&&pt(We.content);if(re)return De;if(J){if(ie)for(Xe=T.call(at.ownerDocument);at.firstChild;)Xe.appendChild(at.firstChild);else Xe=at;return(oe.shadowroot||oe.shadowrootmode)&&(Xe=F.call(r,Xe,!0)),Xe}let Ze=G?at.outerHTML:at.innerHTML;return G&&K["!doctype"]&&at.ownerDocument&&at.ownerDocument.doctype&&at.ownerDocument.doctype.name&&$s(zae,at.ownerDocument.doctype.name)&&(Ze="<!DOCTYPE "+at.ownerDocument.doctype.name+`>
  8188. `+Ze),de&&Y1([I,X,L],rt=>{Ze=Rv(Ze,rt," ")}),P&&he?P.createHTML(Ze):Ze},e.setConfig=function(){let De=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wt(De),Q=!0},e.clearConfig=function(){tt=null,Q=!1},e.isValidAttribute=function(De,Le,at){tt||wt({});const Ce=Ve(De),We=Ve(Le);return Wt(Ce,We,at)},e.addHook=function(De,Le){typeof Le=="function"&&Fv($[De],Le)},e.removeHook=function(De,Le){if(Le!==void 0){const at=xGe($[De],Le);return at===-1?void 0:yGe($[De],at,1)[0]}return XW($[De])},e.removeHooks=function(De){$[De]=[]},e.removeAllHooks=function(){$=nK()},e}var Bae=Uae();function es(t){this.content=t}es.prototype={constructor:es,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return e==-1?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,i=r.find(t),s=r.content.slice();return i==-1?s.push(n||t,e):(s[i+1]=e,n&&(s[i]=n)),new es(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 es(n)},addToStart:function(t,e){return new es([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new es(n)},addBefore:function(t,e,n){var r=this.remove(e),i=r.content.slice(),s=r.find(t);return i.splice(s==-1?i.length:s,0,e,n),new es(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=es.from(t),t.size?new es(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=es.from(t),t.size?new es(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=es.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}};es.from=function(t){if(t instanceof es)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new es(e)};function Hae(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=Hae(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function qae(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;d<u&&o.text[o.text.length-d-1]==l.text[l.text.length-d-1];)d++,n--,r--;return{a:n,b:r}}if(o.content.size||l.content.size){let d=qae(o.content,l.content,n-1,r-1);if(d)return d}n-=c,r-=c}}class qt{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,n,r,i=0,s){for(let o=0,l=0;l<n;o++){let c=this.content[o],d=l+c.nodeSize;if(d>e&&r(c,i+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)i.push(e.content[s]);return new qt(i,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let r=[],i=0;if(n>e)for(let s=0,o=0;o<n;s++){let l=this.content[s],c=o+l.nodeSize;c>e&&((o<e||c>n)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new qt(r,i)}cutByIndex(e,n){return e==n?qt.empty:e==0&&n==this.content.length?this:new qt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new qt(i,s)}addToStart(e){return new qt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new qt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(e.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let n=this.content[e];if(!n)throw new RangeError("Index "+e+" out of range for "+this);return n}maybeChild(e){return this.content[e]||null}forEach(e){for(let n=0,r=0;n<this.content.length;n++){let i=this.content[n];e(i,r,n),r+=i.nodeSize}}findDiffStart(e,n=0){return Hae(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return qae(this,e,n,r)}findIndex(e){if(e==0)return Q1(0,e);if(e==this.size)return Q1(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?Q1(n+1,s):Q1(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return qt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new qt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return qt.empty;let n,r=0;for(let i=0;i<e.length;i++){let s=e[i];r+=s.nodeSize,i&&s.isText&&e[i-1].sameMarkup(s)?(n||(n=e.slice(0,i)),n[n.length-1]=s.withText(n[n.length-1].text+s.text)):n&&n.push(s)}return new qt(n||e,r)}static from(e){if(!e)return qt.empty;if(e instanceof qt)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new qt([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}qt.empty=new qt([],0);const TD={index:0,offset:0};function Q1(t,e){return TD.index=t,TD.offset=e,TD}function SC(t,e){if(t===e)return!0;if(!(t&&typeof t=="object")||!(e&&typeof e=="object"))return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!SC(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!SC(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let Zr=class rL{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,r=!1;for(let i=0;i<e.length;i++){let s=e[i];if(this.eq(s))return e;if(this.type.excludes(s.type))n||(n=e.slice(0,i));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return e.slice(0,n).concat(e.slice(n+1));return e}isInSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return!0;return!1}eq(e){return this==e||this.type==e.type&&SC(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);let i=r.create(n.attrs);return r.checkAttrs(i.attrs),i}static sameSet(e,n){if(e==n)return!0;if(e.length!=n.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(n[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return rL.none;if(e instanceof rL)return[e];let n=e.slice();return n.sort((r,i)=>r.type.rank-i.type.rank),n}};Zr.none=[];class _C extends Error{}class ln{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Vae(this.content,e+this.openStart,n);return r&&new ln(r,this.openStart,this.openEnd)}removeBetween(e,n){return new ln($ae(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 ln.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ln(qt.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new ln(e,r,i)}}ln.empty=new ln(qt.empty,0,0);function $ae(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy($ae(s.content,e-i-1,n-i-1)))}function Vae(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=Vae(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function LGe(t,e,n){if(n.openStart>t.depth)throw new _C("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new _C("Inconsistent open depths");return Gae(t,e,n,0)}function Gae(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r<t.depth-n.openStart){let o=Gae(t,e,n,r+1);return s.copy(s.content.replaceChild(i,o))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&t.depth==r&&e.depth==r){let o=t.parent,l=o.content;return Af(o,l.cut(0,t.parentOffset).append(n.content).append(l.cut(e.parentOffset)))}else{let{start:o,end:l}=OGe(n,t);return Af(s,Kae(t,o,l,e,r))}else return Af(s,kC(t,e,r))}function Wae(t,e){if(!e.type.compatibleContent(t.type))throw new _C("Cannot join "+e.type.name+" onto "+t.type.name)}function aL(t,e,n){let r=t.node(n);return Wae(r,e.node(n)),r}function Tf(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 f0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Tf(t.nodeAfter,r),s++));for(let l=s;l<o;l++)Tf(i.child(l),r);e&&e.depth==n&&e.textOffset&&Tf(e.nodeBefore,r)}function Af(t,e){return t.type.checkContent(e),t.copy(e)}function Kae(t,e,n,r,i){let s=t.depth>i&&aL(t,e,i+1),o=r.depth>i&&aL(n,r,i+1),l=[];return f0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Wae(s,o),Tf(Af(s,Kae(t,e,n,r,i+1)),l)):(s&&Tf(Af(s,kC(t,e,i+1)),l),f0(e,n,i,l),o&&Tf(Af(o,kC(n,r,i+1)),l)),f0(r,null,i,l),new qt(l)}function kC(t,e,n){let r=[];if(f0(null,t,n,r),t.depth>n){let i=aL(t,e,n+1);Tf(Af(i,kC(t,e,n+1)),r)}return f0(e,null,n,r),new qt(r)}function OGe(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(qt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class dw{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)i+=r.child(s).nodeSize;return i}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return Zr.none;if(this.textOffset)return e.child(n).marks;let r=e.maybeChild(n-1),i=e.maybeChild(n);if(!r){let l=r;r=i,i=l}let s=r.marks;for(var o=0;o<s.length;o++)s[o].type.spec.inclusive===!1&&(!i||!s[o].isInSet(i.marks))&&(s=s[o--].removeFromSet(s));return s}marksAcross(e){let n=this.parent.maybeChild(this.index());if(!n||!n.isInline)return null;let r=n.marks,i=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!i||!r[s].isInSet(i.marks))&&(r=r[s--].removeFromSet(r));return r}sharedDepth(e){for(let n=this.depth;n>0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new NC(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let n=1;n<=this.depth;n++)e+=(e?"/":"")+this.node(n).type.name+"_"+this.index(n-1);return e+":"+this.parentOffset}static resolve(e,n){if(!(n>=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new dw(n,r,s)}static resolveCached(e,n){let r=rK.get(e);if(r)for(let s=0;s<r.elts.length;s++){let o=r.elts[s];if(o.pos==n)return o}else rK.set(e,r=new IGe);let i=r.elts[r.i]=dw.resolve(e,n);return r.i=(r.i+1)%zGe,i}}class IGe{constructor(){this.elts=[],this.i=0}}const zGe=12,rK=new WeakMap;class NC{constructor(e,n,r){this.$from=e,this.$to=n,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const UGe=Object.create(null);class Ec{constructor(e,n,r,i=Zr.none){this.type=e,this.attrs=n,this.marks=i,this.content=r||qt.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,n,r,i=0){this.content.nodesBetween(e,n,r,i,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,n,r,i){return this.content.textBetween(e,n,r,i)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,n,r){return this.type==e&&SC(this.attrs,n||e.defaultAttrs||UGe)&&Zr.sameSet(this.marks,r||Zr.none)}copy(e=null){return e==this.content?this:new Ec(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new Ec(this.type,this.attrs,this.content,e)}cut(e,n=this.content.size){return e==0&&n==this.content.size?this:this.copy(this.content.cut(e,n))}slice(e,n=this.content.size,r=!1){if(e==n)return ln.empty;let i=this.resolve(e),s=this.resolve(n),o=r?0:i.sharedDepth(n),l=i.start(o),d=i.node(o).content.cut(i.pos-l,s.pos-l);return new ln(d,i.depth-o,s.depth-o)}replace(e,n,r){return LGe(this.resolve(e),this.resolve(n),r)}nodeAt(e){for(let n=this;;){let{index:r,offset:i}=n.content.findIndex(e);if(n=n.maybeChild(r),!n)return null;if(i==e||n.isText)return n;e-=i+1}}childAfter(e){let{index:n,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(n),index:n,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:n,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(n),index:n,offset:r};let i=this.content.child(n-1);return{node:i,index:n-1,offset:r-i.nodeSize}}resolve(e){return dw.resolveCached(this,e)}resolveNoCache(e){return dw.resolve(this,e)}rangeHasMark(e,n,r){let i=!1;return n>e&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Yae(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=qt.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;c<s;c++)if(!this.type.allowsMarks(r.child(c).marks))return!1;return!0}canReplaceWith(e,n,r,i){if(i&&!this.type.allowsMarks(i))return!1;let s=this.contentMatchAt(e).matchType(r),o=s&&s.matchFragment(this.content,n);return o?o.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=Zr.none;for(let n=0;n<this.marks.length;n++){let r=this.marks[n];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!Zr.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(n=>n.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=qt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}}Ec.prototype.text=void 0;class CC extends Ec{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Yae(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 CC(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new CC(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 Yae(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class ng{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new BGe(e,n);if(r.next==null)return ng.empty;let i=Xae(r);r.next&&r.err("Unexpected trailing text");let s=KGe(WGe(i));return YGe(s,r),s}matchType(e){for(let n=0;n<this.next.length;n++)if(this.next[n].type==e)return this.next[n].next;return null}matchFragment(e,n=0,r=e.childCount){let i=this;for(let s=n;i&&s<r;s++)i=i.matchType(e.child(s).type);return i}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:n}=this.next[e];if(!(n.isText||n.hasRequiredAttrs()))return n}return null}compatible(e){for(let n=0;n<this.next.length;n++)for(let r=0;r<e.next.length;r++)if(this.next[n].type==e.next[r].type)return!0;return!1}fillBefore(e,n=!1,r=0){let i=[this];function s(o,l){let c=o.matchFragment(e,r);if(c&&(!n||c.validEnd))return qt.from(l.map(d=>d.createAndFill()));for(let d=0;d<o.next.length;d++){let{type:u,next:m}=o.next[d];if(!(u.isText||u.hasRequiredAttrs())&&i.indexOf(m)==-1){i.push(m);let p=s(m,l.concat(u));if(p)return p}}return null}return s(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let n=this.computeWrapping(e);return this.wrapCache.push(e,n),n}computeWrapping(e){let n=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let i=r.shift(),s=i.match;if(s.matchType(e)){let o=[];for(let l=i;l.type;l=l.via)o.push(l.type);return o.reverse()}for(let o=0;o<s.next.length;o++){let{type:l,next:c}=s.next[o];!l.isLeaf&&!l.hasRequiredAttrs()&&!(l.name in n)&&(!i.type||c.validEnd)&&(r.push({match:l.contentMatch,type:l,via:i}),n[l.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i<r.next.length;i++)e.indexOf(r.next[i].next)==-1&&n(r.next[i].next)}return n(this),e.map((r,i)=>{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o<r.next.length;o++)s+=(o?", ":"")+r.next[o].type.name+"->"+e.indexOf(r.next[o].next);return s}).join(`
  8189. `)}}ng.empty=new ng(!0);class BGe{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 Xae(t){let e=[];do e.push(HGe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function HGe(t){let e=[];do e.push(qGe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function qGe(t){let e=GGe(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=$Ge(t,e);else break;return e}function aK(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function $Ge(t,e){let n=aK(t),r=n;return t.eat(",")&&(t.next!="}"?r=aK(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function VGe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function GGe(t){if(t.eat("(")){let e=Xae(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=VGe(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 WGe(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;i(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d<o.min;d++){let u=n();i(s(o.expr,c),u),c=u}if(o.max==-1)i(s(o.expr,c),c);else for(let d=o.min;d<o.max;d++){let u=n();r(c,u),i(s(o.expr,c),u),c=u}return[r(c)]}else{if(o.type=="name")return[r(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function Qae(t,e){return e-t}function iK(t,e){let n=[];return r(e),n.sort(Qae);function r(i){let s=t[i];if(s.length==1&&!s[0].term)return r(s[0].to);n.push(i);for(let o=0;o<s.length;o++){let{term:l,to:c}=s[o];!l&&n.indexOf(c)==-1&&r(c)}}}function KGe(t){let e=Object.create(null);return n(iK(t,0));function n(r){let i=[];r.forEach(o=>{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u<i.length;u++)i[u][0]==l&&(d=i[u][1]);iK(t,c).forEach(u=>{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[r.join(",")]=new ng(r.indexOf(t.length-1)>-1);for(let o=0;o<i.length;o++){let l=i[o][1].sort(Qae);s.next.push({type:i[o][0],next:e[l.join(",")]||n(l)})}return s}}function YGe(t,e){for(let n=0,r=[t];n<r.length;n++){let i=r[n],s=!i.validEnd,o=[];for(let l=0;l<i.next.length;l++){let{type:c,next:d}=i.next[l];o.push(c.name),s&&!(c.isText||c.hasRequiredAttrs())&&(s=!1),r.indexOf(d)==-1&&r.push(d)}s&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function Zae(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function Jae(t,e){let n=Object.create(null);for(let r in t){let i=e&&e[r];if(i===void 0){let s=t[r];if(s.hasDefault)i=s.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=i}return n}function eie(t,e,n,r){for(let i in e)if(!(i in t))throw new RangeError(`Unsupported attribute ${i} for ${n} of type ${i}`);for(let i in t){let s=t[i];s.validate&&s.validate(e[i])}}function tie(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new QGe(t,r,e[r]);return n}let sK=class nie{constructor(e,n,r){this.name=e,this.schema=n,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=tie(e,r.attrs),this.defaultAttrs=Zae(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==ng.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:Jae(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Ec(this,this.computeAttrs(e),qt.from(n),Zr.setFrom(r))}createChecked(e=null,n,r){return n=qt.from(n),this.checkContent(n),new Ec(this,this.computeAttrs(e),n,Zr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=qt.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(qt.empty,!0);return s?new Ec(this,e,n.append(s),Zr.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){eie(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;n<e.length;n++)if(!this.allowsMarkType(e[n].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let n;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?n&&n.push(e[r]):n||(n=e.slice(0,r));return n?n.length?n:Zr.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,o)=>r[s]=new nie(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function XGe(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class QGe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?XGe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class RT{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=tie(e,i.attrs),this.excluded=null;let s=Zae(this.attrs);this.instance=s?new Zr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Zr(this,Jae(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new RT(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n<e.length;n++)e[n].type==this&&(e=e.slice(0,n).concat(e.slice(n+1)),n--);return e}isInSet(e){for(let n=0;n<e.length;n++)if(e[n].type==this)return e[n]}checkAttrs(e){eie(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class rie{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=es.from(e.nodes),n.marks=es.from(e.marks||{}),this.nodes=sK.compile(this.spec.nodes,this),this.marks=RT.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=ng.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?oK(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==""?[]:oK(this,o.split(" "))}this.nodeFromJSON=i=>Ec.fromJSON(this,i),this.markFromJSON=i=>Zr.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof sK){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new CC(r,r.defaultAttrs,e,Zr.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 oK(t,e){let n=[];for(let r=0;r<e.length;r++){let i=e[r],s=t.marks[i],o=s;if(s)n.push(s);else for(let l in t.marks){let c=t.marks[l];(i=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(i)>-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function ZGe(t){return t.tag!=null}function JGe(t){return t.style!=null}let g0=class iL{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(ZGe(i))this.tags.push(i);else if(JGe(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new cK(this,n,!1);return r.addAll(e,Zr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new cK(this,n,!0);return r.addAll(e,Zr.none,n.from,n.to),ln.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;i<this.tags.length;i++){let s=this.tags[i];if(n7e(e,s.tag)&&(s.namespace===void 0||e.namespaceURI==s.namespace)&&(!s.context||n.matchesContext(s.context))){if(s.getAttrs){let o=s.getAttrs(e);if(o===!1)continue;s.attrs=o||void 0}return s}}}matchStyle(e,n,r,i){for(let s=i?this.styles.indexOf(i)+1:0;s<this.styles.length;s++){let o=this.styles[s],l=o.style;if(!(l.indexOf(e)!=0||o.context&&!r.matchesContext(o.context)||l.length>e.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o<n.length;o++){let l=n[o];if((l.priority==null?50:l.priority)<s)break}n.splice(o,0,i)}for(let i in e.marks){let s=e.marks[i].spec.parseDOM;s&&s.forEach(o=>{r(o=dK(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=dK(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new iL(e,iL.schemaRules(e)))}};const aie={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},e7e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},iie={ol:!0,ul:!0},uw=1,sL=2,b0=4;function lK(t,e,n){return e!=null?(e?uw:0)|(e==="full"?sL:0):t&&t.whitespace=="pre"?uw|sL:n&~b0}class Z1{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=Zr.none,this.match=s||(o&b0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(qt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&uw)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=qt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(qt.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&&!aie.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class cK{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=lK(null,n.preserveWhitespace,0)|(r?b0:0);i?s=new Z1(i.type,i.attrs,Zr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new Z1(null,null,Zr.none,!0,null,o):s=new Z1(e.schema.topNodeType,null,Zr.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,s=i.options&sL?"full":this.localPreserveWS||(i.options&uw)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
  8190. `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c<l.length;c++)c&&this.insertNode(o.linebreakReplacement.create(),n,!0),l[c]&&this.insertNode(o.text(l[c]),n,!/\S/.test(l[c]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let l=i.content[i.content.length-1],c=e.previousSibling;(!l||c&&c.nodeName=="BR"||l.isText&&/[ \t\r\n\u000c]$/.test(l.text))&&(r=r.slice(1))}r&&this.insertNode(o.text(r),n,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,n,r){let i=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let o=e.nodeName.toLowerCase(),l;iie.hasOwnProperty(o)&&this.parser.normalizeLists&&t7e(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(l=this.parser.matchTag(e,this,r));e:if(c?c.ignore:e7e.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(aie.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(`
  8191. `),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let i=0;i<this.parser.matchedStyles.length;i++){let s=this.parser.matchedStyles[i],o=r.getPropertyValue(s);if(o)for(let l=void 0;;){let c=this.parser.matchStyle(s,o,this,l);if(!c)break;if(c.ignore)return null;if(c.clearMark?n=n.filter(d=>!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,i){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],d=c.findWrapping(e);if(d&&(!i||i.length>d.length+l)&&(i=d,s=c,!d.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o<i.length;o++)n=this.enterInner(i[o],null,n,!1);return n}insertNode(e,n,r){if(e.isInline&&this.needsBlock&&!this.top.type){let s=this.textblockFromContext();s&&(n=this.enterInner(s,null,n))}let i=this.findPlace(e,n,r);if(i){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let o=Zr.none;for(let l of i.concat(e.marks))(s.type?s.type.allowsMarkType(l.type):uK(l.type,e.type))&&(o=l.addToSet(o));return s.content.push(e.mark(o)),!0}return!1}enter(e,n,r,i){let s=this.findPlace(e.create(n),r,!1);return s&&(s=this.enterInner(e,n,r,!0,i)),s}enterInner(e,n,r,i=!1,s){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(e);let l=lK(e,s,o.options);o.options&b0&&o.content.length==0&&(l|=b0);let c=Zr.none;return r=r.filter(d=>(o.type?o.type.allowsMarkType(d.type):uK(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Z1(e,n,c,i,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=uw)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&e.nodeType==1&&e.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(e,n,r){if(e!=n&&this.find)for(let i=0;i<this.find.length;i++)this.find[i].pos==null&&e.nodeType==1&&e.contains(this.find[i].node)&&n.compareDocumentPosition(this.find[i].node)&(r?2:4)&&(this.find[i].pos=this.currentPos)}findInText(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&(this.find[n].pos=this.currentPos-(e.nodeValue.length-this.find[n].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let d=n[l];if(d==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let u=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function t7e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&iie.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function n7e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function dK(t){let e={};for(let n in t)e[n]=t[n];return e}function uK(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c<l.edgeCount;c++){let{type:d,next:u}=l.edge(c);if(d==e||s.indexOf(u)<0&&o(u))return!0}};if(o(i.contentMatch))return!0}}class pg{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=AD(n).createDocumentFragment());let i=r,s=[];return e.forEach(o=>{if(s.length||o.marks.length){let l=0,c=0;for(;l<s.length&&c<o.marks.length;){let d=o.marks[c];if(!this.marks[d.type.name]){c++;continue}if(!d.eq(s[l][0])||d.type.spec.spanning===!1)break;l++,c++}for(;l<s.length;)i=s.pop()[1];for(;c<o.marks.length;){let d=o.marks[c++],u=this.serializeMark(d,o.isInline,n);u&&(s.push([d,i]),i.appendChild(u.dom),i=u.contentDOM||u.dom)}}i.appendChild(this.serializeNodeInner(o,n))}),r}serializeNodeInner(e,n){let{dom:r,contentDOM:i}=Ik(AD(n),this.nodes[e.type.name](e),null,e.attrs);if(i){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,i)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let i=e.marks.length-1;i>=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&Ik(AD(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return Ik(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new pg(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=mK(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return mK(e.marks)}}function mK(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function AD(t){return t.document||window.document}const hK=new WeakMap;function r7e(t){let e=hK.get(t);return e===void 0&&hK.set(t,e=a7e(t)),e}function a7e(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i<r.length;i++)n(r[i]);else for(let i in r)n(r[i])}return n(t),e}function Ik(t,e,n,r){if(typeof e=="string")return{dom:t.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let i=e[0],s;if(typeof i!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(s=r7e(r))&&s.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),d=e[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let m in d)if(d[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=u;m<e.length;m++){let p=e[m];if(p===0){if(m<e.length-1||m>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:y}=Ik(t,p,n,r);if(c.appendChild(f),y){if(l)throw new RangeError("Multiple content holes");l=y}}}return{dom:c,contentDOM:l}}const sie=65535,oie=Math.pow(2,16);function i7e(t,e){return t+e*oie}function pK(t){return t&sie}function s7e(t){return(t-(t&sie))/oie}const lie=1,cie=2,zk=4,die=8;class oL{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&die)>0}get deletedBefore(){return(this.delInfo&(lie|zk))>0}get deletedAfter(){return(this.delInfo&(cie|zk))>0}get deletedAcross(){return(this.delInfo&zk)>0}}class el{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&el.empty)return el.empty}recover(e){let n=0,r=pK(e);if(!this.inverted)for(let i=0;i<r;i++)n+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[r*3]+n+s7e(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,r){let i=0,s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?i:0);if(c>e)break;let d=this.ranges[l+s],u=this.ranges[l+o],m=c+d;if(e<=m){let p=d?e==c?-1:e==m?1:n:n,f=c+i+(p<0?0:u);if(r)return f;let y=e==(n<0?c:m)?null:i7e(l/3,e-c),v=e==c?cie:e==m?lie:zk;return(n<0?e!=c:e!=m)&&(v|=die),new oL(f,v,y)}i+=u-d}return r?e+i:new oL(e+i,0,null)}touches(e,n){let r=0,i=pK(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?r:0);if(c>e)break;let d=this.ranges[l+s],u=c+d;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-d}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i<this.ranges.length;i+=3){let o=this.ranges[i],l=o-(this.inverted?s:0),c=o+(this.inverted?0:s),d=this.ranges[i+n],u=this.ranges[i+r];e(l,l+d,c,c+u),s+=u-d}}invert(){return new el(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?el.empty:new el(e<0?[0,-e,0]:[0,0,e])}}el.empty=new el([]);class mw{constructor(e,n,r=0,i=e?e.length:0){this.mirror=n,this.from=r,this.to=i,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new mw(this._maps,this.mirror,e,n)}appendMap(e,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(e){for(let n=0,r=this._maps.length;n<e._maps.length;n++){let i=e.getMirror(n);this.appendMap(e._maps[n],i!=null&&i<n?r+i:void 0)}}getMirror(e){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==e)return this.mirror[n+(n%2?-1:1)]}}setMirror(e,n){this.mirror||(this.mirror=[]),this.mirror.push(e,n)}appendMappingInverted(e){for(let n=e.maps.length-1,r=this._maps.length+e._maps.length;n>=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new mw;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,r){let i=0;for(let s=this.from;s<this.to;s++){let o=this._maps[s],l=o.mapResult(e,n);if(l.recover!=null){let c=this.getMirror(s);if(c!=null&&c>s&&c<this.to){s=c,e=this._maps[c].recover(l.recover);continue}}i|=l.delInfo,e=l.pos}return r?e:new oL(e,i,null)}}const MD=Object.create(null);class Os{getMap(){return el.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=MD[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in MD)throw new RangeError("Duplicate use of step JSON ID "+e);return MD[e]=n,n.prototype.jsonID=e,n}}class li{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new li(e,null)}static fail(e){return new li(null,e)}static fromReplace(e,n,r,i){try{return li.ok(e.replace(n,r,i))}catch(s){if(s instanceof _C)return li.fail(s.message);throw s}}}function tz(t,e,n){let r=[];for(let i=0;i<t.childCount;i++){let s=t.child(i);s.content.size&&(s=s.copy(tz(s.content,e,s))),s.isInline&&(s=e(s,n,i)),r.push(s)}return qt.fromArray(r)}class Nh extends Os{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=e.resolve(this.from),i=r.node(r.sharedDepth(this.to)),s=new ln(tz(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 li.fromReplace(e,this.from,this.to,s)}invert(){return new Mc(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Nh(n.pos,r.pos,this.mark)}merge(e){return e instanceof Nh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Nh(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Nh(n.from,n.to,e.markFromJSON(n.mark))}}Os.jsonID("addMark",Nh);class Mc extends Os{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new ln(tz(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return li.fromReplace(e,this.from,this.to,r)}invert(){return new Nh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Mc(n.pos,r.pos,this.mark)}merge(e){return e instanceof Mc&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Mc(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 Mc(n.from,n.to,e.markFromJSON(n.mark))}}Os.jsonID("removeMark",Mc);class Ch extends Os{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return li.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return li.fromReplace(e,this.pos,this.pos+1,new ln(qt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;i<n.marks.length;i++)if(!n.marks[i].isInSet(r))return new Ch(this.pos,n.marks[i]);return new Ch(this.pos,this.mark)}}return new rg(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Ch(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Ch(n.pos,e.markFromJSON(n.mark))}}Os.jsonID("addNodeMark",Ch);class rg extends Os{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return li.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return li.fromReplace(e,this.pos,this.pos+1,new ln(qt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Ch(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new rg(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 rg(n.pos,e.markFromJSON(n.mark))}}Os.jsonID("removeNodeMark",rg);class Ri extends Os{constructor(e,n,r,i=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=i}apply(e){return this.structure&&lL(e,this.from,this.to)?li.fail("Structure replace would overwrite content"):li.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new el([this.from,this.to-this.from,this.slice.size])}invert(e){return new Ri(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new Ri(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Ri)||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?ln.empty:new ln(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Ri(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?ln.empty:new ln(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Ri(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 Ri(n.from,n.to,ln.fromJSON(e,n.slice),!!n.structure)}}Os.jsonID("replace",Ri);class Oi extends Os{constructor(e,n,r,i,s,o,l=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=i,this.slice=s,this.insert=o,this.structure=l}apply(e){if(this.structure&&(lL(e,this.from,this.gapFrom)||lL(e,this.gapTo,this.to)))return li.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return li.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?li.fromReplace(e,this.from,this.to,r):li.fail("Content does not fit in gap")}getMap(){return new el([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 Oi(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),i=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||i<n.pos||s>r.pos?null:new Oi(n.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Oi(n.from,n.to,n.gapFrom,n.gapTo,ln.fromJSON(e,n.slice),n.insert,!!n.structure)}}Os.jsonID("replaceAround",Oi);function lL(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function o7e(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let m=c.marks;if(!r.isInSet(m)&&u.type.allowsMarkType(r.type)){let p=Math.max(d,e),f=Math.min(d+c.nodeSize,n),y=r.addToSet(m);for(let v=0;v<m.length;v++)m[v].isInSet(y)||(o&&o.to==p&&o.mark.eq(m[v])?o.to=f:i.push(o=new Mc(p,f,m[v])));l&&l.to==p?l.to=f:s.push(l=new Nh(p,f,r))}}),i.forEach(c=>t.step(c)),s.forEach(c=>t.step(c))}function l7e(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof RT){let d=o.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let d=Math.min(l+o.nodeSize,n);for(let u=0;u<c.length;u++){let m=c[u],p;for(let f=0;f<i.length;f++){let y=i[f];y.step==s-1&&m.eq(i[f].style)&&(p=y)}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 Mc(o.from,o.to,o.style)))}function nz(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c<s.childCount;c++){let d=s.child(c),u=l+d.nodeSize,m=r.matchType(d.type);if(!m)o.push(new Ri(l,u,ln.empty));else{r=m;for(let p=0;p<d.marks.length;p++)n.allowsMarkType(d.marks[p].type)||t.step(new Mc(l,u,d.marks[p]));if(i&&d.isText&&n.whitespace!="pre"){let p,f=/\r?\n|\r/g,y;for(;p=f.exec(d.text);)y||(y=new ln(qt.from(n.schema.text(" ",n.allowedMarks(d.marks))),0,0)),o.push(new Ri(l+p.index,l+p.index+p[0].length,y))}}l=u}if(!r.validEnd){let c=r.fillBefore(qt.empty,!0);t.replace(l,l,new ln(c,0,0))}for(let c=o.length-1;c>=0;c--)t.step(o[c])}function c7e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function yy(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(r<t.depth&&o.canReplace(l,c,n))return r;if(r==0||o.type.spec.isolating||!c7e(o,l,c))break;l&&(i=1),c<o.childCount&&(s=1)}return null}function d7e(t,e,n){let{$from:r,$to:i,depth:s}=e,o=r.before(s+1),l=i.after(s+1),c=o,d=l,u=qt.empty,m=0;for(let y=s,v=!1;y>n;y--)v||r.index(y)>0?(v=!0,u=qt.from(r.node(y).copy(u)),m++):c--;let p=qt.empty,f=0;for(let y=s,v=!1;y>n;y--)v||i.after(y+1)<i.end(y)?(v=!0,p=qt.from(i.node(y).copy(p)),f++):d++;t.step(new Oi(c,d,o,l,new ln(u.append(p),m,f),u.size-m,!0))}function rz(t,e,n=null,r=t){let i=u7e(t,e),s=i&&m7e(r,e);return s?i.map(fK).concat({type:e,attrs:n}).concat(s.map(fK)):null}function fK(t){return{type:t,attrs:null}}function u7e(t,e){let{parent:n,startIndex:r,endIndex:i}=t,s=n.contentMatchAt(r).findWrapping(e);if(!s)return null;let o=s.length?s[0]:e;return n.canReplaceWith(r,i,o)?s:null}function m7e(t,e){let{parent:n,startIndex:r,endIndex:i}=t,s=n.child(r),o=e.contentMatch.findWrapping(s.type);if(!o)return null;let c=(o.length?o[o.length-1]:e).contentMatch;for(let d=r;c&&d<i;d++)c=c.matchType(n.child(d).type);return!c||!c.validEnd?null:o}function h7e(t,e,n){let r=qt.empty;for(let o=n.length-1;o>=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=qt.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new Oi(i,s,i,s,new ln(r,0,0),n.length,!0))}function p7e(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&f7e(t.doc,t.mapping.slice(s).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",y=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!y?d=!1:!f&&y&&(d=!0)}d===!1&&mie(t,o,l,s),nz(t,t.mapping.slice(s).map(l,1),r,void 0,d===null);let u=t.mapping.slice(s),m=u.map(l,1),p=u.map(l+o.nodeSize,1);return t.step(new Oi(m,p,m+1,p-1,new ln(qt.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&uie(t,o,l,s),!1}})}function uie(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function mie(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(`
  8192. `))}})}function f7e(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function g7e(t,e,n,r,i){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let o=n.create(r,null,i||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,o);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new Oi(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new ln(qt.from(o),0,0),1,!0))}function Hu(t,e,n=1,r){let i=t.resolve(e),s=i.depth-n,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let d=i.depth-1,u=n-2;d>s;d--,u--){let m=i.node(d),p=i.index(d);if(m.type.spec.isolating)return!1;let f=m.content.cutByIndex(p,m.childCount),y=r&&r[u+1];y&&(f=f.replaceChild(0,y.type.create(y.attrs)));let v=r&&r[u]||m;if(!m.canReplace(p+1,m.childCount)||!v.type.validContent(f))return!1}let l=i.indexAfter(s),c=r&&r[0];return i.node(s).canReplaceWith(l,l,c?c.type:i.node(s+1).type)}function b7e(t,e,n=1,r){let i=t.doc.resolve(e),s=qt.empty,o=qt.empty;for(let l=i.depth,c=i.depth-n,d=n-1;l>c;l--,d--){s=qt.from(i.node(l).copy(s));let u=r&&r[d];o=qt.from(u?u.type.create(u.attrs,o):i.node(l).copy(o))}t.step(new Ri(e,e,new ln(s.append(o),n,n),!0))}function op(t,e){let n=t.resolve(e),r=n.index();return hie(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function x7e(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i<e.childCount;i++){let s=e.child(i),o=s.type==r?t.type.schema.nodes.text:s.type;if(n=n.matchType(o),!n||!t.type.allowsMarks(s.marks))return!1}return n.validEnd}function hie(t,e){return!!(t&&e&&!t.isLeaf&&x7e(t,e))}function LT(t,e,n=-1){let r=t.resolve(e);for(let i=r.depth;;i--){let s,o,l=r.index(i);if(i==r.depth?(s=r.nodeBefore,o=r.nodeAfter):n>0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&hie(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=n<0?r.before(i):r.after(i)}}function y7e(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(i&&o.inlineContent){let u=o.whitespace=="pre",m=!!o.contentMatch.matchType(i);u&&!m?r=!1:!u&&m&&(r=!0)}let l=t.steps.length;if(r===!1){let u=t.doc.resolve(e+n);mie(t,u.node(),u.before(),l)}o.inlineContent&&nz(t,e+n-1,o,s.node().contentMatchAt(s.index()),r==null);let c=t.mapping.slice(l),d=c.map(e-n);if(t.step(new Ri(d,c.map(e+n,-1),ln.empty,!0)),r===!0){let u=t.doc.resolve(d);uie(t,u.node(),u.before(),t.steps.length)}return t}function v7e(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,n))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,n))return r.after(i+1);if(s<r.node(i).childCount)return null}return null}function pie(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let i=n.content;for(let s=0;s<n.openStart;s++)i=i.firstChild.content;for(let s=1;s<=(n.openStart==0&&n.size?2:1);s++)for(let o=r.depth;o>=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,c=r.index(o)+(l>0?1:0),d=r.node(o),u=!1;if(s==1)u=d.canReplace(c,c,i);else{let m=d.contentMatchAt(c).findWrapping(i.firstChild.type);u=m&&d.canReplaceWith(c,c,m[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function OT(t,e,n=e,r=ln.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),s=t.resolve(n);return fie(i,s,r)?new Ri(e,n,r):new w7e(i,s,r).fit()}function fie(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class w7e{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=qt.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=qt.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new ln(s,o,l);return e>-1?new Oi(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ri(r.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r<e;r++){let s=n.firstChild;if(n.childCount>1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=jD(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:d}=this.frontier[l],u,m=null;if(n==1&&(o?d.matchType(o.type)||(m=d.fillBefore(qt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:m};if(n==2&&o&&(u=d.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:u};if(s&&d.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=jD(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new ln(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=jD(e,n);if(i.childCount<=1&&n>0){let s=e.size-n<=n+i.size;this.unplaced=new ln(Qv(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new ln(Qv(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let v=0;v<s.length;v++)this.openFrontierNode(s[v]);let o=this.unplaced,l=r?r.content:o.content,c=o.openStart-e,d=0,u=[],{match:m,type:p}=this.frontier[n];if(i){for(let v=0;v<i.childCount;v++)u.push(i.child(v));m=m.matchFragment(i)}let f=l.size+e-(o.content.size-o.openEnd);for(;d<l.childCount;){let v=l.child(d),b=m.matchType(v.type);if(!b)break;d++,(d>1||c==0||v.content.size)&&(m=b,u.push(gie(v.mark(p.allowedMarks(v.marks)),d==1?c:0,d==l.childCount?f:-1)))}let y=d==l.childCount;y||(f=-1),this.placed=Zv(this.placed,n,qt.from(u)),this.frontier[n].match=m,y&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,b=l;v<f;v++){let g=b.lastChild;this.frontier.push({type:g.type,match:g.contentMatchAt(g.childCount)}),b=g.content}this.unplaced=y?e==0?ln.empty:new ln(Qv(o.content,e-1,1),e-1,f<0?o.openEnd:e-1):new ln(Qv(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||!ED(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,i=this.$to.after(r);for(;r>1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),o=ED(e,n,i,r,s);if(o){for(let l=n-1;l>=0;l--){let{match:c,type:d}=this.frontier[l],u=ED(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=Zv(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Zv(this.placed,this.depth,qt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(qt.empty,!0);n.childCount&&(this.placed=Zv(this.placed,this.frontier.length,n))}}function Qv(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Qv(t.firstChild.content,e-1,n)))}function Zv(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Zv(t.lastChild.content,e-1,n)))}function jD(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function gie(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,gie(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(qt.empty,!0)))),t.copy(r)}function ED(t,e,n,r,i){let s=t.node(e),o=i?t.indexAfter(e):t.index(e);if(o==s.childCount&&!n.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!S7e(n,s.content,o)?l:null}function S7e(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function _7e(t){return t.spec.defining||t.spec.definingForContent}function k7e(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let i=t.doc.resolve(e),s=t.doc.resolve(n);if(fie(i,s,r))return t.step(new Ri(e,n,r));let o=xie(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 y=i.node(p).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;o.indexOf(p)>-1?l=p:i.before(p)==f&&o.splice(1,0,-p)}let c=o.indexOf(l),d=[],u=r.openStart;for(let p=r.content,f=0;;f++){let y=p.firstChild;if(d.push(y),f==r.openStart)break;p=y.content}for(let p=u-1;p>=0;p--){let f=d[p],y=_7e(f.type);if(y&&!f.sameMarkup(i.node(Math.abs(l)-1)))u=p;else if(y||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+u+1)%(r.openStart+1),y=d[f];if(y)for(let v=0;v<o.length;v++){let b=o[(v+c)%o.length],g=!0;b<0&&(g=!1,b=-b);let _=i.node(b-1),k=i.index(b-1);if(_.canReplaceWith(k,k,y.type,y.marks))return t.replace(i.before(b),g?s.after(b):n,new ln(bie(r.content,0,r.openStart,f),f,r.openEnd))}}let m=t.steps.length;for(let p=o.length-1;p>=0&&(t.replace(e,n,r),!(t.steps.length>m));p--){let f=o[p];f<0||(e=i.before(f),n=s.after(f))}}function bie(t,e,n,r,i){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(bie(s.content,e+1,n,r,s)))}if(e>r){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(qt.empty,!0))}return t}function N7e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=v7e(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new ln(qt.from(r),0,0))}function C7e(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n),s=xie(r,i);for(let o=0;o<s.length;o++){let l=s[o],c=o==s.length-1;if(c&&l==0||r.node(l).type.contentMatch.validEnd)return t.delete(r.start(l),i.end(l));if(l>0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&i.end(o)-n!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function xie(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let s=t.start(i);if(s<t.pos-(t.depth-i)||e.end(i)>e.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&n.push(i)}return n}class hx extends Os{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return li.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let i=n.type.create(r,null,n.marks);return li.fromReplace(e,this.pos,this.pos+1,new ln(qt.from(i),0,n.isLeaf?0:1))}getMap(){return el.empty}invert(e){return new hx(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 hx(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 hx(n.pos,n.attr,n.value)}}Os.jsonID("attr",hx);class hw extends Os{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return li.ok(r)}getMap(){return el.empty}invert(e){return new hw(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 hw(n.attr,n.value)}}Os.jsonID("docAttr",hw);let Bx=class extends Error{};Bx=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Bx.prototype=Object.create(Error.prototype);Bx.prototype.constructor=Bx;Bx.prototype.name="TransformError";class yie{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new mw}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Bx(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let i=this.mapping.maps[r];r&&(e=i.map(e,1),n=i.map(n,-1)),i.forEach((s,o,l,c)=>{e=Math.min(e,l),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=ln.empty){let i=OT(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new ln(qt.from(r),0,0))}delete(e,n){return this.replace(e,n,ln.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return k7e(this,e,n,r),this}replaceRangeWith(e,n,r){return N7e(this,e,n,r),this}deleteRange(e,n){return C7e(this,e,n),this}lift(e,n){return d7e(this,e,n),this}join(e,n=1){return y7e(this,e,n),this}wrap(e,n){return h7e(this,e,n),this}setBlockType(e,n=e,r,i=null){return p7e(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return g7e(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new hx(e,n,r)),this}setDocAttribute(e,n){return this.step(new hw(e,n)),this}addNodeMark(e,n){return this.step(new Ch(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Zr)n.isInSet(r.marks)&&this.step(new rg(e,n));else{let i=r.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new rg(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return b7e(this,e,n,r),this}addMark(e,n,r){return o7e(this,e,n,r),this}removeMark(e,n,r){return l7e(this,e,n,r),this}clearIncompatible(e,n,r){return nz(this,e,n,r),this}}const DD=Object.create(null);class nr{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new P7e(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=ln.empty){let r=n.content.lastChild,i=null;for(let l=0;l<n.openEnd;l++)i=r,r=r.lastChild;let s=e.steps.length,o=this.ranges;for(let l=0;l<o.length;l++){let{$from:c,$to:d}=o[l],u=e.mapping.slice(s);e.replaceRange(u.map(c.pos),u.map(d.pos),l?ln.empty:n),l==0&&xK(e,s,(r?r.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:o,$to:l}=i[s],c=e.mapping.slice(r),d=c.map(o.pos),u=c.map(l.pos);s?e.deleteRange(d,u):(e.replaceRangeWith(d,u,n),xK(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let i=e.parent.inlineContent?new Bn(e):qb(e.node(0),e.parent,e.pos,e.index(),n,r);if(i)return i;for(let s=e.depth-1;s>=0;s--){let o=n<0?qb(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):qb(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new sl(e.node(0))}static atStart(e){return qb(e,e,0,0,1)||new sl(e)}static atEnd(e){return qb(e,e,e.content.size,e.childCount,-1)||new sl(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=DD[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in DD)throw new RangeError("Duplicate use of selection JSON ID "+e);return DD[e]=n,n.prototype.jsonID=e,n}getBookmark(){return Bn.between(this.$anchor,this.$head).getBookmark()}}nr.prototype.visible=!0;class P7e{constructor(e,n){this.$from=e,this.$to=n}}let gK=!1;function bK(t){!gK&&!t.parent.inlineContent&&(gK=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class Bn extends nr{constructor(e,n=e){bK(e),bK(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return nr.near(r);let i=e.resolve(n.map(this.anchor));return new Bn(i.parent.inlineContent?i:r,r)}replace(e,n=ln.empty){if(super.replace(e,n),n==ln.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof Bn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new IT(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 Bn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let s=nr.findFrom(n,r,!0)||nr.findFrom(n,-r,!0);if(s)n=s.$head;else return nr.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(nr.findFrom(e,-r,!0)||nr.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=i<0&&(e=n))),new Bn(e,n)}}nr.jsonID("text",Bn);class IT{constructor(e,n){this.anchor=e,this.head=n}map(e){return new IT(e.map(this.anchor),e.map(this.head))}resolve(e){return Bn.between(e.resolve(this.anchor),e.resolve(this.head))}}class Tn extends nr{constructor(e){let n=e.nodeAfter,r=e.node(0).resolve(e.pos+n.nodeSize);super(e,r),this.node=n}map(e,n){let{deleted:r,pos:i}=n.mapResult(this.anchor),s=e.resolve(i);return r?nr.near(s):new Tn(s)}content(){return new ln(qt.from(this.node),0,0)}eq(e){return e instanceof Tn&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new az(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Tn(e.resolve(n.anchor))}static create(e,n){return new Tn(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}Tn.prototype.visible=!1;nr.jsonID("node",Tn);class az{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new IT(r,r):new az(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&Tn.isSelectable(r)?new Tn(n):nr.near(n)}}class sl extends nr{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=ln.empty){if(n==ln.empty){e.delete(0,e.doc.content.size);let r=nr.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new sl(e)}map(e){return new sl(e)}eq(e){return e instanceof sl}getBookmark(){return T7e}}nr.jsonID("all",sl);const T7e={map(){return this},resolve(t){return new sl(t)}};function qb(t,e,n,r,i,s=!1){if(e.inlineContent)return Bn.create(t,n);for(let o=r-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&Tn.isSelectable(l))return Tn.create(t,n-(i<0?l.nodeSize:0))}else{let c=qb(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function xK(t,e,n){let r=t.steps.length-1;if(r<e)return;let i=t.steps[r];if(!(i instanceof Ri||i instanceof Oi))return;let s=t.mapping.maps[r],o;s.forEach((l,c,d,u)=>{o==null&&(o=u)}),t.setSelection(nr.near(t.doc.resolve(o),n))}const yK=1,J1=2,vK=4;class A7e extends yie{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|yK)&~J1,this.storedMarks=null,this}get selectionSet(){return(this.updated&yK)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=J1,this}ensureMarks(e){return Zr.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&J1)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~J1,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Zr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=r==n?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(nr.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|=vK,this}get scrolledIntoView(){return(this.updated&vK)>0}}function wK(t,e){return!e||!t?t:t.bind(e)}class Jv{constructor(e,n,r){this.name=e,this.init=wK(n.init,r),this.apply=wK(n.apply,r)}}const M7e=[new Jv("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Jv("selection",{init(t,e){return t.selection||nr.atStart(e.doc)},apply(t){return t.selection}}),new Jv("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Jv("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class FD{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=M7e.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Jv(r.key,r.spec.state,r))})}}class ex{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=n){let i=this.config.plugins[r];if(i.spec.filterTransaction&&!i.spec.filterTransaction.call(i,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),i=null;for(;;){let s=!1;for(let o=0;o<this.config.plugins.length;o++){let l=this.config.plugins[o];if(l.spec.appendTransaction){let c=i?i[o].n:0,d=i?i[o].state:this,u=c<n.length&&l.spec.appendTransaction.call(l,c?n.slice(c):n,d,r);if(u&&r.filterTransaction(u,o)){if(u.setMeta("appendedTransaction",e),!i){i=[];for(let m=0;m<this.config.plugins.length;m++)i.push(m<o?{state:r,n:n.length}:{state:this,n:0})}n.push(u),r=r.applyInner(u),s=!0}i&&(i[o]={state:r,n:n.length})}}if(!s)return{state:r,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new ex(this.config),r=this.config.fields;for(let i=0;i<r.length;i++){let s=r[i];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new A7e(this)}static create(e){let n=new FD(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new ex(n);for(let i=0;i<n.fields.length;i++)r[n.fields[i].name]=n.fields[i].init(e,r);return r}reconfigure(e){let n=new FD(this.schema,e.plugins),r=n.fields,i=new ex(n);for(let s=0;s<r.length;s++){let o=r[s].name;i[o]=this.hasOwnProperty(o)?this[o]:r[s].init(e,i)}return i}toJSON(e){let n={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(n.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new FD(e.schema,e.plugins),s=new ex(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Ec.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=nr.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let c=r[l],d=c.spec.state;if(c.key==o.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=d.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function vie(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=vie(i,e,{})),n[r]=i}return n}class Ma{constructor(e){this.spec=e,this.props={},e.props&&vie(e.props,this,this.props),this.key=e.key?e.key.key:wie("plugin")}getState(e){return e[this.key]}}const RD=Object.create(null);function wie(t){return t in RD?t+"$"+ ++RD[t]:(RD[t]=0,t+"$")}class Ni{constructor(e="key"){this.key=wie(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const iz=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Sie(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const _ie=(t,e,n)=>{let r=Sie(t,n);if(!r)return!1;let i=sz(r);if(!i){let o=r.blockRange(),l=o&&yy(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Eie(t,i,e,-1))return!0;if(r.parent.content.size==0&&(Hx(s,"end")||Tn.isSelectable(s)))for(let o=r.depth;;o--){let l=OT(t.doc,r.before(o),r.after(o),ln.empty);if(l&&l.slice.size<l.to-l.from){if(e){let c=t.tr.step(l);c.setSelection(Hx(s,"end")?nr.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):Tn.create(c.doc,i.pos-s.nodeSize)),e(c.scrollIntoView())}return!0}if(o==1||r.node(o-1).childCount>1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},j7e=(t,e,n)=>{let r=Sie(t,n);if(!r)return!1;let i=sz(r);return i?kie(t,i,e):!1},E7e=(t,e,n)=>{let r=Cie(t,n);if(!r)return!1;let i=oz(r);return i?kie(t,i,e):!1};function kie(t,e,n){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let d=OT(t.doc,s,c,ln.empty);if(!d||d.from!=s||d instanceof Ri&&d.slice.size>=c-s)return!1;if(n){let u=t.tr.step(d);u.setSelection(Bn.create(u.doc,s)),n(u.scrollIntoView())}return!0}function Hx(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const Nie=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=sz(r)}let o=s&&s.nodeBefore;return!o||!Tn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Tn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function sz(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 Cie(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const Pie=(t,e,n)=>{let r=Cie(t,n);if(!r)return!1;let i=oz(r);if(!i)return!1;let s=i.nodeAfter;if(Eie(t,i,e,1))return!0;if(r.parent.content.size==0&&(Hx(s,"start")||Tn.isSelectable(s))){let o=OT(t.doc,r.before(),r.after(),ln.empty);if(o&&o.slice.size<o.to-o.from){if(e){let l=t.tr.step(o);l.setSelection(Hx(s,"start")?nr.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):Tn.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos,i.pos+s.nodeSize).scrollIntoView()),!0):!1},Tie=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;s=oz(r)}let o=s&&s.nodeAfter;return!o||!Tn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Tn.create(t.doc,s.pos)).scrollIntoView()),!0)};function oz(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 D7e=(t,e)=>{let n=t.selection,r=n instanceof Tn,i;if(r){if(n.node.isTextblock||!op(t.doc,n.from))return!1;i=n.from}else if(i=LT(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);r&&s.setSelection(Tn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},F7e=(t,e)=>{let n=t.selection,r;if(n instanceof Tn){if(n.node.isTextblock||!op(t.doc,n.to))return!1;r=n.to}else if(r=LT(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},R7e=(t,e)=>{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),s=i&&yy(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},Aie=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
  8193. `).scrollIntoView()),!0)};function lz(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 L7e=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=lz(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(nr.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},Mie=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof sl||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=lz(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,l=t.tr.insert(o,s.createAndFill());l.setSelection(Bn.create(l.doc,o+1)),e(l.scrollIntoView())}return!0},jie=(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(Hu(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),i=r&&yy(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function O7e(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof Tn&&e.selection.node.isBlock)return!r.parentOffset||!Hu(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,c=!1,d=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){c=r.end(f)==r.pos+(r.depth-f),d=r.start(f)==r.pos-(r.depth-f),l=lz(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),s.unshift(c&&l?{type:l}:null),o=f;break}else{if(f==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof Bn||e.selection instanceof sl)&&u.deleteSelection();let m=u.mapping.map(r.pos),p=Hu(u.doc,m,s.length,s);if(p||(s[0]=l?{type:l}:null,p=Hu(u.doc,m,s.length,s)),!p)return!1;if(u.split(m,s.length,s),!c&&d&&r.node(o).type!=l){let f=u.mapping.map(r.before(o)),y=u.doc.resolve(f);l&&r.node(o-1).canReplaceWith(y.index(),y.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return n&&n(u.scrollIntoView()),!0}}const I7e=O7e(),z7e=(t,e)=>{let{$from:n,to:r}=t.selection,i,s=n.sharedDepth(r);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(Tn.create(t.doc,i))),!0)};function U7e(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||op(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Eie(t,e,n,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&U7e(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,y=qt.empty;for(let g=o.length-1;g>=0;g--)y=qt.from(o[g].create(null,y));y=qt.from(i.copy(y));let v=t.tr.step(new Oi(e.pos-1,f,e.pos,f,new ln(y,1,0),o.length,!0)),b=v.doc.resolve(f+2*o.length);b.nodeAfter&&b.nodeAfter.type==i.type&&op(v.doc,b.pos)&&v.join(b.pos),n(v.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&c?null:nr.findFrom(e,1),m=u&&u.$from.blockRange(u.$to),p=m&&yy(m);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(m,p).scrollIntoView()),!0;if(d&&Hx(s,"start",!0)&&Hx(i,"end")){let f=i,y=[];for(;y.push(f),!f.isTextblock;)f=f.lastChild;let v=s,b=1;for(;!v.isTextblock;v=v.firstChild)b++;if(f.canReplace(f.childCount,f.childCount,v.content)){if(n){let g=qt.empty;for(let k=y.length-1;k>=0;k--)g=qt.from(y[k].copy(g));let _=t.tr.step(new Oi(e.pos-y.length,e.pos+s.nodeSize,e.pos+b,e.pos+s.nodeSize-b,new ln(g,y.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function Die(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection(Bn.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const B7e=Die(-1),H7e=Die(1);function q7e(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&rz(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function SK(t,e=null){return function(n,r){let i=!1;for(let s=0;s<n.selection.ranges.length&&!i;s++){let{$from:{pos:o},$to:{pos:l}}=n.selection.ranges[s];n.doc.nodesBetween(o,l,(c,d)=>{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)i=!0;else{let u=n.doc.resolve(d),m=u.index();i=u.parent.canReplaceWith(m,m+1,t)}})}if(!i)return!1;if(r){let s=n.tr;for(let o=0;o<n.selection.ranges.length;o++){let{$from:{pos:l},$to:{pos:c}}=n.selection.ranges[o];s.setBlockType(l,c,t,e)}r(s.scrollIntoView())}return!0}}function cz(...t){return function(e,n,r){for(let i=0;i<t.length;i++)if(t[i](e,n,r))return!0;return!1}}cz(iz,_ie,Nie);cz(iz,Pie,Tie);cz(Aie,Mie,jie,I7e);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function $7e(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s);if(!o)return!1;let l=r?n.tr:null;return V7e(l,o,t,e)?(r&&r(l.scrollIntoView()),!0):!1}}function V7e(t,e,n,r=null){let i=!1,s=e,o=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);s=new NC(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new NC(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=rz(s,n,r,e);return l?(t&&G7e(t,e,l,i,n),!0):!1}function G7e(t,e,n,r,i){let s=qt.empty;for(let u=n.length-1;u>=0;u--)s=qt.from(n[u].type.create(n[u].attrs,s));t.step(new Oi(e.start-(r?2:0),e.end,e.start,e.end,new ln(s,0,0),n.length,!0));let o=0;for(let u=0;u<n.length;u++)n[u].type==i&&(o=u+1);let l=n.length-o,c=e.start+n.length-(r?2:0),d=e.parent;for(let u=e.startIndex,m=e.endIndex,p=!0;u<m;u++,p=!1)!p&&Hu(t.doc,c,l)&&(t.split(c,l),c+=2*l),c+=d.child(u).nodeSize;return t}function W7e(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,o=>o.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?K7e(e,n,t,s):Y7e(e,n,s):!0:!1}}function K7e(t,e,n,r){let i=t.tr,s=r.end,o=r.$to.end(r.depth);s<o&&(i.step(new Oi(s-1,o,s,o,new ln(qt.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new NC(i.doc.resolve(r.$from.pos),i.doc.resolve(o),r.depth));const l=yy(r);if(l==null)return!1;i.lift(r,l);let c=i.doc.resolve(i.mapping.map(s,-1)-1);return op(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&i.join(c.pos),e(i.scrollIntoView()),!0}function Y7e(t,e,n){let r=t.tr,i=n.parent;for(let f=n.end,y=n.endIndex-1,v=n.startIndex;y>v;y--)f-=i.child(y).nodeSize,r.delete(f-1,f+1);let s=r.doc.resolve(n.start),o=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,d=s.node(-1),u=s.index(-1);if(!d.canReplace(u+(l?0:1),u+1,o.content.append(c?qt.empty:qt.from(i))))return!1;let m=s.pos,p=m+o.nodeSize;return r.step(new Oi(m-(l?1:0),p+(c?1:0),m+1,p-1,new ln((l?qt.empty:qt.from(i.copy(qt.empty))).append(c?qt.empty:qt.from(i.copy(qt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function X7e(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,d=>d.childCount>0&&d.firstChild.type==t);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,c=l.child(o-1);if(c.type!=t)return!1;if(n){let d=c.lastChild&&c.lastChild.type==l.type,u=qt.from(d?t.create():null),m=new ln(qt.from(t.create(null,qt.from(l.type.create(null,u)))),d?3:1,0),p=s.start,f=s.end;n(e.tr.step(new Oi(p-(d?3:1),f,p,f,m,1,!0)).scrollIntoView())}return!0}}const is=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},qx=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let cL=null;const vu=function(t,e,n){let r=cL||(cL=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},Q7e=function(){cL=null},ag=function(t,e,n,r){return n&&(_K(t,e,n,r,-1)||_K(t,e,n,r,1))},Z7e=/^(img|br|input|textarea|hr)$/i;function _K(t,e,n,r,i){for(var s;;){if(t==n&&e==r)return!0;if(e==(i<0?0:zl(t))){let o=t.parentNode;if(!o||o.nodeType!=1||hS(t)||Z7e.test(t.nodeName)||t.contentEditable=="false")return!1;e=is(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?zl(t):0}else return!1}}function zl(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function J7e(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=zl(t)}else if(t.parentNode&&!hS(t))e=is(t),t=t.parentNode;else return null}}function e9e(t,e){for(;;){if(t.nodeType==3&&e<t.nodeValue.length)return t;if(t.nodeType==1&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!hS(t))e=is(t)+1,t=t.parentNode;else return null}}function t9e(t,e,n){for(let r=e==0,i=e==zl(t);r||i;){if(t==n)return!0;let s=is(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,i=i&&s==zl(t)}}function hS(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 zT=function(t){return t.focusNode&&ag(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function rf(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function n9e(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function r9e(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(zl(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(zl(r.startContainer),r.startOffset)}}}const jd=typeof navigator<"u"?navigator:null,kK=typeof document<"u"?document:null,lp=jd&&jd.userAgent||"",dL=/Edge\/(\d+)/.exec(lp),Fie=/MSIE \d/.exec(lp),uL=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(lp),Ao=!!(Fie||uL||dL),Uh=Fie?document.documentMode:uL?+uL[1]:dL?+dL[1]:0,Gl=!Ao&&/gecko\/(\d+)/i.test(lp);Gl&&+(/Firefox\/(\d+)/.exec(lp)||[0,0])[1];const mL=!Ao&&/Chrome\/(\d+)/.exec(lp),ds=!!mL,Rie=mL?+mL[1]:0,Fs=!Ao&&!!jd&&/Apple Computer/.test(jd.vendor),$x=Fs&&(/Mobile\/\w+/.test(lp)||!!jd&&jd.maxTouchPoints>2),Dl=$x||(jd?/Mac/.test(jd.platform):!1),Lie=jd?/Win/.test(jd.platform):!1,Fu=/Android \d/.test(lp),pS=!!kK&&"webkitFontSmoothing"in kK.documentElement.style,a9e=pS?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function i9e(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 hu(t,e){return typeof t=="number"?t:t[e]}function s9e(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function NK(t,e,n){let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=qx(o);continue}let l=o,c=l==s.body,d=c?i9e(s):s9e(l),u=0,m=0;if(e.top<d.top+hu(r,"top")?m=-(d.top-e.top+hu(i,"top")):e.bottom>d.bottom-hu(r,"bottom")&&(m=e.bottom-e.top>d.bottom-d.top?e.top+hu(i,"top")-d.top:e.bottom-d.bottom+hu(i,"bottom")),e.left<d.left+hu(r,"left")?u=-(d.left-e.left+hu(i,"left")):e.right>d.right-hu(r,"right")&&(u=e.right-d.right+hu(i,"right")),u||m)if(c)s.defaultView.scrollBy(u,m);else{let f=l.scrollLeft,y=l.scrollTop;m&&(l.scrollTop+=m),u&&(l.scrollLeft+=u);let v=l.scrollLeft-f,b=l.scrollTop-y;e={left:e.left-v,top:e.top-b,right:e.right-v,bottom:e.bottom-b}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:qx(o)}}function o9e(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=n+1;o<Math.min(innerHeight,e.bottom);o+=5){let l=t.root.elementFromPoint(s,o);if(!l||l==t.dom||!t.dom.contains(l))continue;let c=l.getBoundingClientRect();if(c.top>=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:Oie(t.dom)}}function Oie(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=qx(r));return e}function l9e({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Iie(n,r==0?0:r-e)}function Iie(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:i,left:s}=t[n];r.scrollTop!=i+e&&(r.scrollTop=i+e),r.scrollLeft!=s&&(r.scrollLeft=s)}}let Fb=null;function c9e(t){if(t.setActive)return t.setActive();if(Fb)return t.focus(Fb);let e=Oie(t);t.focus(Fb==null?{get preventScroll(){return Fb={preventScroll:!0},!0}}:void 0),Fb||(Fb=!1,Iie(e,0))}function zie(t,e){let n,r=2e8,i,s=0,o=e.top,l=e.top,c,d;for(let u=t.firstChild,m=0;u;u=u.nextSibling,m++){let p;if(u.nodeType==1)p=u.getClientRects();else if(u.nodeType==3)p=vu(u).getClientRects();else continue;for(let f=0;f<p.length;f++){let y=p[f];if(y.top<=o&&y.bottom>=l){o=Math.max(y.bottom,o),l=Math.min(y.top,l);let v=y.left>e.left?y.left-e.left:y.right<e.left?e.left-y.right:0;if(v<r){n=u,r=v,i=v&&n.nodeType==3?{left:y.right<e.left?y.right:y.left,top:e.top}:e,u.nodeType==1&&v&&(s=m+(e.left>=(y.left+y.right)/2?1:0));continue}}else y.top>e.top&&!c&&y.left<=e.left&&y.right>=e.left&&(c=u,d={left:Math.max(y.left,Math.min(y.right,e.left)),top:y.top});!n&&(e.left>=y.right&&e.top>=y.top||e.left>=y.left&&e.top>=y.bottom)&&(s=m+1)}}return!n&&c&&(n=c,i=d,r=0),n&&n.nodeType==3?d9e(n,i):!n||r&&n.nodeType==1?{node:t,offset:s}:zie(n,i)}function d9e(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let o=th(r,1);if(o.top!=o.bottom&&dz(e,o)){i={node:t,offset:s+(e.left>=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function dz(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function u9e(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function m9e(t,e,n){let{node:r,offset:i}=zie(e,n),s=-1;if(r.nodeType==1&&!r.firstChild){let o=r.getBoundingClientRect();s=o.left!=o.right&&n.left>(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(r,i,s)}function h9e(t,e,n,r){let i=-1;for(let s=e,o=!1;s!=t.dom;){let l=t.docView.nearestDesc(s,!0),c;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&c.left>r.left||c.top>r.top?i=l.posBefore:(!o&&c.right<r.left||c.bottom<r.top)&&(i=l.posAfter),o=!0),!l.contentDOM&&i<0&&!l.node.isText))return(l.node.isBlock?r.top<(c.top+c.bottom)/2:r.left<(c.left+c.right)/2)?l.posBefore:l.posAfter;s=l.dom.parentNode}return i>-1?i:t.docView.posFromDOM(e,n,-1)}function Uie(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let i=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),s=i;;){let o=t.childNodes[s];if(o.nodeType==1){let l=o.getClientRects();for(let c=0;c<l.length;c++){let d=l[c];if(dz(e,d))return Uie(o,e,d)}}if((s=(s+1)%r)==i)break}return t}function p9e(t,e){let n=t.dom.ownerDocument,r,i=0,s=r9e(n,e.left,e.top);s&&({node:r,offset:i}=s);let o=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),l;if(!o||!t.dom.contains(o.nodeType!=1?o.parentNode:o)){let d=t.dom.getBoundingClientRect();if(!dz(e,d)||(o=Uie(t.dom,e,d),!o))return null}if(Fs)for(let d=o;r&&d;d=qx(d))d.draggable&&(r=void 0);if(o=u9e(o,e),r){if(Gl&&r.nodeType==1&&(i=Math.min(i,r.childNodes.length),i<r.childNodes.length)){let u=r.childNodes[i],m;u.nodeName=="IMG"&&(m=u.getBoundingClientRect()).right<=e.left&&m.bottom>e.top&&i++}let d;pS&&i&&r.nodeType==1&&(d=r.childNodes[i-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=h9e(t,r,i,e))}l==null&&(l=m9e(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function CK(t){return t.top<t.bottom||t.left<t.right}function th(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(CK(r))return r}return Array.prototype.find.call(n,CK)||t.getBoundingClientRect()}const f9e=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Bie(t,e,n){let{node:r,offset:i,atom:s}=t.docView.domFromPos(e,n<0?-1:1),o=pS||Gl;if(r.nodeType==3)if(o&&(f9e.test(r.nodeValue)||(n<0?!i:i==r.nodeValue.length))){let c=th(vu(r,i,i),n);if(Gl&&i&&/\s/.test(r.nodeValue[i-1])&&i<r.nodeValue.length){let d=th(vu(r,i-1,i-1),-1);if(d.top==c.top){let u=th(vu(r,i,i+1),-1);if(u.top!=c.top)return zv(u,u.left<d.left)}}return c}else{let c=i,d=i,u=n<0?1:-1;return n<0&&!i?(d++,u=-1):n>=0&&i==r.nodeValue.length?(c--,u=1):n<0?c--:d++,zv(th(vu(r,c,d),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==zl(r))){let c=r.childNodes[i-1];if(c.nodeType==1)return LD(c.getBoundingClientRect(),!1)}if(s==null&&i<zl(r)){let c=r.childNodes[i];if(c.nodeType==1)return LD(c.getBoundingClientRect(),!0)}return LD(r.getBoundingClientRect(),n>=0)}if(s==null&&i&&(n<0||i==zl(r))){let c=r.childNodes[i-1],d=c.nodeType==3?vu(c,zl(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return zv(th(d,1),!1)}if(s==null&&i<zl(r)){let c=r.childNodes[i];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let d=c?c.nodeType==3?vu(c,0,o?0:1):c.nodeType==1?c:null:null;if(d)return zv(th(d,-1),!0)}return zv(th(r.nodeType==3?vu(r):r,-n),n>=0)}function zv(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 LD(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 Hie(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function g9e(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Hie(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=Bie(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=vu(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 b9e=/[\u0590-\u08ac]/;function x9e(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=t.domSelection();return l?!b9e.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:Hie(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:m}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let f=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:y,focusOffset:v}=t.domSelectionRange(),b=y&&!f.contains(y.nodeType==1?y:y.parentNode)||c==y&&d==v;try{l.collapse(u,m),c&&(c!=u||d!=m)&&l.extend&&l.extend(c,d)}catch{}return p!=null&&(l.caretBidiLevel=p),b}):r.pos==r.start()||r.pos==r.end()}let PK=null,TK=null,AK=!1;function y9e(t,e,n){return PK==e&&TK==n?AK:(PK=e,TK=n,AK=n=="up"||n=="down"?g9e(t,e,n):x9e(t,e,n))}const Wl=0,MK=1,ff=2,Ed=3;class fS{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=Wl,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n<this.children.length;n++)e+=this.children[n].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let n=0,r=this.posAtStart;;n++){let i=this.children[n];if(i==e)return r;r+=i.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,n,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let s,o;if(e==this.contentDOM)s=e.childNodes[n-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.previousSibling}for(;s&&!((o=s.pmViewDesc)&&o.parent==this);)s=s.previousSibling;return s?this.posBeforeChild(o)+o.size:this.posAtStart}else{let s,o;if(e==this.contentDOM)s=e.childNodes[n];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.nextSibling}for(;s&&!((o=s.pmViewDesc)&&o.parent==this);)s=s.nextSibling;return s?this.posBeforeChild(o):this.posAtEnd}let i;if(e==this.dom&&this.contentDOM)i=n>is(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!n||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let i=this.children[n],s=r+i.size;if(r==e&&s!=r){for(;!i.border&&i.children.length;)for(let o=0;o<i.children.length;o++){let l=i.children[o];if(l.size){i=l;break}}return i}if(e<s)return i.descAt(e-r-i.border);r=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,i=0;for(let s=0;r<this.children.length;r++){let o=this.children[r],l=s+o.size;if(l>e||o instanceof $ie){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof qie&&s.side>=0;r--);if(n<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?is(s.dom)+1:0}}else{let s,o=!0;for(;s=r<this.children.length?this.children[r]:null,!(!s||s.dom.parentNode==this.contentDOM);r++,o=!1);return s&&o&&!s.border&&!s.domAtom?s.domFromPos(0,n):{node:this.contentDOM,offset:s?is(s.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:n,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let i=-1,s=-1;for(let o=r,l=0;;l++){let c=this.children[l],d=o+c.size;if(i==-1&&e<=d){let u=o+c.border;if(e>=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,u);e=o;for(let m=l;m>0;m--){let p=this.children[m-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){i=is(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=is(m.dom);break}n+=m.size}s==-1&&(s=this.contentDOM.childNodes.length);break}o=d}return{node:this.contentDOM,from:e,to:n,fromOffset:i,toOffset:s}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let n=this.children[e<0?0:this.children.length-1];return n.size==0||n.emptyChildAt(e)}domAfterPos(e){let{node:n,offset:r}=this.domFromPos(e,0);if(n.nodeType!=1||r==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[r]}setSelection(e,n,r,i=!1){let s=Math.min(e,n),o=Math.max(e,n);for(let f=0,y=0;f<this.children.length;f++){let v=this.children[f],b=y+v.size;if(s>y&&o<b)return v.setSelection(e-y-v.border,n-y-v.border,r,i);y=b}let l=this.domFromPos(e,e?-1:1),c=n==e?l:this.domFromPos(n,n?-1:1),d=r.root.getSelection(),u=r.domSelectionRange(),m=!1;if((Gl||Fs)&&e==n){let{node:f,offset:y}=l;if(f.nodeType==3){if(m=!!(y&&f.nodeValue[y-1]==`
  8194. `),m&&y==f.nodeValue.length)for(let v=f,b;v;v=v.parentNode){if(b=v.nextSibling){b.nodeName=="BR"&&(l=c={node:b.parentNode,offset:is(b)+1});break}let g=v.pmViewDesc;if(g&&g.node&&g.node.isBlock)break}}else{let v=f.childNodes[y-1];m=v&&(v.nodeName=="BR"||v.contentEditable=="false")}}if(Gl&&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&&Fs)&&ag(l.node,l.offset,u.anchorNode,u.anchorOffset)&&ag(c.node,c.offset,u.focusNode,u.focusOffset))return;let p=!1;if((d.extend||e==n)&&!(m&&Gl)){d.collapse(l.node,l.offset);try{e!=n&&d.extend(c.node,c.offset),p=!0}catch{}}if(!p){if(e>n){let y=l;l=c,c=y}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(l.node,l.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i<this.children.length;i++){let s=this.children[i],o=r+s.size;if(r==o?e<=o&&n>=r:e<o&&n>r){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?ff:MK,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Ed:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?ff:Ed}r=o}this.dirty=ff}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?ff:MK;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class qie extends fS{constructor(e,n,r,i){let s,o=n.type.toDOM;if(typeof o=="function"&&(o=o(r,()=>{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==Wl&&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 v9e extends fS{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class ig extends fS{constructor(e,n,r,i,s){super(e,[],r,i),this.mark=n,this.spec=s}static create(e,n,r,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,r);return(!o||!o.dom)&&(o=pg.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new ig(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Ed||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Ed&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=Wl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=Wl}}slice(e,n,r){let i=ig.create(this.parent,this.mark,!0,r),s=this.children,o=this.size;n<o&&(s=pL(s,n,o,r)),e>0&&(s=pL(s,0,e,r));for(let l=0;l<s.length;l++)s[l].parent=i;return i.children=s,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class Bh extends fS{constructor(e,n,r,i,s,o,l,c,d){super(e,[],s,o),this.node=n,this.outerDeco=r,this.innerDeco=i,this.nodeDOM=l}static create(e,n,r,i,s,o){let l=s.nodeViews[n.type.name],c,d=l&&l(n,s,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=d&&d.dom,m=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:m}=pg.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=Wie(u,r,n),d?c=new w9e(e,n,r,i,u,m||null,p,d,s,o+1):n.isText?new UT(e,n,r,i,u,p,s):new Bh(e,n,r,i,u,m||null,p,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>qt.empty)}return e}matchesNode(e,n,r){return this.dirty==Wl&&e.eq(this.node)&&PC(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new _9e(this,o&&o.node,e);C9e(this.node,this.innerDeco,(d,u,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,e,u):d.type.side>=0&&!m&&c.syncToMarks(u==this.node.childCount?Zr.none:this.node.child(u).marks,r,e,u),c.placeWidget(d,e,i)},(d,u,m,p)=>{c.syncToMarks(d.marks,r,e,p);let f;c.findNodeMatch(d,u,m,p)||l&&e.state.selection.from>i&&e.state.selection.to<i+d.nodeSize&&(f=c.findIndexWithChild(s.node))>-1&&c.updateNodeAt(d,u,m,f,e)||c.updateNextNode(d,u,m,e,p,i)||c.addNode(d,u,m,e,i),i+=d.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==ff)&&(o&&this.protectLocalComposition(e,o),Vie(this.contentDOM,this.children,e),$x&&P9e(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof Bn)||r<n||i>n+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=T9e(this.node.content,o,r-n,i-n);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:i}){if(this.getDesc(n))return;let s=n;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new v9e(this,s,n,i);e.input.compositionNodes.push(o),this.children=pL(this.children,r,r+i.length,e,o)}update(e,n,r,i){return this.dirty==Ed||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=Wl}updateOuterDeco(e){if(PC(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Gie(this.dom,this.nodeDOM,hL(this.outerDeco,this.node,n),hL(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function jK(t,e,n,r,i){Wie(r,e,t);let s=new Bh(void 0,t,e,n,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class UT extends Bh{constructor(e,n,r,i,s,o,l){super(e,n,r,i,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==Ed||this.dirty!=Wl&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Wl||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=Wl,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),s=document.createTextNode(i.text);return new UT(this.parent,i,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Ed)}get domAtom(){return!1}isText(e){return this.node.text==e}}class $ie extends fS{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Wl&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class w9e extends Bh{constructor(e,n,r,i,s,o,l,c,d,u){super(e,n,r,i,s,o,l,d,u),this.spec=c}update(e,n,r,i){if(this.dirty==Ed)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Vie(t,e,n){let r=t.firstChild,i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=o.dom;if(l.parentNode==t){for(;l!=r;)r=EK(r),i=!0;r=r.nextSibling}else i=!0,t.insertBefore(l,r);if(o instanceof ig){let c=r?r.previousSibling:t.lastChild;Vie(o.contentDOM,o.children,n),r=c?c.nextSibling:t.firstChild}}for(;r;)r=EK(r),i=!0;i&&n.trackWrites==t&&(n.trackWrites=null)}const x0=function(t){t&&(this.nodeName=t)};x0.prototype=Object.create(null);const gf=[new x0];function hL(t,e,n){if(t.length==0)return gf;let r=n?gf[0]:new x0,i=[r];for(let s=0;s<t.length;s++){let o=t[s].type.attrs;if(o){o.nodeName&&i.push(r=new x0(o.nodeName));for(let l in o){let c=o[l];c!=null&&(n&&i.length==1&&i.push(r=new x0(e.isInline?"span":"div")),l=="class"?r.class=(r.class?r.class+" ":"")+c:l=="style"?r.style=(r.style?r.style+";":"")+c:l!="nodeName"&&(r[l]=c))}}}return i}function Gie(t,e,n,r){if(n==gf&&r==gf)return e;let i=e;for(let s=0;s<r.length;s++){let o=r[s],l=n[s];if(s){let c;l&&l.nodeName==o.nodeName&&i!=t&&(c=i.parentNode)&&c.nodeName.toLowerCase()==o.nodeName||(c=document.createElement(o.nodeName),c.pmIsDeco=!0,c.appendChild(i),l=gf[0]),i=c}S9e(i,l||gf[0],o)}return i}function S9e(t,e,n){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in n)&&t.removeAttribute(r);for(let r in n)r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],i=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<r.length;s++)i.indexOf(r[s])==-1&&t.classList.remove(r[s]);for(let s=0;s<i.length;s++)r.indexOf(i[s])==-1&&t.classList.add(i[s]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;for(;i=r.exec(e.style);)t.style.removeProperty(i[1])}n.style&&(t.style.cssText+=n.style)}}function Wie(t,e,n){return Gie(t,t,gf,hL(e,n,t.nodeType!=1))}function PC(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 EK(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class _9e{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=k9e(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let r=e;r<n;r++)this.top.children[r].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,r,i){let s=0,o=this.stack.length>>1,l=Math.min(o,e.length);for(;s<l&&(s==o-1?this.top:this.stack[s+1<<1]).matchesMark(e[s])&&e[s].type.spec.spanning!==!1;)s++;for(;s<o;)this.destroyRest(),this.top.dirty=Wl,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=ig.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,n,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,c=Math.min(this.top.children.length,l+5);l<c;l++){let d=this.top.children[l];if(d.matchesNode(e,n,r)&&!this.preMatch.matched.has(d)){s=l;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,r,i,s){let o=this.top.children[i];return o.dirty==Ed&&o.dom==o.contentDOM&&(o.dirty=ff),o.update(e,n,r,s)?(this.destroyBetween(this.index,i),this.index++,!0):!1}findIndexWithChild(e){for(;;){let n=e.parentNode;if(!n)return-1;if(n==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let i=this.index;i<this.top.children.length;i++)if(this.top.children[i]==r)return i}return-1}e=n}}updateNextNode(e,n,r,i,s,o){for(let l=this.index;l<this.top.children.length;l++){let c=this.top.children[l];if(c instanceof 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!=Ed&&PC(n,c.outerDeco));if(!p&&c.update(e,n,r,i))return this.destroyBetween(this.index,l),c.dom!=u&&(this.changed=!0),this.index++,!0;if(!p&&(m=this.recreateWrapper(c,e,n,r,i,o)))return this.destroyBetween(this.index,l),this.top.children[this.index]=m,m.contentDOM&&(m.dirty=ff,m.updateChildren(i,o+1),m.dirty=Wl),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,i,s,o){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!PC(r,e.outerDeco)||!i.eq(e.innerDeco))return null;let l=Bh.create(this.top,n,r,i,s,o);if(l.contentDOM){l.children=e.children,e.children=[];for(let c of l.children)c.parent=l}return e.destroy(),l}addNode(e,n,r,i,s){let o=Bh.create(this.top,e,n,r,i,s);o.contentDOM&&o.updateChildren(i,s+1),this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(e,n,r){let i=this.index<this.top.children.length?this.top.children[this.index]:null;if(i&&i.matchesWidget(e)&&(e==i.widget||!i.widget.type.toDOM.parentNode))this.index++;else{let s=new qie(this.top,e,n,r);this.top.children.splice(this.index++,0,s),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],n=this.top;for(;e instanceof ig;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof UT)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Fs||ds)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",n),this.addHackNode("BR",this.top))}addHackNode(e,n){if(n==this.top&&this.index<n.children.length&&n.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let i=new $ie(this.top,[],r,null);n!=this.top?n.children.push(i):n.children.splice(this.index++,0,i),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function k9e(t,e){let n=e,r=n.children.length,i=t.childCount,s=new Map,o=[];e:for(;i>0;){let l;for(;;)if(r){let d=n.children[r-1];if(d instanceof ig)n=d,r=d.children.length;else{l=d,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=l.node;if(c){if(c!=t.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function N9e(t,e){return t.type.side-e.type.side}function C9e(t,e,n,r){let i=e.locals(t),s=0;if(i.length==0){for(let d=0;d<t.childCount;d++){let u=t.child(d);r(u,i,e.forChild(s,u),d),s+=u.nodeSize}return}let o=0,l=[],c=null;for(let d=0;;){let u,m;for(;o<i.length&&i[o].to==s;){let b=i[o++];b.widget&&(u?(m||(m=[u])).push(b):u=b)}if(u)if(m){m.sort(N9e);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 y=s+p.nodeSize;if(p.isText){let b=y;o<i.length&&i[o].from<b&&(b=i[o].from);for(let g=0;g<l.length;g++)l[g].to<b&&(b=l[g].to);b<y&&(c=p.cut(b-s),p=p.cut(0,b-s),y=b,f=-1)}else for(;o<i.length&&i[o].to<y;)o++;let v=p.isInline&&!p.isLeaf?l.filter(b=>!b.inline):l.slice();r(p,v,e.forChild(s,p),f),s=y}}function P9e(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 T9e(t,e,n,r){for(let i=0,s=0;i<t.childCount&&s<=r;){let o=t.child(i++),l=s;if(s+=o.nodeSize,!o.isText)continue;let c=o.text;for(;i<t.childCount;){let d=t.child(i++);if(s+=d.nodeSize,!d.isText)break;c+=d.text}if(s>=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l<r?c.lastIndexOf(e,r-l-1):-1;if(d>=0&&d+e.length+l>=n)return l+d;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function pL(t,e,n,r,i){let s=[];for(let o=0,l=0;o<t.length;o++){let c=t[o],d=l,u=l+=c.size;d>=n||u<=e?s.push(c):(d<e&&s.push(c.slice(0,e-d,r)),i&&(s.push(i),i=void 0),u>n&&s.push(c.slice(n-d,c.size,r)))}return s}function uz(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),s=i&&i.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,d;if(zT(n)){for(c=o;i&&!i.node;)i=i.parent;let m=i.node;if(i&&m.isAtom&&Tn.isSelectable(m)&&i.parent&&!(m.isInline&&t9e(n.focusNode,n.focusOffset,i.dom))){let p=i.posBefore;d=new Tn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let m=o,p=o;for(let f=0;f<n.rangeCount;f++){let y=n.getRangeAt(f);m=Math.min(m,t.docView.posFromDOM(y.startContainer,y.startOffset,1)),p=Math.max(p,t.docView.posFromDOM(y.endContainer,y.endOffset,-1))}if(m<0)return null;[c,o]=p==t.state.selection.anchor?[p,m]:[m,p],l=r.resolve(o)}else c=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let u=r.resolve(c);if(!d){let m=e=="pointer"||t.state.selection.head<l.pos&&!s?1:-1;d=mz(t,u,l,m)}return d}function Kie(t){return t.editable?t.hasFocus():Xie(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function qu(t,e=!1){let n=t.state.selection;if(Yie(t,n),!!Kie(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&ds){let r=t.domSelectionRange(),i=t.domObserver.currentSelection;if(r.anchorNode&&i.anchorNode&&ag(r.anchorNode,r.anchorOffset,i.anchorNode,i.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)M9e(t);else{let{anchor:r,head:i}=n,s,o;DK&&!(n instanceof Bn)&&(n.$from.parent.inlineContent||(s=FK(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(o=FK(t,n.to))),t.docView.setSelection(r,i,t,e),DK&&(s&&RK(s),o&&RK(o)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&A9e(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const DK=Fs||ds&&Rie<63;function FK(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),i=r<n.childNodes.length?n.childNodes[r]:null,s=r?n.childNodes[r-1]:null;if(Fs&&i&&i.contentEditable=="false")return OD(i);if((!i||i.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(i)return OD(i);if(s)return OD(s)}}function OD(t){return t.contentEditable="true",Fs&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function RK(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function A9e(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,i=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Kie(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function M9e(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,is(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Ao&&Uh<=11&&(n.disabled=!0,n.disabled=!1)}function Yie(t,e){if(e instanceof Tn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(LK(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else LK(t)}function LK(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function mz(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||Bn.between(e,n,r)}function OK(t){return t.editable&&!t.hasFocus()?!1:Xie(t)}function Xie(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 j9e(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return ag(e.node,e.offset,n.anchorNode,n.anchorOffset)}function fL(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&nr.findFrom(s,e)}function oh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function IK(t,e,n){let r=t.state.selection;if(r instanceof Bn)if(n.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return oh(t,new Bn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=fL(t.state,e);return i&&i instanceof Tn?oh(t,i):!1}else if(!(Dl&&n.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?Tn.isSelectable(s)?oh(t,new Tn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):pS?oh(t,new Bn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Tn&&r.node.isInline)return oh(t,new Bn(e>0?r.$to:r.$from));{let i=fL(t.state,e);return i?oh(t,i):!1}}}function TC(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function y0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Rb(t,e){return e<0?E9e(t):D9e(t)}function E9e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,s,o=!1;for(Gl&&n.nodeType==1&&r<TC(n)&&y0(n.childNodes[r],-1)&&(o=!0);;)if(r>0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(y0(l,-1))i=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Qie(n))break;{let l=n.previousSibling;for(;l&&y0(l,-1);)i=n.parentNode,s=is(l),l=l.previousSibling;if(l)n=l,r=TC(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?gL(t,n,r):i&&gL(t,i,s)}function D9e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=TC(n),s,o;for(;;)if(r<i){if(n.nodeType!=1)break;let l=n.childNodes[r];if(y0(l,1))s=n,o=++r;else break}else{if(Qie(n))break;{let l=n.nextSibling;for(;l&&y0(l,1);)s=l.parentNode,o=is(l)+1,l=l.nextSibling;if(l)n=l,r=0,i=TC(n);else{if(n=n.parentNode,n==t.dom)break;r=i=0}}}s&&gL(t,s,o)}function Qie(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function F9e(t,e){for(;t&&e==t.childNodes.length&&!hS(t);)e=is(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 R9e(t,e){for(;t&&!e&&!hS(t);)e=is(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 gL(t,e,n){if(e.nodeType!=3){let s,o;(o=F9e(e,n))?(e=o,n=0):(s=R9e(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(zT(r)){let s=document.createRange();s.setEnd(e,n),s.setStart(e,n),r.removeAllRanges(),r.addRange(s)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:i}=t;setTimeout(()=>{t.state==i&&qu(t)},50)}function zK(t,e){let n=t.state.doc.resolve(e);if(!(ds||Lie)&&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 UK(t,e,n){let r=t.state.selection;if(r instanceof Bn&&!r.empty||n.indexOf("s")>-1||Dl&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=fL(t.state,e);if(o&&o instanceof Tn)return oh(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof sl?nr.near(o,e):nr.findFrom(o,e);return l?oh(t,l):!1}return!1}function BK(t,e){if(!(t.state.selection instanceof Bn))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let o=t.state.tr;return e<0?o.delete(n.pos-s.nodeSize,n.pos):o.delete(n.pos,n.pos+s.nodeSize),t.dispatch(o),!0}return!1}function HK(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function L9e(t){if(!Fs||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;HK(t,r,"true"),setTimeout(()=>HK(t,r,"false"),20)}return!1}function O9e(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function I9e(t,e){let n=e.keyCode,r=O9e(e);if(n==8||Dl&&n==72&&r=="c")return BK(t,-1)||Rb(t,-1);if(n==46&&!e.shiftKey||Dl&&n==68&&r=="c")return BK(t,1)||Rb(t,1);if(n==13||n==27)return!0;if(n==37||Dl&&n==66&&r=="c"){let i=n==37?zK(t,t.state.selection.from)=="ltr"?-1:1:-1;return IK(t,i,r)||Rb(t,i)}else if(n==39||Dl&&n==70&&r=="c"){let i=n==39?zK(t,t.state.selection.from)=="ltr"?1:-1:1;return IK(t,i,r)||Rb(t,i)}else{if(n==38||Dl&&n==80&&r=="c")return UK(t,-1,r)||Rb(t,-1);if(n==40||Dl&&n==78&&r=="c")return L9e(t)||UK(t,1,r)||Rb(t,1);if(r==(Dl?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function hz(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=t.someProp("clipboardSerializer")||pg.fromSchema(t.state.schema),l=rse(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let d=c.firstChild,u,m=0;for(;d&&d.nodeType==1&&(u=nse[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let y=l.createElement(u[f]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),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,`
  8195. `);return{dom:c,text:p,slice:e}}function Zie(t,e,n,r,i){let s=i.parent.type.spec.code,o,l;if(!n&&!e)return null;let c=!!e&&(r||s||!n);if(c){if(t.someProp("transformPastedText",p=>{e=p(e,s||r,t)}),s)return l=new ln(qt.from(t.state.schema.text(e.replace(/\r\n?/g,`
  8196. `))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let m=t.someProp("clipboardTextParser",p=>p(e,i,r,t));if(m)l=m;else{let p=i.marks(),{schema:f}=t.state,y=pg.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let b=o.appendChild(document.createElement("p"));v&&b.appendChild(y.serializeNode(f.text(v,p)))})}}else t.someProp("transformPastedHTML",m=>{n=m(n,t)}),o=H9e(n),pS&&q9e(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")||g0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:i,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!z9e.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)l=$9e(qK(l,+u[1],+u[2]),u[4]);else if(l=ln.maxOpen(U9e(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=qK(l,m,p)}return t.someProp("transformPasted",m=>{l=m(l,t,c)}),l}const z9e=/^(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 U9e(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&&ese(c,s,l,o[o.length-1],0))o[o.length-1]=d;else{o.length&&(o[o.length-1]=tse(o[o.length-1],s.length));let u=Jie(l,c);o.push(u),i=i.matchType(u.type),s=c}}),o)return qt.from(o)}return t}function Jie(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,qt.from(t));return t}function ese(t,e,n,r,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let s=ese(t,e,n,r.lastChild,i+1);if(s)return r.copy(r.content.replaceChild(r.childCount-1,s));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(qt.from(Jie(n,t,i+1))))}}function tse(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,tse(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(qt.empty,!0);return t.copy(n.append(r))}function bL(t,e,n,r,i,s){let o=e<0?t.firstChild:t.lastChild,l=o.content;return t.childCount>1&&(s=0),i<r-1&&(l=bL(l,e,n,r,i+1,s)),i>=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(qt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function qK(t,e,n){return e<t.openStart&&(t=new ln(bL(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new ln(bL(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const nse={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 $K=null;function rse(){return $K||($K=document.implementation.createHTMLDocument("title"))}let ID=null;function B9e(t){let e=window.trustedTypes;return e?(ID||(ID=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),ID.createHTML(t)):t}function H9e(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=rse().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),i;if((i=r&&nse[r[1].toLowerCase()])&&(t=i.map(s=>"<"+s+">").join("")+t+i.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=B9e(t),i)for(let s=0;s<i.length;s++)n=n.querySelector(i[s])||n;return n}function q9e(t){let e=t.querySelectorAll(ds?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent==" "&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function $9e(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:i,openStart:s,openEnd:o}=t;for(let l=r.length-2;l>=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;i=qt.from(c.create(r[l+1],i)),s++,o++}return new ln(i,s,o)}const io={},so={},V9e={touchstart:!0,touchmove:!0};class G9e{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 W9e(t){for(let e in io){let n=io[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{Y9e(t,r)&&!pz(t,r)&&(t.editable||!(r.type in so))&&n(t,r)},V9e[e]?{passive:!0}:void 0)}Fs&&t.dom.addEventListener("input",()=>null),xL(t)}function Ph(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function K9e(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 xL(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>pz(t,r))})}function pz(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function Y9e(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 X9e(t,e){!pz(t,e)&&io[e.type]&&(t.editable||!(e.type in so))&&io[e.type](t,e)}so.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!ise(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Fu&&ds&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),$x&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,rf(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||I9e(t,n)?n.preventDefault():Ph(t,"key")};so.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};so.keypress=(t,e)=>{let n=e;if(ise(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Dl&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof Bn)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,i,s))&&t.dispatch(s()),n.preventDefault()}};function BT(t){return{left:t.clientX,top:t.clientY}}function Q9e(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function fz(t,e,n,r,i){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(t.someProp(e,l=>o>s.depth?l(t,n,s.nodeAfter,s.before(o),i,!0):l(t,n,s.node(o),s.before(o),i,!1)))return!0;return!1}function px(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function Z9e(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&Tn.isSelectable(r)?(px(t,new Tn(n)),!0):!1}function J9e(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof Tn&&(r=n.node);let s=t.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(Tn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?i=s.before(n.$from.depth):i=s.before(o);break}}return i!=null?(px(t,Tn.create(t.state.doc,i)),!0):!1}function eWe(t,e,n,r,i){return fz(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(i?J9e(t,n):Z9e(t,n))}function tWe(t,e,n,r){return fz(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function nWe(t,e,n,r){return fz(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||rWe(t,n,r)}function rWe(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(px(t,Bn.create(r,0,r.content.size)),!0):!1;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)px(t,Bn.create(r,l+1,l+1+o.content.size));else if(Tn.isSelectable(o))px(t,Tn.create(r,l));else continue;return!0}}function gz(t){return AC(t)}const ase=Dl?"metaKey":"ctrlKey";io.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=gz(t),i=Date.now(),s="singleClick";i-t.input.lastClick.time<500&&Q9e(n,t.input.lastClick)&&!n[ase]&&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(BT(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new aWe(t,o,n,!!r)):(s=="doubleClick"?tWe:nWe)(t,o.pos,o.inside,n)?n.preventDefault():Ph(t,"pointer"))};class aWe{constructor(e,n,r,i){this.view=e,this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[ase],this.allowDefault=r.shiftKey;let s,o;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),o=n.inside;else{let u=e.state.doc.resolve(n.pos);s=u.parent,o=u.depth?u.before():0}const l=i?null:r.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||d instanceof Tn&&d.from<=o&&d.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Gl&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),Ph(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>qu(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(BT(e))),this.updateAllowDefault(e),this.allowDefault||!n?Ph(this.view,"pointer"):eWe(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Fs&&this.mightDrag&&!this.mightDrag.node.isAtom||ds&&!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)?(px(this.view,nr.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):Ph(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ph(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)}}io.touchstart=t=>{t.input.lastTouch=Date.now(),gz(t),Ph(t,"pointer")};io.touchmove=t=>{t.input.lastTouch=Date.now(),Ph(t,"pointer")};io.contextmenu=t=>gz(t);function ise(t,e){return t.composing?!0:Fs&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const iWe=Fu?5e3:-1;so.compositionstart=so.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof Bn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||ds&&Lie&&sWe(t)))t.markCursor=t.state.storedMarks||n.marks(),AC(t,!0),t.markCursor=null;else if(AC(t,!e.selection.empty),Gl&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}t.input.composing=!0}sse(t,iWe)};function sWe(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}so.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,sse(t,20))};function sse(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>AC(t),e))}function ose(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=lWe());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function oWe(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=J7e(e.focusNode,e.focusOffset),r=e9e(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let o=n.pmViewDesc;if(!(!o||!o.isText(n.nodeValue)))return r}}return n||r}function lWe(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function AC(t,e=!1){if(!(Fu&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),ose(t),e||t.docView&&t.docView.dirty){let n=uz(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function cWe(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const pw=Ao&&Uh<15||$x&&a9e<604;io.copy=so.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let s=pw?null:n.clipboardData,o=r.content(),{dom:l,text:c}=hz(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):cWe(t,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function dWe(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function uWe(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?fw(t,r.value,null,i,e):fw(t,r.textContent,r.innerHTML,i,e)},50)}function fw(t,e,n,r,i){let s=Zie(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,i,s||ln.empty)))return!0;if(!s)return!1;let o=dWe(s),l=o?t.state.tr.replaceSelectionWith(o,r):t.state.tr.replaceSelection(s);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function lse(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," "):""}so.paste=(t,e)=>{let n=e;if(t.composing&&!Fu)return;let r=pw?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&fw(t,lse(r),r.getData("text/html"),i,n)?n.preventDefault():uWe(t,n)};class cse{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const mWe=Dl?"altKey":"ctrlKey";function dse(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[mWe]}io.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,s=i.empty?null:t.posAtCoords(BT(n)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof Tn?i.to-1:i.to))){if(r&&r.mightDrag)o=Tn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let m=t.docView.nearestDesc(n.target,!0);m&&m.node.type.spec.draggable&&m!=t.docView&&(o=Tn.create(t.state.doc,m.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:d,slice:u}=hz(t,l);(!n.dataTransfer.files.length||!ds||Rie>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(pw?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",pw||n.dataTransfer.setData("text/plain",d),t.dragging=new cse(u,dse(t,n),o)};io.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};so.dragover=so.dragenter=(t,e)=>e.preventDefault();so.drop=(t,e)=>{try{hWe(t,e,t.dragging)}finally{t.dragging=null}};function hWe(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(BT(e));if(!r)return;let i=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",f=>{s=f(s,t,!1)}):s=Zie(t,lse(e.dataTransfer),pw?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(n&&dse(t,e));if(t.someProp("handleDrop",f=>f(t,e,s||ln.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?pie(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&&Tn.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new Tn(p));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((y,v,b,g)=>f=g),c.setSelection(mz(t,p,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}io.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&qu(t)},20))};io.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)};io.beforeinput=(t,e)=>{if(ds&&Fu&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,rf(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 so)io[t]=so[t];function gw(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 MC{constructor(e,n){this.toDOM=e,this.spec=n||Mf,this.side=this.spec.side||0}map(e,n,r,i){let{pos:s,deleted:o}=e.mapResult(n.from+i,this.side<0?-1:1);return o?null:new Xs(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof MC&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&gw(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Hh{constructor(e,n){this.attrs=e,this.spec=n||Mf}map(e,n,r,i){let s=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new Xs(s,o,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof Hh&&gw(this.attrs,e.attrs)&&gw(this.spec,e.spec)}static is(e){return e.type instanceof Hh}destroy(){}}class bz{constructor(e,n){this.attrs=e,this.spec=n||Mf}map(e,n,r,i){let s=e.mapResult(n.from+i,1);if(s.deleted)return null;let o=e.mapResult(n.to+i,-1);return o.deleted||o.pos<=s.pos?null:new Xs(s.pos-r,o.pos-r,this)}valid(e,n){let{index:r,offset:i}=e.content.findIndex(n.from),s;return i==n.from&&!(s=e.child(r)).isText&&i+s.nodeSize==n.to}eq(e){return this==e||e instanceof bz&&gw(this.attrs,e.attrs)&&gw(this.spec,e.spec)}destroy(){}}class Xs{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new Xs(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new Xs(e,e,new MC(n,r))}static inline(e,n,r,i){return new Xs(e,n,new Hh(r,i))}static node(e,n,r,i){return new Xs(e,n,new bz(r,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof Hh}get widget(){return this.type instanceof MC}}const $b=[],Mf={};class ka{constructor(e,n){this.local=e.length?e:$b,this.children=n.length?n:$b}static create(e,n){return n.length?jC(n,e,0,Mf):Ps}find(e,n,r){let i=[];return this.findInner(e??0,n??1e9,i,0,r),i}findInner(e,n,r,i,s){for(let o=0;o<this.local.length;o++){let l=this.local[o];l.from<=n&&l.to>=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<n&&this.children[o+1]>e){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,i+l,s)}}map(e,n,r){return this==Ps||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Mf)}mapInner(e,n,r,i,s){let o;for(let l=0;l<this.local.length;l++){let c=this.local[l].map(e,r,i);c&&c.type.valid(n,c)?(o||(o=[])).push(c):s.onRemove&&s.onRemove(this.local[l].spec)}return this.children.length?pWe(this.children,o||[],e,n,r,i,s):o?new ka(o.sort(jf),$b):Ps}add(e,n){return n.length?this==Ps?ka.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let i,s=0;e.forEach((l,c)=>{let d=c+r,u;if(u=mse(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,jC(u,l,d+1,Mf)),s+=3}});let o=use(s?hse(n):n,-r);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||o.splice(l--,1);return new ka(o.length?this.local.concat(o).sort(jf):this.local,i||this.children)}remove(e){return e.length==0||this==Ps?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,i=this.local;for(let s=0;s<r.length;s+=3){let o,l=r[s]+n,c=r[s+1]+n;for(let u=0,m;u<e.length;u++)(m=e[u])&&m.from>l&&m.to<c&&(e[u]=null,(o||(o=[])).push(m));if(!o)continue;r==this.children&&(r=this.children.slice());let d=r[s+2].removeInner(o,l+1);d!=Ps?r[s+2]=d:(r.splice(s,3),s-=3)}if(i.length){for(let s=0,o;s<e.length;s++)if(o=e[s])for(let l=0;l<i.length;l++)i[l].eq(o,n)&&(i==this.local&&(i=this.local.slice()),i.splice(l--,1))}return r==this.children&&i==this.local?this:i.length||r.length?new ka(i,r):Ps}forChild(e,n){if(this==Ps)return this;if(n.isLeaf)return ka.empty;let r,i;for(let l=0;l<this.children.length;l+=3)if(this.children[l]>=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+n.content.size;for(let l=0;l<this.local.length;l++){let c=this.local[l];if(c.from<o&&c.to>s&&c.type instanceof 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 ka(i.sort(jf),$b);return r?new hh([l,r]):l}return r||Ps}eq(e){if(this==e)return!0;if(!(e instanceof ka)||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 xz(this.localsInner(e))}localsInner(e){if(this==Ps)return $b;if(e.inlineContent||!this.local.some(Hh.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Hh||n.push(this.local[r]);return n}forEachSet(e){e(this)}}ka.empty=new ka([],[]);ka.removeOverlap=xz;const Ps=ka.empty;class hh{constructor(e){this.members=e}map(e,n){const r=this.members.map(i=>i.map(e,n,Mf));return hh.from(r)}forChild(e,n){if(n.isLeaf)return ka.empty;let r=[];for(let i=0;i<this.members.length;i++){let s=this.members[i].forChild(e,n);s!=Ps&&(s instanceof hh?r=r.concat(s.members):r.push(s))}return hh.from(r)}eq(e){if(!(e instanceof hh)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let i=0;i<this.members.length;i++){let s=this.members[i].localsInner(e);if(s.length)if(!n)n=s;else{r&&(n=n.slice(),r=!1);for(let o=0;o<s.length;o++)n.push(s[o])}}return n?xz(r?n:n.sort(jf)):$b}static from(e){switch(e.length){case 0:return Ps;case 1:return e[0];default:return new hh(e.every(n=>n instanceof ka)?e:e.reduce((n,r)=>n.concat(r instanceof ka?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function pWe(t,e,n,r,i,s,o){let l=t.slice();for(let d=0,u=s;d<n.maps.length;d++){let m=0;n.maps[d].forEach((p,f,y,v)=>{let b=v-y-(f-p);for(let g=0;g<l.length;g+=3){let _=l[g+1];if(_<0||p>_+u-m)continue;let k=l[g]+u-m;f>=k?l[g+1]=p<=k?-2:-1:p>=u&&b&&(l[g]+=b,l[g+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>=r.content.size){c=!0;continue}let p=n.map(t[d+1]+s,-1),f=p-i,{index:y,offset:v}=r.content.findIndex(m),b=r.maybeChild(y);if(b&&v==m&&v+b.nodeSize==f){let g=l[d+2].mapInner(n,b,u+1,t[d]+s+1,o);g!=Ps?(l[d]=m,l[d+1]=f,l[d+2]=g):(l[d+1]=-2,c=!0)}else c=!0}if(c){let d=fWe(l,t,e,n,i,s,o),u=jC(d,r,0,o);e=u.local;for(let m=0;m<l.length;m+=3)l[m+1]<0&&(l.splice(m,3),m-=3);for(let m=0,p=0;m<u.children.length;m+=3){let f=u.children[m];for(;p<l.length&&l[p]<f;)p+=3;l.splice(p,0,u.children[m],u.children[m+1],u.children[m+2])}}return new ka(e.sort(jf),l)}function use(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new Xs(i.from+e,i.to+e,i.type))}return n}function fWe(t,e,n,r,i,s,o){function l(c,d){for(let u=0;u<c.local.length;u++){let m=c.local[u].map(r,i,d);m?n.push(m):o.onRemove&&o.onRemove(c.local[u].spec)}for(let u=0;u<c.children.length;u+=3)l(c.children[u+2],c.children[u]+d+1)}for(let c=0;c<t.length;c+=3)t[c+1]==-1&&l(t[c+2],e[c]+s+1);return n}function mse(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let s=0,o;s<t.length;s++)(o=t[s])&&o.from>n&&o.to<r&&((i||(i=[])).push(o),t[s]=null);return i}function hse(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function jC(t,e,n,r){let i=[],s=!1;e.forEach((l,c)=>{let d=mse(t,l,c+n);if(d){s=!0;let u=jC(d,l,n+c+1,r);u!=Ps&&i.push(c,c+l.nodeSize,u)}});let o=use(s?hse(t):t,-n).sort(jf);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||(r.onRemove&&r.onRemove(o[l].spec),o.splice(l--,1));return o.length||i.length?new ka(o,i):Ps}function jf(t,e){return t.from-e.from||t.to-e.to}function xz(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let s=e[i];if(s.from==r.from){s.to!=r.to&&(e==t&&(e=t.slice()),e[i]=s.copy(s.from,r.to),VK(e,i+1,s.copy(r.to,s.to)));continue}else{s.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,s.from),VK(e,i,r.copy(s.from,r.to)));break}}}return e}function VK(t,e,n){for(;e<t.length&&jf(n,t[e])>0;)e++;t.splice(e,0,n)}function zD(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Ps&&e.push(r)}),t.cursorWrapper&&e.push(ka.create(t.state.doc,[t.cursorWrapper.deco])),hh.from(e)}const gWe={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},bWe=Ao&&Uh<=11;class xWe{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 yWe{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new xWe,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;i<r.length;i++)this.queue.push(r[i]);Ao&&Uh<=11&&r.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Fs&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),bWe&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,gWe)),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(OK(this.view)){if(this.suppressingSelectionUpdates)return qu(this.view);if(Ao&&Uh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&ag(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let s=e.focusNode;s;s=qx(s))n.add(s);for(let s=e.anchorNode;s;s=qx(s))if(n.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&OK(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let u=0;u<n.length;u++){let m=this.registerMutation(n[u],c);m&&(s=s<0?m.from:Math.min(m.from,s),o=o<0?m.to:Math.max(m.to,o),m.typeOver&&(l=!0))}if(c.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let m=u.nextSibling;m&&m.nodeType==1&&m.contentEditable=="false"&&u.parentNode.removeChild(u)}}else if(Gl&&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||SWe(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&&zT(r)&&(d=uz(e))&&d.eq(nr.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,qu(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||i)&&(s>-1&&(e.docView.markDirty(s,o),vWe(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,_We(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||qu(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let m=e.addedNodes[u];n.push(m),m.nodeType==3&&(this.lastChangedTextNode=m)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let i=e.previousSibling,s=e.nextSibling;if(Ao&&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?is(i)+1:0,l=r.localPosFromDOM(e.target,o,-1),c=s&&s.parentNode==e.target?is(s):e.target.childNodes.length,d=r.localPosFromDOM(e.target,c,1);return{from:l,to:d}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let GK=new WeakMap,WK=!1;function vWe(t){if(!GK.has(t)&&(GK.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=Gl,WK)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."),WK=!0}}function KK(t,e){let n=e.startContainer,r=e.startOffset,i=e.endContainer,s=e.endOffset,o=t.domAtPos(t.state.selection.anchor);return ag(o.node,o.offset,i,s)&&([n,r,i,s]=[i,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:s}}function wWe(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return KK(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?KK(t,n):null}function SWe(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function _We(t,e){var n;let{focusNode:r,focusOffset:i}=t.domSelectionRange();for(let s of e)if(((n=s.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let o=s.nextSibling;for(;o&&o.nodeName!="TD"&&o.nodeName!="TH";)o=o.nextSibling;if(o){let l=o;for(;;){let c=l.firstChild;if(!c||c.nodeType!=1||c.contentEditable=="false"||/^(BR|IMG)$/.test(c.nodeName))break;l=c}l.insertBefore(s,l.firstChild),r==s&&t.domSelection().collapse(s,i)}else s.parentNode.removeChild(s)}}function kWe(t,e,n){let{node:r,fromOffset:i,toOffset:s,from:o,to:l}=t.docView.parseRange(e,n),c=t.domSelectionRange(),d,u=c.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(d=[{node:u,offset:c.anchorOffset}],zT(c)||d.push({node:c.focusNode,offset:c.focusOffset})),ds&&t.input.lastKeyCode===8)for(let b=s;b>i;b--){let g=r.childNodes[b-1],_=g.pmViewDesc;if(g.nodeName=="BR"&&!_){s=b;break}if(!_||_.size)break}let m=t.state.doc,p=t.someProp("domParser")||g0.fromSchema(t.state.schema),f=m.resolve(o),y=null,v=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:i,to:s,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:NWe,context:f});if(d&&d[0].pos!=null){let b=d[0].pos,g=d[1]&&d[1].pos;g==null&&(g=b),y={anchor:b+o,head:g+o}}return{doc:v,sel:y,from:o,to:l}}function NWe(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Fs&&/^(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||Fs&&/^(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 CWe=/^(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 PWe(t,e,n,r,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,T=uz(t,A);if(T&&!t.state.selection.eq(T)){if(ds&&Fu&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",F=>F(t,rf(13,"Enter"))))return;let C=t.state.tr.setSelection(T);A=="pointer"?C.setMeta("pointer",!0):A=="key"&&C.scrollIntoView(),s&&C.setMeta("composition",s),t.dispatch(C)}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=kWe(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 y=MWe(m.content,d.doc.content,d.from,p,f);if(y&&t.input.domChangeCount++,($x&&t.input.lastIOSEnter>Date.now()-225||Fu)&&i.some(A=>A.nodeType==1&&!CWe.test(A.nodeName))&&(!y||y.endA>=y.endB)&&t.someProp("handleKeyDown",A=>A(t,rf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!y)if(r&&c instanceof Bn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))y={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let A=YK(t,t.state.doc,d.sel);if(A&&!A.eq(t.state.selection)){let T=t.state.tr.setSelection(A);s&&T.setMeta("composition",s),t.dispatch(T)}}return}t.state.selection.from<t.state.selection.to&&y.start==y.endB&&t.state.selection instanceof Bn&&(y.start>t.state.selection.from&&y.start<=t.state.selection.from+2&&t.state.selection.from>=d.from?y.start=t.state.selection.from:y.endA<t.state.selection.to&&y.endA>=t.state.selection.to-2&&t.state.selection.to<=d.to&&(y.endB+=t.state.selection.to-y.endA,y.endA=t.state.selection.to)),Ao&&Uh<=11&&y.endB==y.start+1&&y.endA==y.start&&y.start>d.from&&d.doc.textBetween(y.start-d.from-1,y.start-d.from+1)=="  "&&(y.start--,y.endA--,y.endB--);let v=d.doc.resolveNoCache(y.start-d.from),b=d.doc.resolveNoCache(y.endB-d.from),g=u.resolve(y.start),_=v.sameParent(b)&&v.parent.inlineContent&&g.end()>=y.endA;if(($x&&t.input.lastIOSEnter>Date.now()-225&&(!_||i.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!_&&v.pos<d.doc.content.size&&(!v.sameParent(b)||!v.parent.inlineContent)&&v.pos<b.pos&&!/\S/.test(d.doc.textBetween(v.pos,b.pos,"","")))&&t.someProp("handleKeyDown",A=>A(t,rf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>y.start&&AWe(u,y.start,y.endA,v,b)&&t.someProp("handleKeyDown",A=>A(t,rf(8,"Backspace")))){Fu&&ds&&t.domObserver.suppressSelectionUpdates();return}ds&&y.endB==y.start&&(t.input.lastChromeDelete=Date.now()),Fu&&!_&&v.start()!=b.start()&&b.parentOffset==0&&v.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==y.endA&&(y.endB-=2,b=d.doc.resolveNoCache(y.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(A){return A(t,rf(13,"Enter"))})},20));let k=y.start,P=y.endA,N=A=>{let T=A||t.state.tr.replace(k,P,d.doc.slice(y.start-d.from,y.endB-d.from));if(d.sel){let C=YK(t,T.doc,d.sel);C&&!(ds&&t.composing&&C.empty&&(y.start!=y.endB||t.input.lastChromeDelete<Date.now()-100)&&(C.head==k||C.head==T.mapping.map(P)-1)||Ao&&C.empty&&C.head==k)&&T.setSelection(C)}return s&&T.setMeta("composition",s),T.scrollIntoView()},M;if(_)if(v.pos==b.pos){Ao&&Uh<=11&&v.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>qu(t),20));let A=N(t.state.tr.delete(k,P)),T=u.resolve(y.start).marksAcross(u.resolve(y.endA));T&&A.ensureMarks(T),t.dispatch(A)}else if(y.endA==y.endB&&(M=TWe(v.parent.content.cut(v.parentOffset,b.parentOffset),g.parent.content.cut(g.parentOffset,y.endA-g.start())))){let A=N(t.state.tr);M.type=="add"?A.addMark(k,P,M.mark):A.removeMark(k,P,M.mark),t.dispatch(A)}else if(v.parent.child(v.index()).isText&&v.index()==b.index()-(b.textOffset?0:1)){let A=v.parent.textBetween(v.parentOffset,b.parentOffset),T=()=>N(t.state.tr.insertText(A,k,P));t.someProp("handleTextInput",C=>C(t,k,P,A,T))||t.dispatch(T())}else t.dispatch(N());else t.dispatch(N())}function YK(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:mz(t,e.resolve(n.anchor),e.resolve(n.head))}function TWe(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,s=r,o,l,c;for(let u=0;u<r.length;u++)i=r[u].removeFromSet(i);for(let u=0;u<n.length;u++)s=n[u].removeFromSet(s);if(i.length==1&&s.length==0)l=i[0],o="add",c=u=>u.mark(l.addToSet(u.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",c=u=>u.mark(l.removeFromSet(u.marks));else return null;let d=[];for(let u=0;u<e.childCount;u++)d.push(c(e.child(u)));if(qt.from(d).eq(t))return{mark:l,type:o}}function AWe(t,e,n,r,i){if(n-e<=i.pos-r.pos||UD(r,!0,!1)<i.pos)return!1;let s=t.resolve(e);if(!r.parent.isTextblock){let l=s.nodeAfter;return l!=null&&n==e+l.nodeSize}if(s.parentOffset<s.parent.content.size||!s.parent.isTextblock)return!1;let o=t.resolve(UD(s,!0,!0));return!o.parent.isTextblock||o.pos>n||UD(o,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(o.parent.content)}function UD(t,e,n){let r=t.depth,i=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function MWe(t,e,n,r,i){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:o,b:l}=t.findDiffEnd(e,n+t.size,n+e.size);if(i=="end"){let c=Math.max(0,s-Math.min(o,l));r-=o+c-s}if(o<s&&t.size<e.size){let c=r<=s&&r>=o?s-r:0;s-=c,s&&s<e.size&&XK(e.textBetween(s-1,s+1))&&(s+=c?1:-1),l=s+(l-o),o=s}else if(l<s){let c=r<=s&&r>=l?s-r:0;s-=c,s&&s<t.size&&XK(t.textBetween(s-1,s+1))&&(s+=c?1:-1),o=s+(o-l),l=s}return{start:s,endA:o,endB:l}}function XK(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 pse{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 G9e,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(tY),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=JK(this),ZK(this),this.nodeViews=eY(this),this.docView=jK(this.state.doc,QK(this),zD(this),this.dom,this),this.domObserver=new yWe(this,(r,i,s,o)=>PWe(this,r,i,s,o)),this.domObserver.start(),W9e(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&&xL(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(tY),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(ose(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=eY(this);EWe(f,this.nodeViews)&&(this.nodeViews=f,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&xL(this),this.editable=JK(this),ZK(this);let c=zD(this),d=QK(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&&o9e(this);if(o){this.domObserver.stop();let f=m&&(Ao||ds)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&jWe(i.selection,e.selection);if(m){let y=ds?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=oWe(this)),(s||!this.docView.update(e.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=jK(e.doc,d,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&j9e(this))?qu(this,f):(Yie(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():p&&l9e(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 Tn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&NK(this,n.getBoundingClientRect(),e)}else NK(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,i=-1;if(this.state.doc.nodeAt(r.from)==r.node)i=r.from;else{let s=r.from+(this.state.doc.content.size-n.doc.content.size);(s>0&&this.state.doc.nodeAt(s))==r.node&&(i=s)}this.dragging=new cse(e.slice,e.move,i<0?void 0:Tn.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let o=0;o<this.directPlugins.length;o++){let l=this.directPlugins[o].props[e];if(l!=null&&(i=n?n(l):l))return i}let s=this.state.plugins;if(s)for(let o=0;o<s.length;o++){let l=s[o].props[e];if(l!=null&&(i=n?n(l):l))return i}}hasFocus(){if(Ao){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&c9e(this.dom),qu(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return p9e(this,e)}coordsAtPos(e,n=1){return Bie(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return y9e(this,n||this.state,e)}pasteHTML(e,n){return fw(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return fw(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return hz(this,e)}destroy(){this.docView&&(K9e(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],zD(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Q7e())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return X9e(this,e)}domSelectionRange(){let e=this.domSelection();return e?Fs&&this.root.nodeType===11&&n9e(this.dom.ownerDocument)==this.dom&&wWe(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}pse.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function QK(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[Xs.node(0,t.state.doc.content.size,e)]}function ZK(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:Xs.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function JK(t){return!t.someProp("editable",e=>e(t.state)===!1)}function jWe(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 eY(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function EWe(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function tY(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 Qh={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:"'"},EC={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},DWe=typeof navigator<"u"&&/Mac/.test(navigator.platform),FWe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ss=0;ss<10;ss++)Qh[48+ss]=Qh[96+ss]=String(ss);for(var ss=1;ss<=24;ss++)Qh[ss+111]="F"+ss;for(var ss=65;ss<=90;ss++)Qh[ss]=String.fromCharCode(ss+32),EC[ss]=String.fromCharCode(ss);for(var BD in Qh)EC.hasOwnProperty(BD)||(EC[BD]=Qh[BD]);function RWe(t){var e=DWe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||FWe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?EC:Qh)[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 LWe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),OWe=typeof navigator<"u"&&/Win/.test(navigator.platform);function IWe(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,s,o;for(let l=0;l<e.length-1;l++){let c=e[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))LWe?o=!0:i=!0;else throw new Error("Unrecognized modifier name: "+c)}return r&&(n="Alt-"+n),i&&(n="Ctrl-"+n),o&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function zWe(t){let e=Object.create(null);for(let n in t)e[IWe(n)]=t[n];return e}function HD(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 UWe(t){return new Ma({props:{handleKeyDown:fse(t)}})}function fse(t){let e=zWe(t);return function(n,r){let i=RWe(r),s,o=e[HD(i,r)];if(o&&o(n.state,n.dispatch,n))return!0;if(i.length==1&&i!=" "){if(r.shiftKey){let l=e[HD(i,r,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(OWe&&r.ctrlKey&&r.altKey)&&(s=Qh[r.keyCode])&&s!=i){let l=e[HD(s,r)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var BWe=Object.defineProperty,yz=(t,e)=>{for(var n in e)BWe(t,n,{get:e[n],enumerable:!0})};function HT(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:i}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return i},get tr(){return r=n.selection,i=n.doc,s=n.storedMarks,n}}}var qT=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:i}=n,s=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...d)=>{const u=l(...d)(s);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(i),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o=[],l=!!t,c=t||i.tr,d=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(m=>m===!0)),u={...Object.fromEntries(Object.entries(n).map(([m,p])=>[m,(...y)=>{const v=this.buildProps(c,e),b=p(...y)(v);return o.push(b),u}])),run:d};return u}createCan(t){const{rawCommands:e,state:n}=this,r=!1,i=t||n.tr,s=this.buildProps(i,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...d)=>c(...d)({...s,dispatch:void 0})])),chain:()=>this.createChain(i,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:HT({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}},gse={};yz(gse,{blur:()=>HWe,clearContent:()=>qWe,clearNodes:()=>$We,command:()=>VWe,createParagraphNear:()=>GWe,cut:()=>WWe,deleteCurrentNode:()=>KWe,deleteNode:()=>YWe,deleteRange:()=>XWe,deleteSelection:()=>QWe,enter:()=>ZWe,exitCode:()=>JWe,extendMarkRange:()=>eKe,first:()=>tKe,focus:()=>rKe,forEach:()=>aKe,insertContent:()=>iKe,insertContentAt:()=>lKe,joinBackward:()=>uKe,joinDown:()=>dKe,joinForward:()=>mKe,joinItemBackward:()=>hKe,joinItemForward:()=>pKe,joinTextblockBackward:()=>fKe,joinTextblockForward:()=>gKe,joinUp:()=>cKe,keyboardShortcut:()=>xKe,lift:()=>yKe,liftEmptyBlock:()=>vKe,liftListItem:()=>wKe,newlineInCode:()=>SKe,resetAttributes:()=>_Ke,scrollIntoView:()=>kKe,selectAll:()=>NKe,selectNodeBackward:()=>CKe,selectNodeForward:()=>PKe,selectParentNode:()=>TKe,selectTextblockEnd:()=>AKe,selectTextblockStart:()=>MKe,setContent:()=>jKe,setMark:()=>QKe,setMeta:()=>ZKe,setNode:()=>JKe,setNodeSelection:()=>eYe,setTextDirection:()=>tYe,setTextSelection:()=>nYe,sinkListItem:()=>rYe,splitBlock:()=>aYe,splitListItem:()=>iYe,toggleList:()=>sYe,toggleMark:()=>oYe,toggleNode:()=>lYe,toggleWrap:()=>cYe,undoInputRule:()=>dYe,unsetAllMarks:()=>uYe,unsetMark:()=>mYe,unsetTextDirection:()=>hYe,updateAttributes:()=>pYe,wrapIn:()=>fYe,wrapInList:()=>gYe});var HWe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),qWe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),$We=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:i}=r;return n&&i.forEach(({$from:s,$to:o})=>{t.doc.nodesBetween(s.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:d,mapping:u}=e,m=d.resolve(u.map(c)),p=d.resolve(u.map(c+l.nodeSize)),f=m.blockRange(p);if(!f)return;const y=yy(f);if(l.type.isTextblock){const{defaultType:v}=m.parent.contentMatchAt(m.index());e.setNodeMarkup(f.start,v)}(y||y===0)&&e.lift(f,y)})}),!0},VWe=t=>e=>t(e),GWe=()=>({state:t,dispatch:e})=>Mie(t,e),WWe=(t,e)=>({editor:n,tr:r})=>{const{state:i}=n,s=i.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new Bn(r.doc.resolve(Math.max(o-1,0)))),!0},KWe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const i=t.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const l=i.before(s),c=i.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function ui(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 YWe=t=>({tr:e,state:n,dispatch:r})=>{const i=ui(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const c=s.before(o),d=s.after(o);e.delete(c,d).scrollIntoView()}return!0}return!1},XWe=t=>({tr:e,dispatch:n})=>{const{from:r,to:i}=t;return n&&e.delete(r,i),!0},QWe=()=>({state:t,dispatch:e})=>iz(t,e),ZWe=()=>({commands:t})=>t.keyboardShortcut("Enter"),JWe=()=>({state:t,dispatch:e})=>L7e(t,e);function vz(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function DC(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>n.strict?e[i]===t[i]:vz(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function bse(t,e,n={}){return t.find(r=>r.type===e&&DC(Object.fromEntries(Object.keys(n).map(i=>[i,r.attrs[i]])),n))}function nY(t,e,n={}){return!!bse(t,e,n)}function wz(t,e,n){var r;if(!t||!e)return;let i=t.parent.childAfter(t.parentOffset);if((!i.node||!i.node.marks.some(u=>u.type===e))&&(i=t.parent.childBefore(t.parentOffset)),!i.node||!i.node.marks.some(u=>u.type===e)||(n=n||((r=i.node.marks[0])==null?void 0:r.attrs),!bse([...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&&nY([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c<t.parent.childCount&&nY([...t.parent.child(c).marks],e,n);)d+=t.parent.child(c).nodeSize,c+=1;return{from:l,to:d}}function um(t,e){if(typeof t=="string"){if(!e.marks[t])throw Error(`There is no mark type named '${t}'. Maybe you forgot to add the extension?`);return e.marks[t]}return t}var eKe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const s=um(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:d,to:u}=l;if(i){const m=wz(c,s,e);if(m&&m.from<=d&&m.to>=u){const p=Bn.create(o,m.from,m.to);n.setSelection(p)}}return!0},tKe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r<n.length;r+=1)if(n[r](e))return!0;return!1};function xse(t){return t instanceof Bn}function bf(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function yse(t,e=null){if(!e)return null;const n=nr.atStart(t),r=nr.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const i=n.from,s=r.to;return e==="all"?Bn.create(t,bf(0,i,s),bf(t.content.size,i,s)):Bn.create(t,bf(e,i,s),bf(e,i,s))}function rY(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function FC(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function nKe(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var rKe=(t=null,e={})=>({editor:n,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(FC()||rY())&&r.dom.focus(),nKe()&&!FC()&&!rY()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!xse(n.state.selection))return o(),!0;const l=yse(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},aKe=(t,e)=>n=>t.every((r,i)=>e(r,{...n,index:i})),iKe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),vse=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&vse(r)}return t};function ek(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 vse(n)}function bw(t,e,n){if(t instanceof Ec||t instanceof qt)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,i=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return qt.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),bw("",e,n)}if(i){if(n.errorOnInvalidContent){let o=!1,l="";const c=new rie({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?g0.fromSchema(c).parseSlice(ek(t),n.parseOptions):g0.fromSchema(c).parse(ek(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=g0.fromSchema(e);return n.slice?s.parseSlice(ek(t),n.parseOptions).content:s.parse(ek(t),n.parseOptions)}return bw("",e,n)}function sKe(t,e,n){const r=t.steps.length-1;if(r<e)return;const i=t.steps[r];if(!(i instanceof Ri||i instanceof Oi))return;const s=t.mapping.maps[r];let o=0;s.forEach((l,c,d,u)=>{o===0&&(o=u)}),t.setSelection(nr.near(t.doc.resolve(o),n))}var oKe=t=>!("type"in t),lKe=(t,e,n)=>({tr:r,dispatch:i,editor:s})=>{var o;if(i){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=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{bw(e,s.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{l=bw(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((oKe(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}=r.doc.resolve(u);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(u-=1,m+=1)}let v;if(p){if(Array.isArray(e))v=e.map(b=>b.text||"").join("");else if(e instanceof qt){let b="";e.forEach(g=>{g.text&&(b+=g.text)}),v=b}else typeof e=="object"&&e&&e.text?v=e.text:v=e;r.insertText(v,u,m)}else{v=l;const b=r.doc.resolve(u),g=b.node(),_=b.parentOffset===0,k=g.isText||g.isTextblock,P=g.content.size>0;_&&k&&P&&(u=Math.max(0,u-1)),r.replaceWith(u,m,v)}n.updateSelection&&sKe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:v}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:v})}return!0},cKe=()=>({state:t,dispatch:e})=>D7e(t,e),dKe=()=>({state:t,dispatch:e})=>F7e(t,e),uKe=()=>({state:t,dispatch:e})=>_ie(t,e),mKe=()=>({state:t,dispatch:e})=>Pie(t,e),hKe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=LT(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},pKe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=LT(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},fKe=()=>({state:t,dispatch:e})=>j7e(t,e),gKe=()=>({state:t,dispatch:e})=>E7e(t,e);function wse(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function bKe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,i,s,o;for(let l=0;l<e.length-1;l+=1){const c=e[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))FC()||wse()?o=!0:i=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),i&&(n=`Ctrl-${n}`),o&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var xKe=t=>({editor:e,view:n,tr:r,dispatch:i})=>{const s=bKe(t).split(/-(?!$)/),o=s.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,l))});return c?.steps.forEach(d=>{const u=d.map(r.mapping);u&&i&&r.maybeStep(u)}),!0};function Zh(t,e,n={}){const{from:r,to:i,empty:s}=t.selection,o=e?ui(e,t.schema):null,l=[];t.doc.nodesBetween(r,i,(m,p)=>{if(m.isText)return;const f=Math.max(r,p),y=Math.min(i,p+m.nodeSize);l.push({node:m,from:f,to:y})});const c=i-r,d=l.filter(m=>o?o.name===m.node.type.name:!0).filter(m=>DC(m.node.attrs,n,{strict:!1}));return s?!!d.length:d.reduce((m,p)=>m+p.to-p.from,0)>=c}var yKe=(t,e={})=>({state:n,dispatch:r})=>{const i=ui(t,n.schema);return Zh(n,i,e)?R7e(n,r):!1},vKe=()=>({state:t,dispatch:e})=>jie(t,e),wKe=t=>({state:e,dispatch:n})=>{const r=ui(t,e.schema);return W7e(r)(e,n)},SKe=()=>({state:t,dispatch:e})=>Aie(t,e);function $T(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function aY(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,i)=>(n.includes(i)||(r[i]=t[i]),r),{})}var _Ke=(t,e)=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=$T(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ui(t,r.schema)),l==="mark"&&(o=um(t,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{r.doc.nodesBetween(d.$from.pos,d.$to.pos,(u,m)=>{s&&s===u.type&&(c=!0,i&&n.setNodeMarkup(m,void 0,aY(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(aY(p.attrs,e))))})})}),c},kKe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),NKe=()=>({tr:t,dispatch:e})=>{if(e){const n=new sl(t.doc);t.setSelection(n)}return!0},CKe=()=>({state:t,dispatch:e})=>Nie(t,e),PKe=()=>({state:t,dispatch:e})=>Tie(t,e),TKe=()=>({state:t,dispatch:e})=>z7e(t,e),AKe=()=>({state:t,dispatch:e})=>H7e(t,e),MKe=()=>({state:t,dispatch:e})=>B7e(t,e);function yL(t,e,n={},r={}){return bw(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var jKe=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const d=yL(t,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});return o&&s.replaceWith(0,c.content.size,d).setMeta("preventUpdate",!n),!0}return o&&s.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},t,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Sse(t,e){const n=um(e,t.schema),{from:r,to:i,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,i,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function _se(t,e){const n=new yie(t);return e.forEach(r=>{r.steps.forEach(i=>{n.step(i)})}),n}function EKe(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 DKe(t,e,n){const r=[];return t.nodesBetween(e.from,e.to,(i,s)=>{n(i)&&r.push({node:i,pos:s})}),r}function FKe(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function VT(t){return e=>FKe(e.$from,t)}function Sn(t,e,n){return t.config[e]===void 0&&t.parent?Sn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?Sn(t.parent,e,n):null}):t.config[e]}function Sz(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=Sn(e,"addExtensions",n);return r?[e,...Sz(r())]:e}).flat(10)}function _z(t,e){const n=pg.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(n),i.innerHTML}function kse(t){return typeof t=="function"}function Lr(t,e=void 0,...n){return kse(t)?e?t.bind(e)(...n):t(...n):t}function RKe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Vx(t){const e=t.filter(i=>i.type==="extension"),n=t.filter(i=>i.type==="node"),r=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function Nse(t){const e=[],{nodeExtensions:n,markExtensions:r}=Vx(t),i=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage,extensions:i},c=Sn(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=Sn(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 Ga(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([i,s])=>{if(!r[i]){r[i]=s;return}if(i==="class"){const l=s?String(s).split(" "):[],c=r[i]?r[i].split(" "):[],d=l.filter(u=>!c.includes(u));r[i]=[...c,...d].join(" ")}else if(i==="style"){const l=s?s.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[i]?r[i].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[m,p]=u.split(":").map(f=>f.trim());d.set(m,p)}),l.forEach(u=>{const[m,p]=u.split(":").map(f=>f.trim());d.set(m,p)}),r[i]=Array.from(d.entries()).map(([u,m])=>`${u}: ${m}`).join("; ")}else r[i]=s}),r},{})}function xw(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>Ga(n,r),{})}function LKe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function iY(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):LKe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function sY(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&RKe(n)?!1:n!=null))}function oY(t){var e,n;const r={};return!((e=t?.attribute)!=null&&e.isRequired)&&"default"in(t?.attribute||{})&&(r.default=t.attribute.default),((n=t?.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function OKe(t,e){var n;const r=Nse(t),{nodeExtensions:i,markExtensions:s}=Vx(t),o=(n=i.find(d=>Sn(d,"topNode")))==null?void 0:n.name,l=Object.fromEntries(i.map(d=>{const u=r.filter(g=>g.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((g,_)=>{const k=Sn(_,"extendNodeSchema",m);return{...g,...k?k(d):{}}},{}),f=sY({...p,content:Lr(Sn(d,"content",m)),marks:Lr(Sn(d,"marks",m)),group:Lr(Sn(d,"group",m)),inline:Lr(Sn(d,"inline",m)),atom:Lr(Sn(d,"atom",m)),selectable:Lr(Sn(d,"selectable",m)),draggable:Lr(Sn(d,"draggable",m)),code:Lr(Sn(d,"code",m)),whitespace:Lr(Sn(d,"whitespace",m)),linebreakReplacement:Lr(Sn(d,"linebreakReplacement",m)),defining:Lr(Sn(d,"defining",m)),isolating:Lr(Sn(d,"isolating",m)),attrs:Object.fromEntries(u.map(oY))}),y=Lr(Sn(d,"parseHTML",m));y&&(f.parseDOM=y.map(g=>iY(g,u)));const v=Sn(d,"renderHTML",m);v&&(f.toDOM=g=>v({node:g,HTMLAttributes:xw(g,u)}));const b=Sn(d,"renderText",m);return b&&(f.toText=b),[d.name,f]})),c=Object.fromEntries(s.map(d=>{const u=r.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((b,g)=>{const _=Sn(g,"extendMarkSchema",m);return{...b,..._?_(d):{}}},{}),f=sY({...p,inclusive:Lr(Sn(d,"inclusive",m)),excludes:Lr(Sn(d,"excludes",m)),group:Lr(Sn(d,"group",m)),spanning:Lr(Sn(d,"spanning",m)),code:Lr(Sn(d,"code",m)),attrs:Object.fromEntries(u.map(oY))}),y=Lr(Sn(d,"parseHTML",m));y&&(f.parseDOM=y.map(b=>iY(b,u)));const v=Sn(d,"renderHTML",m);return v&&(f.toDOM=b=>v({mark:b,HTMLAttributes:xw(b,u)})),[d.name,f]}));return new rie({topNode:o,nodes:l,marks:c})}function IKe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function RC(t){return t.sort((n,r)=>{const i=Sn(n,"priority")||100,s=Sn(r,"priority")||100;return i>s?-1:i<s?1:0})}function Cse(t){const e=RC(Sz(t)),n=IKe(e.map(r=>r.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Pse(t,e,n){const{from:r,to:i}=e,{blockSeparator:s=`
  8197. `,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,i,(c,d,u,m)=>{var p;c.isBlock&&d>r&&(l+=s);const f=o?.[c.type.name];if(f)return u&&(l+=f({node:c,pos:d,parent:u,index:m,range:e})),!1;c.isText&&(l+=(p=c?.text)==null?void 0:p.slice(Math.max(r,d)-d,i-d))}),l}function zKe(t,e){const n={from:0,to:t.content.size};return Pse(t,n,e)}function Tse(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function UKe(t,e){const n=ui(e,t.schema),{from:r,to:i}=t.selection,s=[];t.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function Ase(t,e){const n=$T(typeof e=="string"?e:e.name,t.schema);return n==="node"?UKe(t,e):n==="mark"?Sse(t,e):{}}function BKe(t,e=JSON.stringify){const n={};return t.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function HKe(t){const e=BKe(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,o)=>o!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function Mse(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,c)=>{o.push({from:l,to:c})});else{const{from:l,to:c}=n[s];if(l===void 0||c===void 0)return;o.push({from:l,to:c})}o.forEach(({from:l,to:c})=>{const d=e.slice(s).map(l,-1),u=e.slice(s).map(c),m=e.invert().map(d,-1),p=e.invert().map(u);r.push({oldRange:{from:m,to:p},newRange:{from:d,to:u}})})}),HKe(r)}function kz(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(i=>{const s=n.resolve(t),o=wz(s,i.type);o&&r.push({mark:i,...o})}):n.nodesBetween(t,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}var qKe=(t,e,n,r=20)=>{const i=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function tk(t,e){return e.nodes[t]||e.marks[t]||null}function Uk(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const i=t.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}var $Ke=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var c,d;const u=((d=(c=i.type.spec).toText)==null?void 0:d.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";n+=i.isAtom&&!i.isText?u:u.slice(0,Math.max(0,r-s))}),n};function vL(t,e,n={}){const{empty:r,ranges:i}=t.selection,s=e?um(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(m=>s?s.name===m.type.name:!0).find(m=>DC(m.attrs,n,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:m,$to:p})=>{const f=m.pos,y=p.pos;t.doc.nodesBetween(f,y,(v,b)=>{if(!v.isText&&!v.marks.length)return;const g=Math.max(f,b),_=Math.min(y,b+v.nodeSize),k=_-g;o+=k,l.push(...v.marks.map(P=>({mark:P,from:g,to:_})))})}),o===0)return!1;const c=l.filter(m=>s?s.name===m.mark.type.name:!0).filter(m=>DC(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 VKe(t,e,n={}){if(!e)return Zh(t,null,n)||vL(t,null,n);const r=$T(e,t.schema);return r==="node"?Zh(t,e,n):r==="mark"?vL(t,e,n):!1}var GKe=(t,e)=>{const{$from:n,$to:r,$anchor:i}=t.selection;if(e){const s=VT(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},WKe=t=>{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function lY(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function cY(t,e){const{nodeExtensions:n}=Vx(e),r=n.find(o=>o.name===t);if(!r)return!1;const i={name:r.name,options:r.options,storage:r.storage},s=Lr(Sn(r,"group",i));return typeof s!="string"?!1:s.split(" ").includes("list")}function GT(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let i=!0;return t.content.forEach(s=>{i!==!1&&(GT(s,{ignoreWhitespace:n,checkChildren:e})||(i=!1))}),i}return!1}function jse(t){return t instanceof Tn}var Ese=class Dse{constructor(e){this.position=e}static fromJSON(e){return new Dse(e.position)}toJSON(){return{position:this.position}}};function KKe(t,e){const n=e.mapping.mapResult(t.position);return{position:new Ese(n.pos),mapResult:n}}function YKe(t){return new Ese(t)}function XKe(t,e,n){var r;const{selection:i}=e;let s=null;if(xse(i)&&(s=i.$cursor),s){const l=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(d=>d.type.excludes(n)))}const{ranges:o}=i;return o.some(({$from:l,$to:c})=>{let d=l.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(l.pos,c.pos,(u,m,p)=>{if(d)return!1;if(u.isInline){const f=!p||p.type.allowsMarkType(n),y=!!n.isInSet(u.marks)||!u.marks.some(v=>v.type.excludes(n));d=f&&y}return!d}),d})}var QKe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=um(t,r.schema);if(i)if(o){const d=Sse(r,c);n.addStoredMark(c.create({...d,...e}))}else l.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;r.doc.nodesBetween(u,m,(p,f)=>{const y=Math.max(f,u),v=Math.min(f+p.nodeSize,m);p.marks.find(g=>g.type===c)?p.marks.forEach(g=>{c===g.type&&n.addMark(y,v,c.create({...g.attrs,...e}))}):n.addMark(y,v,c.create(e))})});return XKe(r,n,c)},ZKe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),JKe=(t,e={})=>({state:n,dispatch:r,chain:i})=>{const s=ui(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})=>SK(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>SK(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},eYe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,i=bf(t,0,r.content.size),s=Tn.create(r,i);e.setSelection(s)}return!0},tYe=(t,e)=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&n.doc.nodesBetween(o,l,(c,d)=>{c.isText||n.setNodeMarkup(d,void 0,{...c.attrs,dir:t})}),!0},nYe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:i,to:s}=typeof t=="number"?{from:t,to:t}:t,o=Bn.atStart(r).from,l=Bn.atEnd(r).to,c=bf(i,o,l),d=bf(s,o,l),u=Bn.create(r,c,d);e.setSelection(u)}return!0},rYe=t=>({state:e,dispatch:n})=>{const r=ui(t,e.schema);return X7e(r)(e,n)};function dY(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(i=>e?.includes(i.type.name));t.tr.ensureMarks(r)}}var aYe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,d=i.extensionManager.attributes,u=Uk(d,l.node().type.name,l.node().attrs);if(s instanceof Tn&&s.node.isBlock)return!l.parentOffset||!Hu(o,l.pos)?!1:(r&&(t&&dY(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:EKe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let f=m&&p?[{type:p,attrs:u}]:void 0,y=Hu(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!y&&Hu(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(y=!0,f=p?[{type:p,attrs:u}]:void 0),r){if(y&&(s instanceof Bn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),p&&!m&&!l.parentOffset&&l.parent.type!==p)){const v=e.mapping.map(l.before()),b=e.doc.resolve(v);l.node(-1).canReplaceWith(b.index(),b.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&dY(n,i.extensionManager.splittableMarks),e.scrollIntoView()}return y},iYe=(t,e={})=>({tr:n,state:r,dispatch:i,editor:s})=>{var o;const l=ui(t,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==l)return!1;const p=s.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==l||c.index(-2)!==c.node(-2).childCount-1)return!1;if(i){let g=qt.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let T=c.depth-_;T>=c.depth-3;T-=1)g=qt.from(c.node(T).copy(g));const k=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,P={...Uk(p,c.node().type.name,c.node().attrs),...e},N=((o=l.contentMatch.defaultType)==null?void 0:o.createAndFill(P))||void 0;g=g.append(qt.from(l.createAndFill(null,N)||void 0));const M=c.before(c.depth-(_-1));n.replace(M,c.after(-k),new ln(g,4-_,0));let A=-1;n.doc.nodesBetween(M,n.doc.content.size,(T,C)=>{if(A>-1)return!1;T.isTextblock&&T.content.size===0&&(A=C+1)}),A>-1&&n.setSelection(Bn.near(n.doc.resolve(A))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,y={...Uk(p,m.type.name,m.attrs),...e},v={...Uk(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,d.pos);const b=f?[{type:l,attrs:y},{type:f,attrs:v}]:[{type:l,attrs:y}];if(!Hu(n.doc,c.pos,2))return!1;if(i){const{selection:g,storedMarks:_}=r,{splittableMarks:k}=s.extensionManager,P=_||g.$to.parentOffset&&g.$from.marks();if(n.split(c.pos,2,b).scrollIntoView(),!P||!i)return!0;const N=P.filter(M=>k.includes(M.type.name));n.ensureMarks(N)}return!0},qD=(t,e)=>{const n=VT(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&op(t.doc,n.pos)&&t.join(n.pos),!0},$D=(t,e)=>{const n=VT(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&op(t.doc,r)&&t.join(r),!0},sYe=(t,e,n,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:c,commands:d,can:u})=>{const{extensions:m,splittableMarks:p}=i.extensionManager,f=ui(t,o.schema),y=ui(e,o.schema),{selection:v,storedMarks:b}=o,{$from:g,$to:_}=v,k=g.blockRange(_),P=b||v.$to.parentOffset&&v.$from.marks();if(!k)return!1;const N=VT(M=>cY(M.type.name,m))(v);if(k.depth>=1&&N&&k.depth-N.depth<=1){if(N.node.type===f)return d.liftListItem(y);if(cY(N.node.type.name,m)&&f.validContent(N.node.content)&&l)return c().command(()=>(s.setNodeMarkup(N.pos,f),!0)).command(()=>qD(s,f)).command(()=>$D(s,f)).run()}return!n||!P||!l?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>qD(s,f)).command(()=>$D(s,f)).run():c().command(()=>{const M=u().wrapInList(f,r),A=P.filter(T=>p.includes(T.type.name));return s.ensureMarks(A),M?!0:d.clearNodes()}).wrapInList(f,r).command(()=>qD(s,f)).command(()=>$D(s,f)).run()},oYe=(t,e={},n={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=n,o=um(t,r.schema);return vL(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},lYe=(t,e,n={})=>({state:r,commands:i})=>{const s=ui(t,r.schema),o=ui(e,r.schema),l=Zh(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?i.setNode(o,c):i.setNode(s,{...c,...n})},cYe=(t,e={})=>({state:n,commands:r})=>{const i=ui(t,n.schema);return Zh(n,i,e)?r.lift(i):r.wrapIn(i,e)},dYe=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const i=n[r];let s;if(i.spec.isInputRules&&(s=i.getState(t))){if(e){const o=t.tr,l=s.transform;for(let c=l.steps.length-1;c>=0;c-=1)o.step(l.steps[c].invert(l.docs[c]));if(s.text){const c=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,t.schema.text(s.text,c))}else o.delete(s.from,s.to)}return!0}}return!1},uYe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:i}=n;return r||e&&i.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},mYe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=um(t,r.schema),{$from:d,empty:u,ranges:m}=l;if(!i)return!0;if(u&&o){let{from:p,to:f}=l;const y=(s=d.marks().find(b=>b.type===c))==null?void 0:s.attrs,v=wz(d,c,y);v&&(p=v.from,f=v.to),n.removeMark(p,f,c)}else m.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},hYe=t=>({tr:e,state:n,dispatch:r})=>{const{selection:i}=n;let s,o;return typeof t=="number"?(s=t,o=t):t&&"from"in t&&"to"in t?(s=t.from,o=t.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,c)=>{if(l.isText)return;const d={...l.attrs};delete d.dir,e.setNodeMarkup(c,void 0,d)}),!0},pYe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=$T(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ui(t,r.schema)),l==="mark"&&(o=um(t,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;let p,f,y,v;n.selection.empty?r.doc.nodesBetween(u,m,(b,g)=>{s&&s===b.type&&(c=!0,y=Math.max(g,u),v=Math.min(g+b.nodeSize,m),p=g,f=b)}):r.doc.nodesBetween(u,m,(b,g)=>{g<u&&s&&s===b.type&&(c=!0,y=Math.max(g,u),v=Math.min(g+b.nodeSize,m),p=g,f=b),g>=u&&g<=m&&(s&&s===b.type&&(c=!0,i&&n.setNodeMarkup(g,void 0,{...b.attrs,...e})),o&&b.marks.length&&b.marks.forEach(_=>{if(o===_.type&&(c=!0,i)){const k=Math.max(g,u),P=Math.min(g+b.nodeSize,m);n.addMark(k,P,o.create({..._.attrs,...e}))}}))}),f&&(p!==void 0&&i&&n.setNodeMarkup(p,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(b=>{o===b.type&&i&&n.addMark(y,v,o.create({...b.attrs,...e}))}))}),c},fYe=(t,e={})=>({state:n,dispatch:r})=>{const i=ui(t,n.schema);return q7e(i,e)(n,r)},gYe=(t,e={})=>({state:n,dispatch:r})=>{const i=ui(t,n.schema);return $7e(i,e)(n,r)},bYe=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},WT=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},xYe=(t,e)=>{if(vz(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function nk(t){var e;const{editor:n,from:r,to:i,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||(e=d.nodeBefore||d.nodeAfter)!=null&&e.marks.find(p=>p.type.spec.code))return!1;let u=!1;const m=$Ke(d)+s;return o.forEach(p=>{if(u)return;const f=xYe(m,p.find);if(!f)return;const y=c.state.tr,v=HT({state:c.state,transaction:y}),b={from:r-(f[0].length-s.length),to:i},{commands:g,chain:_,can:k}=new qT({editor:n,state:v});p.handler({state:v,range:b,match:f,commands:g,chain:_,can:k})===null||!y.steps.length||(p.undoable&&y.setMeta(l,{transform:y,from:r,to:i,text:s}),c.dispatch(y),u=!0)}),u}function yYe(t){const{editor:e,rules:n}=t,r=new Ma({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const c=i.getMeta("applyInputRules");return c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=_z(qt.from(u),o.schema);const{from:m}=c,p=m+u.length;nk({editor:e,from:m,to:p,text:u,rules:n,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return nk({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&nk({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?nk({editor:e,from:o.pos,to:o.pos,text:`
  8198. `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function vYe(t){return Object.prototype.toString.call(t).slice(8,-1)}function rk(t){return vYe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function Fse(t,e){const n={...t};return rk(t)&&rk(e)&&Object.keys(e).forEach(r=>{rk(e[r])&&rk(t[r])?n[r]=Fse(t[r],e[r]):n[r]=e[r]}),n}var Nz=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{...Lr(Sn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Lr(Sn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>Fse(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}},cp=class Rse extends Nz{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new Rse(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!!!o.find(d=>d?.type.name===n.name))return!1;const c=o.find(d=>d?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function wYe(t){return typeof t=="number"}var SYe=class{constructor(t){this.find=t.find,this.handler=t.handler}},_Ye=(t,e,n)=>{if(vz(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=t,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function kYe(t){const{editor:e,state:n,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:d,can:u}=new qT({editor:e,state:n}),m=[];return n.doc.nodesBetween(r,i,(f,y)=>{var v,b,g,_,k;if((b=(v=f.type)==null?void 0:v.spec)!=null&&b.code||!(f.isText||f.isTextblock||f.isInline))return;const P=(k=(_=(g=f.content)==null?void 0:g.size)!=null?_:f.nodeSize)!=null?k:0,N=Math.max(r,y),M=Math.min(i,y+P);if(N>=M)return;const A=f.isText?f.text||"":f.textBetween(N-y,M-y,void 0,"");_Ye(A,s.find,o).forEach(C=>{if(C.index===void 0)return;const F=N+C.index+1,$=F+C[0].length,I={from:n.tr.mapping.map(F),to:n.tr.mapping.map($)},X=s.handler({state:n,range:I,match:C,commands:c,chain:d,can:u,pasteEvent:o,dropEvent:l});m.push(X)})}),m.every(f=>f!==null)}var ak=null,NYe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function CYe(t){const{editor:e,rules:n}=t;let r=null,i=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const c=({state:u,from:m,to:p,rule:f,pasteEvt:y})=>{const v=u.tr,b=HT({state:u,transaction:v});if(!(!kYe({editor:e,state:b,from:Math.max(m-1,0),to:p.b-1,rule:f,pasteEvent:y,dropEvent:l})||!v.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,v}};return n.map(u=>new Ma({view(m){const p=y=>{var v;r=(v=m.dom.parentElement)!=null&&v.contains(y.target)?m.dom.parentElement:null,r&&(ak=e)},f=()=>{ak&&(ak=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(m,p)=>{if(s=r===m.dom.parentElement,l=p,!s){const f=ak;f?.isEditable&&setTimeout(()=>{const y=f.state.selection;y&&f.commands.deleteRange({from:y.from,to:y.to})},10)}return!1},paste:(m,p)=>{var f;const y=(f=p.clipboardData)==null?void 0:f.getData("text/html");return o=p,i=!!y?.includes("data-pm-slice"),!1}}},appendTransaction:(m,p,f)=>{const y=m[0],v=y.getMeta("uiEvent")==="paste"&&!i,b=y.getMeta("uiEvent")==="drop"&&!s,g=y.getMeta("applyPasteRules"),_=!!g;if(!v&&!b&&!_)return;if(_){let{text:N}=g;typeof N=="string"?N=N:N=_z(qt.from(N),f.schema);const{from:M}=g,A=M+N.length,T=NYe(N);return c({rule:u,state:f,from:M,to:{b:A},pasteEvt:T})}const k=p.doc.content.findDiffStart(f.doc.content),P=p.doc.content.findDiffEnd(f.doc.content);if(!(!wYe(k)||!P||k===P.b))return c({rule:u,state:f,from:k,to:P,pasteEvt:o})}}))}var KT=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Cse(t),this.schema=OKe(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:tk(e.name,this.schema)},r=Sn(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return RC([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:tk(r.name,this.schema)},s=[],o=Sn(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&Sn(r,"exitable",i)&&(l.ArrowRight=()=>cp.handleExit({editor:t,mark:r})),o){const p=Object.fromEntries(Object.entries(o()).map(([f,y])=>[f,()=>y({editor:t})]));l={...l,...p}}const c=UWe(l);s.push(c);const d=Sn(r,"addInputRules",i);if(lY(r,t.options.enableInputRules)&&d){const p=d();if(p&&p.length){const f=yYe({editor:t,rules:p}),y=Array.isArray(f)?f:[f];s.push(...y)}}const u=Sn(r,"addPasteRules",i);if(lY(r,t.options.enablePasteRules)&&u){const p=u();if(p&&p.length){const f=CYe({editor:t,rules:p});s.push(...f)}}const m=Sn(r,"addProseMirrorPlugins",i);if(m){const p=m();s.push(...p)}return s})}get attributes(){return Nse(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Vx(this.extensions);return Object.fromEntries(e.filter(n=>!!Sn(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:ui(n.name,this.schema)},s=Sn(n,"addNodeView",i);if(!s)return[];const o=s();if(!o)return[];const l=(c,d,u,m,p)=>{const f=xw(c,r);return o({node:c,view:d,getPos:u,decorations:m,innerDecorations:p,editor:t,extension:n,HTMLAttributes:f})};return[n.name,l]}))}dispatchTransaction(t){const{editor:e}=this;return RC([...this.extensions].reverse()).reduceRight((r,i)=>{const s={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:tk(i.name,this.schema)},o=Sn(i,"dispatchTransaction",s);return o?l=>{o.call(s,{transaction:l,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Vx(this.extensions);return Object.fromEntries(e.filter(n=>!!Sn(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:um(n.name,this.schema)},s=Sn(n,"addMarkView",i);if(!s)return[];const o=(l,c,d)=>{const u=xw(l,r);return s()({mark:l,view:c,inline:d,editor:t,extension:n,HTMLAttributes:u,updateAttributes:m=>{BYe(l,t,m)}})};return[n.name,o]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:tk(e.name,this.schema)};e.type==="mark"&&((n=Lr(Sn(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const i=Sn(e,"onBeforeCreate",r),s=Sn(e,"onCreate",r),o=Sn(e,"onUpdate",r),l=Sn(e,"onSelectionUpdate",r),c=Sn(e,"onTransaction",r),d=Sn(e,"onFocus",r),u=Sn(e,"onBlur",r),m=Sn(e,"onDestroy",r);i&&this.editor.on("beforeCreate",i),s&&this.editor.on("create",s),o&&this.editor.on("update",o),l&&this.editor.on("selectionUpdate",l),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),m&&this.editor.on("destroy",m)})}};KT.resolve=Cse;KT.sort=RC;KT.flatten=Sz;var PYe={};yz(PYe,{ClipboardTextSerializer:()=>Ose,Commands:()=>Ise,Delete:()=>zse,Drop:()=>Use,Editable:()=>Bse,FocusEvents:()=>qse,Keymap:()=>$se,Paste:()=>Vse,Tabindex:()=>Gse,TextDirection:()=>Wse,focusEventsPluginKey:()=>Hse});var Yr=class Lse extends Nz{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Lse(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},Ose=Yr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Ma({key:new Ni("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:i}=e,{ranges:s}=i,o=Math.min(...s.map(u=>u.$from.pos)),l=Math.max(...s.map(u=>u.$to.pos)),c=Tse(n);return Pse(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),Ise=Yr.create({name:"commands",addCommands(){return{...gse}}}),zse=Yr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,i;const s=()=>{var o,l,c,d;if((d=(c=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:c.call(l,t))!=null?d:t.getMeta("y-sync$"))return;const u=_se(t.before,[t,...e]);Mse(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,(y,v)=>{const b=v+y.nodeSize-2,g=f.oldRange.from<=v&&b<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:y,from:v,to:b,newFrom:u.mapping.map(v),newTo:u.mapping.map(b),deletedRange:f.oldRange,newRange:f.newRange,partial:!g,editor:this.editor,transaction:t,combinedTransform:u})})});const p=u.mapping;u.steps.forEach((f,y)=>{var v,b;if(f instanceof Mc){const g=p.slice(y).map(f.from,-1),_=p.slice(y).map(f.to),k=p.invert().map(g,-1),P=p.invert().map(_),N=(v=u.doc.nodeAt(g-1))==null?void 0:v.marks.some(A=>A.eq(f.mark)),M=(b=u.doc.nodeAt(_))==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:P},newRange:{from:g,to:_},partial:!!(M||N),editor:this.editor,transaction:t,combinedTransform:u})}})};(i=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||i?setTimeout(s,0):s()}}),Use=Yr.create({name:"drop",addProseMirrorPlugins(){return[new Ma({key:new Ni("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),Bse=Yr.create({name:"editable",addProseMirrorPlugins(){return[new Ma({key:new Ni("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Hse=new Ni("focusEvents"),qse=Yr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new Ma({key:Hse,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),$se=Yr.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,y=m.parent.isTextblock&&p>0?l.doc.resolve(p-1):m,v=y.parent.type.spec.isolating,b=m.pos-m.parentOffset,g=v&&y.parent.childCount===1?b===m.pos:nr.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!g||g&&m.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return FC()||wse()?s:i},addProseMirrorPlugins(){return[new Ma({key:new Ni("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(v=>v.getMeta("composition")))return;const r=t.some(v=>v.docChanged)&&!e.doc.eq(n.doc),i=t.some(v=>v.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,c=nr.atStart(e.doc).from,d=nr.atEnd(e.doc).to;if(s||!(o===c&&l===d)||!GT(n.doc))return;const p=n.tr,f=HT({state:n,transaction:p}),{commands:y}=new qT({editor:this.editor,state:f});if(y.clearNodes(),!!p.steps.length)return p}})]}}),Vse=Yr.create({name:"paste",addProseMirrorPlugins(){return[new Ma({key:new Ni("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),Gse=Yr.create({name:"tabindex",addProseMirrorPlugins(){return[new Ma({key:new Ni("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Wse=Yr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Vx(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 Ma({key:new Ni("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),TYe=class e0{constructor(e,n,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=i}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new e0(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 e0(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 e0(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const i=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=n.isInline,l=this.pos+r+(s?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const c=this.resolvedPos.doc.resolve(l);if(!i&&!o&&c.depth<=this.depth)return;const d=new e0(c,this.editor,i,i||o?n:null);i&&(d.actualDepth=this.depth+1),e.push(d)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(n).length>0){const s=i.node.attrs,o=Object.keys(n);for(let l=0;l<o.length;l+=1){const c=o[l];if(s[c]!==n[c])break}}else r=i;i=i.parent}return r}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},r=!1){let i=[];if(!this.children||this.children.length===0)return i;const s=Object.keys(n);return this.children.forEach(o=>{r&&i.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,n,r))))}),i}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},AYe=`.ProseMirror {
  8199. position: relative;
  8200. }
  8201. .ProseMirror {
  8202. word-wrap: break-word;
  8203. white-space: pre-wrap;
  8204. white-space: break-spaces;
  8205. -webkit-font-variant-ligatures: none;
  8206. font-variant-ligatures: none;
  8207. font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
  8208. }
  8209. .ProseMirror [contenteditable="false"] {
  8210. white-space: normal;
  8211. }
  8212. .ProseMirror [contenteditable="false"] [contenteditable="true"] {
  8213. white-space: pre-wrap;
  8214. }
  8215. .ProseMirror pre {
  8216. white-space: pre-wrap;
  8217. }
  8218. img.ProseMirror-separator {
  8219. display: inline !important;
  8220. border: none !important;
  8221. margin: 0 !important;
  8222. width: 0 !important;
  8223. height: 0 !important;
  8224. }
  8225. .ProseMirror-gapcursor {
  8226. display: none;
  8227. pointer-events: none;
  8228. position: absolute;
  8229. margin: 0;
  8230. }
  8231. .ProseMirror-gapcursor:after {
  8232. content: "";
  8233. display: block;
  8234. position: absolute;
  8235. top: -2px;
  8236. width: 20px;
  8237. border-top: 1px solid black;
  8238. animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
  8239. }
  8240. @keyframes ProseMirror-cursor-blink {
  8241. to {
  8242. visibility: hidden;
  8243. }
  8244. }
  8245. .ProseMirror-hideselection *::selection {
  8246. background: transparent;
  8247. }
  8248. .ProseMirror-hideselection *::-moz-selection {
  8249. background: transparent;
  8250. }
  8251. .ProseMirror-hideselection * {
  8252. caret-color: transparent;
  8253. }
  8254. .ProseMirror-focused .ProseMirror-gapcursor {
  8255. display: block;
  8256. }`;function MYe(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}var jYe=class extends bYe{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:KKe,createMappablePosition:YKe},this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:i,moved:s})=>this.options.onDrop(r,i,s)),this.on("paste",({event:r,slice:i})=>this.options.onPaste(r,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=yse(e,this.options.autofocus);this.editorState=ex.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=MYe(AYe,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=kse(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(s))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e;const r=[...this.options.enableCoreExtensions?[Bse,Ose.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),Ise,qse,$se,Gse,Use,Vse,zse,Wse.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 KT(r,this)}createCommandManager(){this.commandManager=new qT({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=yL(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=yL(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),i=n?this.extensionManager.dispatchTransaction(r):r;this.editorView=new pse(t,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:i,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const s=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(s),this.prependClass(),this.injectCSS();const o=this.view.dom;o.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(d=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(d)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),i=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const o=n.findLast(d=>d.getMeta("focus")||d.getMeta("blur")),l=o?.getMeta("focus"),c=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),c&&this.emit("blur",{editor:this,event:c.event,transaction:o}),!(t.getMeta("preventUpdate")||!n.some(d=>d.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return Ase(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return VKe(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return _z(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=`
  8257. `,textSerializers:n={}}=t||{};return zKe(this.state.doc,{blockSeparator:e,textSerializers:{...Tse(this.schema),...n}})}get isEmpty(){return GT(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 TYe(e,this)}get $doc(){return this.$pos(0)}};function Gx(t){return new WT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=Lr(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),d=n.from+l.indexOf(o),u=d+o.length;if(kz(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(v=>v===t.type&&v!==f.mark.type)).filter(f=>f.to>d).length)return null;u<n.to&&s.delete(u,n.to),d>n.from&&s.delete(n.from+c,d);const p=n.from+c+o.length;s.addMark(n.from+c,p,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Kse(t){return new WT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=Lr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(i);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=o+d;u>l?u=l:l=u+r[1].length;const m=r[0][r[0].length-1];s.insertText(m,o+r[0].length-1),s.replaceWith(u,l,c)}else if(r[0]){const d=t.type.isInline?o:o-1;s.insert(d,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function wL(t){return new WT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=Lr(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function Wx(t){return new WT({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=Lr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),d=c&&rz(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,y=p||m.$to.parentOffset&&m.$from.marks();if(y){const v=y.filter(b=>f.includes(b.type.name));o.ensureMarks(v)}}if(t.keepAttributes){const m=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(m,s).run()}const u=o.doc.resolve(n.from-1).nodeBefore;u&&u.type===t.type&&op(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,u))&&o.join(n.from-1)},undoable:t.undoable})}var EYe=t=>"touches"in t,DYe=class{constructor(t){this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.clientX-this.startX,d=l.clientY-this.startY;this.handleResize(c,d)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const d=c.clientX-this.startX,u=c.clientY-this.startY;this.handleResize(d,u)},this.handleMouseUp=()=>{if(!this.isResizing)return;const l=this.element.offsetWidth,c=this.element.offsetHeight;this.onCommit(l,c),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,i,s,o;this.node=t.node,this.editor=t.editor,this.element=t.element,this.contentElement=t.contentElement,this.getPos=t.getPos,this.onResize=t.onResize,this.onCommit=t.onCommit,this.onUpdate=t.onUpdate,(e=t.options)!=null&&e.min&&(this.minSize={...this.minSize,...t.options.min}),(n=t.options)!=null&&n.max&&(this.maxSize=t.options.max),(r=t?.options)!=null&&r.directions&&(this.directions=t.options.directions),(i=t.options)!=null&&i.preserveAspectRatio&&(this.preserveAspectRatio=t.options.preserveAspectRatio),(s=t.options)!=null&&s.className&&(this.classNames={container:t.options.className.container||"",wrapper:t.options.className.wrapper||"",handle:t.options.className.handle||"",resizing:t.options.className.resizing||""}),(o=t.options)!=null&&o.createCustomHandle&&(this.createCustomHandle=t.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var t;return(t=this.contentElement)!=null?t:null}handleEditorUpdate(){const t=this.editor.isEditable;t!==this.lastEditableState&&(this.lastEditableState=t,t?t&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}update(t,e,n){return t.type!==this.node.type?!1:(this.node=t,this.onUpdate?this.onUpdate(t,e,n):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",this.classNames.container&&(t.className=this.classNames.container),t.appendChild(this.wrapper),t}createWrapper(){const t=document.createElement("div");return t.style.position="relative",t.style.display="block",t.dataset.resizeWrapper="",this.classNames.wrapper&&(t.className=this.classNames.wrapper),t.appendChild(this.element),t}createHandle(t){const e=document.createElement("div");return e.dataset.resizeHandle=t,e.style.position="absolute",this.classNames.handle&&(e.className=this.classNames.handle),e}positionHandle(t,e){const n=e.includes("top"),r=e.includes("bottom"),i=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),i&&(t.style.left="0"),s&&(t.style.right="0"),(e==="top"||e==="bottom")&&(t.style.left="0",t.style.right="0"),(e==="left"||e==="right")&&(t.style.top="0",t.style.bottom="0")}attachHandles(){this.directions.forEach(t=>{let e;this.createCustomHandle?e=this.createCustomHandle(t):e=this.createHandle(t),e instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${t}") did not return an HTMLElement. Falling back to default handle.`),e=this.createHandle(t)),this.createCustomHandle||this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.handleMap.set(t,e),this.wrapper.appendChild(e)})}removeHandles(){this.handleMap.forEach(t=>t.remove()),this.handleMap.clear()}applyInitialSize(){const t=this.node.attrs.width,e=this.node.attrs.height;t?(this.element.style.width=`${t}px`,this.initialWidth=t):this.initialWidth=this.element.offsetWidth,e?(this.element.style.height=`${e}px`,this.initialHeight=e):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(t,e){t.preventDefault(),t.stopPropagation(),this.isResizing=!0,this.activeHandle=e,EYe(t)?(this.startX=t.touches[0].clientX,this.startY=t.touches[0].clientY):(this.startX=t.clientX,this.startY=t.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(t,e){if(!this.activeHandle)return;const n=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:i}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,i,n);this.element.style.width=`${s.width}px`,this.element.style.height=`${s.height}px`,this.onResize&&this.onResize(s.width,s.height)}calculateNewDimensions(t,e,n){let r=this.startWidth,i=this.startHeight;const s=t.includes("right"),o=t.includes("left"),l=t.includes("bottom"),c=t.includes("top");return s?r=this.startWidth+e:o&&(r=this.startWidth-e),l?i=this.startHeight+n:c&&(i=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(i=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,i,t):{width:r,height:i}}applyConstraints(t,e,n){var r,i,s,o;if(!n){let d=Math.max(this.minSize.width,t),u=Math.max(this.minSize.height,e);return(r=this.maxSize)!=null&&r.width&&(d=Math.min(this.maxSize.width,d)),(i=this.maxSize)!=null&&i.height&&(u=Math.min(this.maxSize.height,u)),{width:d,height:u}}let l=t,c=e;return l<this.minSize.width&&(l=this.minSize.width,c=l/this.aspectRatio),c<this.minSize.height&&(c=this.minSize.height,l=c*this.aspectRatio),(s=this.maxSize)!=null&&s.width&&l>this.maxSize.width&&(l=this.maxSize.width,c=l/this.aspectRatio),(o=this.maxSize)!=null&&o.height&&c>this.maxSize.height&&(c=this.maxSize.height,l=c*this.aspectRatio),{width:l,height:c}}applyAspectRatio(t,e,n){const r=n==="left"||n==="right",i=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function FYe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof Tn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var RYe={};yz(RYe,{createAtomBlockMarkdownSpec:()=>LYe,createBlockMarkdownSpec:()=>OYe,createInlineMarkdownSpec:()=>UYe,parseAttributes:()=>Cz,parseIndentedBlocks:()=>SL,renderNestedMarkdownContent:()=>Tz,serializeAttributes:()=>Pz});function Cz(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,d=>(n.push(d),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const d=i.map(u=>u.trim().slice(1));e.class=d.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,d,u])=>{var m;const p=parseInt(((m=u.match(/__QUOTED_(\d+)__/))==null?void 0:m[1])||"0",10),f=n[p];f&&(e[d]=f.slice(1,-1))});const c=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function Pz(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function LYe(t){const{nodeName:e,name:n,parseAttributes:r=Cz,serializeAttributes:i=Pz,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|$)`),y=u.match(f);if(!y)return;const v=y[1]||"",b=r(v);if(!o.find(_=>!(_ in b)))return{type:e,raw:y[0],attributes:b}}},renderMarkdown:u=>{const m=d(u.attrs||{}),p=i(m),f=p?` {${p}}`:"";return`:::${c}${f} :::`}}}function OYe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=Cz,serializeAttributes:s=Pz,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,d=n||e,u=m=>{if(!c)return m;const p={};return c.forEach(f=>{f in m&&(p[f]=m[f])}),p};return{parseMarkdown:(m,p)=>{let f;if(r){const v=r(m);f=typeof v=="string"?[{type:"text",text:v}]:v}else l==="block"?f=p.parseChildren(m.tokens||[]):f=p.parseInline(m.tokens||[]);const y={...o,...m.attributes};return p.createNode(e,y,f)},markdownTokenizer:{name:e,level:"block",start(m){var p;const f=new RegExp(`^:::${d}`,"m"),y=(p=m.match(f))==null?void 0:p.index;return y!==void 0?y:-1},tokenize(m,p,f){var y;const v=new RegExp(`^:::${d}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),b=m.match(v);if(!b)return;const[g,_=""]=b,k=i(_);let P=1;const N=g.length;let M="";const A=/^:::([\w-]*)(\s.*)?/gm,T=m.slice(N);for(A.lastIndex=0;;){const C=A.exec(T);if(C===null)break;const F=C.index,$=C[1];if(!((y=C[2])!=null&&y.endsWith(":::"))){if($)P+=1;else if(P-=1,P===0){const I=T.slice(0,F);M=I.trim();const X=m.slice(0,N+F+C[0].length);let L=[];if(M)if(l==="block")for(L=f.blockTokens(I),L.forEach(te=>{te.text&&(!te.tokens||te.tokens.length===0)&&(te.tokens=f.inlineTokens(te.text))});L.length>0;){const te=L[L.length-1];if(te.type==="paragraph"&&(!te.text||te.text.trim()===""))L.pop();else break}else L=f.inlineTokens(M);return{type:e,raw:X,attributes:k,content:M,tokens:L}}}}}},renderMarkdown:(m,p)=>{const f=u(m.attrs||{}),y=s(f),v=y?` {${y}}`:"",b=p.renderChildren(m.content||[],`
  8258. `);return`:::${d}${v}
  8259. ${b}
  8260. :::`}}}function IYe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,i,s,o]=r;e[i]=s||o,r=n.exec(t)}return e}function zYe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function UYe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=IYe,serializeAttributes:s=zYe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,d=n||e,u=p=>{if(!c)return p;const f={};return c.forEach(y=>{const v=typeof y=="string"?y:y.name,b=typeof y=="string"?void 0:y.skipIfDefault;if(v in p){const g=p[v];if(b!==void 0&&g===b)return;f[v]=g}}),f},m=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,f)=>{const y={...o,...p.attributes};if(l)return f.createNode(e,y);const v=r?r(p):p.content||"";return v?f.createNode(e,y,[f.createTextNode(v)]):f.createNode(e,y,[])},markdownTokenizer:{name:e,level:"inline",start(p){const f=l?new RegExp(`\\[${m}\\s*[^\\]]*\\]`):new RegExp(`\\[${m}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${m}\\]`),y=p.match(f),v=y?.index;return v!==void 0?v:-1},tokenize(p,f,y){const v=l?new RegExp(`^\\[${m}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${m}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${m}\\]`),b=p.match(v);if(!b)return;let g="",_="";if(l){const[,P]=b;_=P}else{const[,P,N]=b;_=P,g=N||""}const k=i(_.trim());return{type:e,raw:b[0],content:g.trim(),attributes:k}}},renderMarkdown:p=>{let f="";r?f=r(p):p.content&&p.content.length>0&&(f=p.content.filter(g=>g.type==="text").map(g=>g.text).join(""));const y=u(p.attrs||{}),v=s(y),b=v?` ${v}`:"";return l?`[${d}${b}]`:`[${d}${b}]${f}[/${d}]`}}}function SL(t,e,n){var r,i,s,o;const l=t.split(`
  8261. `),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}
  8262. `;continue}else return}const y=e.extractItemData(f),{indentLevel:v,mainContent:b}=y;d=`${d}${p}
  8263. `;const g=[b];for(u+=1;u<l.length;){const N=l[u];if(N.trim()===""){const A=l.slice(u+1).findIndex(F=>F.trim()!=="");if(A===-1)break;if((((i=(r=l[u+1+A].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:i.length)||0)>v){g.push(N),d=`${d}${N}
  8264. `,u+=1;continue}else break}if((((o=(s=N.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:o.length)||0)>v)g.push(N),d=`${d}${N}
  8265. `,u+=1;else break}let _;const k=g.slice(1);if(k.length>0){const N=k.map(M=>M.slice(v+m)).join(`
  8266. `);N.trim()&&(e.customNestedParser?_=e.customNestedParser(N):_=n.blockTokens(N))}const P=e.createToken(y,_);c.push(P)}if(c.length!==0)return{items:c,raw:d}}function Tz(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const i=typeof n=="function"?n(r):n,[s,...o]=t.content,l=e.renderChildren([s]),c=[`${i}${l}`];return o&&o.length>0&&o.forEach(d=>{const u=e.renderChildren([d]);if(u){const m=u.split(`
  8267. `).map(p=>p?e.indent(p):"").join(`
  8268. `);c.push(m)}}),c.join(`
  8269. `)}function BYe(t,e,n={}){const{state:r}=e,{doc:i,tr:s}=r,o=t;i.descendants((l,c)=>{const d=s.mapping.map(c),u=s.mapping.map(c)+l.nodeSize;let m=null;if(l.marks.forEach(f=>{if(f!==o)return!1;m=f}),!m)return;let p=!1;if(Object.keys(n).forEach(f=>{n[f]!==m.attrs[f]&&(p=!0)}),p){const f=t.type.create({...t.attrs,...n});s.removeMark(d,u,t.type),s.addMark(d,u,f)}}),s.docChanged&&e.view.dispatch(s)}var Fo=class Yse extends Nz{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Yse(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function sg(t){return new SYe({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:i})=>{const s=Lr(t.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],c=r[0];let d=n.to;if(l){const u=c.search(/\S/),m=n.from+c.indexOf(l),p=m+l.length;if(kz(n.from,n.to,e.doc).filter(y=>y.mark.type.excluded.find(b=>b===t.type&&b!==y.mark.type)).filter(y=>y.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:HYe,getOwnPropertySymbols:qYe}=Object,{hasOwnProperty:$Ye}=Object.prototype;function VD(t,e){return function(r,i,s){return t(r,i,s)&&e(r,i,s)}}function ik(t){return function(n,r,i){if(!n||!r||typeof n!="object"||typeof r!="object")return t(n,r,i);const{cache:s}=i,o=s.get(n),l=s.get(r);if(o&&l)return o===r&&l===n;s.set(n,r),s.set(r,n);const c=t(n,r,i);return s.delete(n),s.delete(r),c}}function VYe(t){return t?.[Symbol.toStringTag]}function uY(t){return HYe(t).concat(qYe(t))}const GYe=Object.hasOwn||((t,e)=>$Ye.call(t,e));function fg(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const WYe="__v",KYe="__o",YYe="_owner",{getOwnPropertyDescriptor:mY,keys:hY}=Object;function XYe(t,e){return t.byteLength===e.byteLength&&LC(new Uint8Array(t),new Uint8Array(e))}function QYe(t,e,n){let r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(!n.equals(t[r],e[r],r,r,t,e,n))return!1;return!0}function ZYe(t,e){return t.byteLength===e.byteLength&&LC(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function JYe(t,e){return fg(t.getTime(),e.getTime())}function eXe(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function tXe(t,e){return t===e}function pY(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const i=new Array(r),s=t.entries();let o,l,c=0;for(;(o=s.next())&&!o.done;){const d=e.entries();let u=!1,m=0;for(;(l=d.next())&&!l.done;){if(i[m]){m++;continue}const p=o.value,f=l.value;if(n.equals(p[0],f[0],c,m,t,e,n)&&n.equals(p[1],f[1],p[0],f[0],t,e,n)){u=i[m]=!0;break}m++}if(!u)return!1;c++}return!0}const nXe=fg;function rXe(t,e,n){const r=hY(t);let i=r.length;if(hY(e).length!==i)return!1;for(;i-- >0;)if(!Xse(t,e,n,r[i]))return!1;return!0}function Uv(t,e,n){const r=uY(t);let i=r.length;if(uY(e).length!==i)return!1;let s,o,l;for(;i-- >0;)if(s=r[i],!Xse(t,e,n,s)||(o=mY(t,s),l=mY(e,s),(o||l)&&(!o||!l||o.configurable!==l.configurable||o.enumerable!==l.enumerable||o.writable!==l.writable)))return!1;return!0}function aXe(t,e){return fg(t.valueOf(),e.valueOf())}function iXe(t,e){return t.source===e.source&&t.flags===e.flags}function fY(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const i=new Array(r),s=t.values();let o,l;for(;(o=s.next())&&!o.done;){const c=e.values();let d=!1,u=0;for(;(l=c.next())&&!l.done;){if(!i[u]&&n.equals(o.value,l.value,o.value,l.value,t,e,n)){d=i[u]=!0;break}u++}if(!d)return!1}return!0}function LC(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 sXe(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 Xse(t,e,n,r){return(r===YYe||r===KYe||r===WYe)&&(t.$$typeof||e.$$typeof)?!0:GYe(e,r)&&n.equals(t[r],e[r],r,r,t,e,n)}const oXe="[object ArrayBuffer]",lXe="[object Arguments]",cXe="[object Boolean]",dXe="[object DataView]",uXe="[object Date]",mXe="[object Error]",hXe="[object Map]",pXe="[object Number]",fXe="[object Object]",gXe="[object RegExp]",bXe="[object Set]",xXe="[object String]",yXe={"[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},vXe="[object URL]",wXe=Object.prototype.toString;function SXe({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:i,areFunctionsEqual:s,areMapsEqual:o,areNumbersEqual:l,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:m,areTypedArraysEqual:p,areUrlsEqual:f,unknownTagComparators:y}){return function(b,g,_){if(b===g)return!0;if(b==null||g==null)return!1;const k=typeof b;if(k!==typeof g)return!1;if(k!=="object")return k==="number"?l(b,g,_):k==="function"?s(b,g,_):!1;const P=b.constructor;if(P!==g.constructor)return!1;if(P===Object)return c(b,g,_);if(Array.isArray(b))return e(b,g,_);if(P===Date)return r(b,g,_);if(P===RegExp)return u(b,g,_);if(P===Map)return o(b,g,_);if(P===Set)return m(b,g,_);const N=wXe.call(b);if(N===uXe)return r(b,g,_);if(N===gXe)return u(b,g,_);if(N===hXe)return o(b,g,_);if(N===bXe)return m(b,g,_);if(N===fXe)return typeof b.then!="function"&&typeof g.then!="function"&&c(b,g,_);if(N===vXe)return f(b,g,_);if(N===mXe)return i(b,g,_);if(N===lXe)return c(b,g,_);if(yXe[N])return p(b,g,_);if(N===oXe)return t(b,g,_);if(N===dXe)return n(b,g,_);if(N===cXe||N===pXe||N===xXe)return d(b,g,_);if(y){let M=y[N];if(!M){const A=VYe(b);A&&(M=y[A])}if(M)return M(b,g,_)}return!1}}function _Xe({circular:t,createCustomConfig:e,strict:n}){let r={areArrayBuffersEqual:XYe,areArraysEqual:n?Uv:QYe,areDataViewsEqual:ZYe,areDatesEqual:JYe,areErrorsEqual:eXe,areFunctionsEqual:tXe,areMapsEqual:n?VD(pY,Uv):pY,areNumbersEqual:nXe,areObjectsEqual:n?Uv:rXe,arePrimitiveWrappersEqual:aXe,areRegExpsEqual:iXe,areSetsEqual:n?VD(fY,Uv):fY,areTypedArraysEqual:n?VD(LC,Uv):LC,areUrlsEqual:sXe,unknownTagComparators:void 0};if(e&&(r=Object.assign({},r,e(r))),t){const i=ik(r.areArraysEqual),s=ik(r.areMapsEqual),o=ik(r.areObjectsEqual),l=ik(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:i,areMapsEqual:s,areObjectsEqual:o,areSetsEqual:l})}return r}function kXe(t){return function(e,n,r,i,s,o,l){return t(e,n,l)}}function NXe({circular:t,comparator:e,createState:n,equals:r,strict:i}){if(n)return function(l,c){const{cache:d=t?new WeakMap:void 0,meta:u}=n();return e(l,c,{cache:d,equals:r,meta:u,strict:i})};if(t)return function(l,c){return e(l,c,{cache:new WeakMap,equals:r,meta:void 0,strict:i})};const s={cache:void 0,equals:r,meta:void 0,strict:i};return function(l,c){return e(l,c,s)}}const CXe=dp();dp({strict:!0});dp({circular:!0});dp({circular:!0,strict:!0});dp({createInternalComparator:()=>fg});dp({strict:!0,createInternalComparator:()=>fg});dp({circular:!0,createInternalComparator:()=>fg});dp({circular:!0,createInternalComparator:()=>fg,strict:!0});function dp(t={}){const{circular:e=!1,createInternalComparator:n,createState:r,strict:i=!1}=t,s=_Xe(t),o=SXe(s),l=n?n(o):kXe(o);return NXe({circular:e,comparator:o,createState:r,equals:l,strict:i})}var PXe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},TXe=({contentComponent:t})=>{const e=GL.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return a.jsx(a.Fragment,{children:Object.values(e)})};function AXe(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:ohe.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var MXe=class extends Qr.Component{constructor(t){var e;super(t),this.editorContentRef=Qr.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=AXe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return a.jsxs(a.Fragment,{children:[a.jsx("div",{ref:PXe(e,this.editorContentRef),...n}),t?.contentComponent&&a.jsx(TXe,{contentComponent:t.contentComponent})]})}},jXe=w.forwardRef((t,e)=>{const n=Qr.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return Qr.createElement(MXe,{key:n,innerRef:e,...t})}),Qse=Qr.memo(jXe),EXe=typeof window<"u"?w.useLayoutEffect:w.useEffect,DXe=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function FXe(t){var e;const[n]=w.useState(()=>new DXe(t.editor)),r=BJ.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:CXe);return EXe(()=>n.watch(t.editor),[t.editor,n]),w.useDebugValue(r),r}var RXe=!1,_L=typeof window>"u",LXe=_L||!!(typeof window<"u"&&window.next),OXe=class Zse{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?_L||LXe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new jYe(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((i,s)=>{var o;return i===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?Zse.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,i)=>r===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function IXe(t={},e=[]){const n=w.useRef(t);n.current=t;const[r]=w.useState(()=>new OXe(n)),i=GL.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return w.useDebugValue(i),w.useEffect(r.onRender(e)),FXe({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var Jse=w.createContext({editor:null});Jse.Consumer;var zXe=w.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),UXe=()=>w.useContext(zXe);Qr.forwardRef((t,e)=>{const{onDragStart:n}=UXe(),r=t.as||"div";return a.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});Qr.createContext({markViewContentRef:()=>{}});var Az=w.createContext({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}});Az.displayName="TiptapContext";var BXe=()=>w.useContext(Az);function eoe({editor:t,instance:e,children:n}){const r=t??e;if(!r)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const i=w.useMemo(()=>({editor:r}),[r]),s=w.useMemo(()=>({editor:r}),[r]);return a.jsx(Jse.Provider,{value:s,children:a.jsx(Az.Provider,{value:i,children:n})})}eoe.displayName="Tiptap";function toe({...t}){const{editor:e}=BXe();return a.jsx(Qse,{editor:e,...t})}toe.displayName="Tiptap.Content";Object.assign(eoe,{Content:toe});var OC=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},HXe=/^\s*>\s$/,qXe=Fo.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return OC("blockquote",{...Ga(this.options.HTMLAttributes,t),children:OC("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(`
  8270. `).map(c=>c.trim()===""?n:`${n} ${c}`);r.push(l.join(`
  8271. `))}),r.join(`
  8272. ${n}
  8273. `)},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[Wx({find:HXe,type:this.type})]}}),$Xe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,VXe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,GXe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,WXe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,KXe=cp.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 OC("strong",{...Ga(this.options.HTMLAttributes,t),children:OC("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[Gx({find:$Xe,type:this.type}),Gx({find:GXe,type:this.type})]},addPasteRules(){return[sg({find:VXe,type:this.type}),sg({find:WXe,type:this.type})]}}),YXe=/(^|[^`])`([^`]+)`(?!`)$/,XXe=/(^|[^`])`([^`]+)`(?!`)/g,QXe=cp.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",Ga(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[Gx({find:YXe,type:this.type})]},addPasteRules(){return[sg({find:XXe,type:this.type})]}}),GD=4,ZXe=/^```([a-z]+)?[\s\n]$/,JXe=/^~~~([a-z]+)?[\s\n]$/,eQe=Fo.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:GD,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",Ga(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n;return((n=t.raw)==null?void 0:n.startsWith("```"))===!1&&t.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const i=((n=t.attrs)==null?void 0:n.language)||"";return t.content?r=[`\`\`\`${i}`,e.renderChildren(t.content),"```"].join(`
  8274. `):r=`\`\`\`${i}
  8275. \`\`\``,r},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=e.pos===1;return!t||e.parent.type.name!==this.name?!1:n||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:GD,{state:r}=t,{selection:i}=r,{$from:s,empty:o}=i;if(s.parent.type!==this.type)return!1;const l=" ".repeat(n);return o?t.commands.insertContent(l):t.commands.command(({tr:c})=>{const{from:d,to:u}=i,f=r.doc.textBetween(d,u,`
  8276. `,`
  8277. `).split(`
  8278. `).map(y=>l+y).join(`
  8279. `);return c.replaceWith(d,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:GD,{state:r}=t,{selection:i}=r,{$from:s,empty:o}=i;return s.parent.type!==this.type?!1:o?t.commands.command(({tr:l})=>{var c;const{pos:d}=s,u=s.start(),m=s.end(),f=r.doc.textBetween(u,m,`
  8280. `,`
  8281. `).split(`
  8282. `);let y=0,v=0;const b=d-u;for(let M=0;M<f.length;M+=1){if(v+f[M].length>=b){y=M;break}v+=f[M].length+1}const _=((c=f[y].match(/^ */))==null?void 0:c[0])||"",k=Math.min(_.length,n);if(k===0)return!0;let P=u;for(let M=0;M<y;M+=1)P+=f[M].length+1;return l.delete(P,P+k),d-P<=k&&l.setSelection(Bn.create(l.doc,P)),!0}):t.commands.command(({tr:l})=>{const{from:c,to:d}=i,p=r.doc.textBetween(c,d,`
  8283. `,`
  8284. `).split(`
  8285. `).map(f=>{var y;const v=((y=f.match(/^ */))==null?void 0:y[0])||"",b=Math.min(v.length,n);return f.slice(b)}).join(`
  8286. `);return l.replaceWith(c,d,r.schema.text(p)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;const s=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
  8287. `);return!s||!o?!1:t.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:i,empty:s}=n;if(!s||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const l=i.after();return l===void 0?!1:r.nodeAt(l)?t.commands.command(({tr:d})=>(d.setSelection(nr.near(r.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[wL({find:ZXe,type:this.type,getAttributes:t=>({language:t[1]})}),wL({find:JXe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new Ma({key:new Ni("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!n||!s)return!1;const{tr:o,schema:l}=t.state,c=l.text(n.replace(/\r\n?/g,`
  8288. `));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(Bn.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),tQe=Fo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8289. `):""}),nQe=Fo.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",Ga(this.options.HTMLAttributes,t)]},renderText(){return`
  8290. `},renderMarkdown:()=>`
  8291. `,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&o){const m=c.filter(p=>l.includes(p.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),rQe=Fo.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]}`,Ga(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(r);return t.content?`${i} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>wL({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),aQe=Fo.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Ga(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!FYe(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return jse(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,d=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(Bn.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(Tn.create(o.doc,c.pos)):o.setSelection(Bn.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(Bn.create(o.doc,d+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Kse({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),iQe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,sQe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,oQe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,lQe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,cQe=cp.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",Ga(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[Gx({find:iQe,type:this.type}),Gx({find:oQe,type:this.type})]},addPasteRules(){return[sg({find:sQe,type:this.type}),sg({find:lQe,type:this.type})]}});const dQe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",uQe="ελ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",kL="numeric",NL="ascii",CL="alpha",v0="asciinumeric",t0="alphanumeric",PL="domain",noe="emoji",mQe="scheme",hQe="slashscheme",WD="whitespace";function pQe(t,e){return t in e||(e[t]=[]),e[t]}function xf(t,e,n){e[kL]&&(e[v0]=!0,e[t0]=!0),e[NL]&&(e[v0]=!0,e[CL]=!0),e[v0]&&(e[t0]=!0),e[CL]&&(e[t0]=!0),e[t0]&&(e[PL]=!0),e[noe]&&(e[PL]=!0);for(const r in e){const i=pQe(r,n);i.indexOf(t)<0&&i.push(t)}}function fQe(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function So(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}So.groups={};So.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;r<e.jr.length;r++){const i=e.jr[r][0],s=e.jr[r][1];if(s&&i.test(t))return s}return e.jd},has(t,e=!1){return e?t in this.j:!!this.go(t)},ta(t,e,n,r){for(let i=0;i<t.length;i++)this.tt(t[i],e,n,r)},tr(t,e,n,r){r=r||So.groups;let i;return e&&e.j?i=e:(i=new So(e),n&&r&&xf(e,n,r)),this.jr.push([t,i]),i},ts(t,e,n,r){let i=this;const s=t.length;if(!s)return i;for(let o=0;o<s-1;o++)i=i.tt(t[o]);return i.tt(t[s-1],e,n,r)},tt(t,e,n,r){r=r||So.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 So,Object.assign(o.j,l.j),o.jr.push.apply(o.jr,l.jr),o.jd=l.jd,o.t=l.t):o=new So,s){if(r)if(o.t&&typeof o.t=="string"){const c=Object.assign(fQe(o.t,r),n);xf(s,c,r)}else n&&xf(s,n,r);o.t=s}return i.j[t]=o,o}};const Zn=(t,e,n,r,i)=>t.ta(e,n,r,i),Fa=(t,e,n,r,i)=>t.tr(e,n,r,i),gY=(t,e,n,r,i)=>t.ts(e,n,r,i),Gt=(t,e,n,r,i)=>t.tt(e,n,r,i),yu="WORD",TL="UWORD",roe="ASCIINUMERICAL",aoe="ALPHANUMERICAL",yw="LOCALHOST",AL="TLD",ML="UTLD",Bk="SCHEME",Vb="SLASH_SCHEME",Mz="NUM",jL="WS",jz="NL",w0="OPENBRACE",S0="CLOSEBRACE",IC="OPENBRACKET",zC="CLOSEBRACKET",UC="OPENPAREN",BC="CLOSEPAREN",HC="OPENANGLEBRACKET",qC="CLOSEANGLEBRACKET",$C="FULLWIDTHLEFTPAREN",VC="FULLWIDTHRIGHTPAREN",GC="LEFTCORNERBRACKET",WC="RIGHTCORNERBRACKET",KC="LEFTWHITECORNERBRACKET",YC="RIGHTWHITECORNERBRACKET",XC="FULLWIDTHLESSTHAN",QC="FULLWIDTHGREATERTHAN",ZC="AMPERSAND",JC="APOSTROPHE",eP="ASTERISK",lh="AT",tP="BACKSLASH",nP="BACKTICK",rP="CARET",ph="COLON",Ez="COMMA",aP="DOLLAR",id="DOT",iP="EQUALS",Dz="EXCLAMATION",Ml="HYPHEN",_0="PERCENT",sP="PIPE",oP="PLUS",lP="POUND",k0="QUERY",Fz="QUOTE",ioe="FULLWIDTHMIDDLEDOT",Rz="SEMI",sd="SLASH",N0="TILDE",cP="UNDERSCORE",soe="EMOJI",dP="SYM";var ooe=Object.freeze({__proto__:null,ALPHANUMERICAL:aoe,AMPERSAND:ZC,APOSTROPHE:JC,ASCIINUMERICAL:roe,ASTERISK:eP,AT:lh,BACKSLASH:tP,BACKTICK:nP,CARET:rP,CLOSEANGLEBRACKET:qC,CLOSEBRACE:S0,CLOSEBRACKET:zC,CLOSEPAREN:BC,COLON:ph,COMMA:Ez,DOLLAR:aP,DOT:id,EMOJI:soe,EQUALS:iP,EXCLAMATION:Dz,FULLWIDTHGREATERTHAN:QC,FULLWIDTHLEFTPAREN:$C,FULLWIDTHLESSTHAN:XC,FULLWIDTHMIDDLEDOT:ioe,FULLWIDTHRIGHTPAREN:VC,HYPHEN:Ml,LEFTCORNERBRACKET:GC,LEFTWHITECORNERBRACKET:KC,LOCALHOST:yw,NL:jz,NUM:Mz,OPENANGLEBRACKET:HC,OPENBRACE:w0,OPENBRACKET:IC,OPENPAREN:UC,PERCENT:_0,PIPE:sP,PLUS:oP,POUND:lP,QUERY:k0,QUOTE:Fz,RIGHTCORNERBRACKET:WC,RIGHTWHITECORNERBRACKET:YC,SCHEME:Bk,SEMI:Rz,SLASH:sd,SLASH_SCHEME:Vb,SYM:dP,TILDE:N0,TLD:AL,UNDERSCORE:cP,UTLD:ML,UWORD:TL,WORD:yu,WS:jL});const pu=/[a-z]/,Bv=new RegExp("\\p{L}","u"),KD=new RegExp("\\p{Emoji}","u"),fu=/\d/,YD=/\s/,bY="\r",XD=`
  8292. `,gQe="️",bQe="‍",QD="";let sk=null,ok=null;function xQe(t=[]){const e={};So.groups=e;const n=new So;sk==null&&(sk=xY(dQe)),ok==null&&(ok=xY(uQe)),Gt(n,"'",JC),Gt(n,"{",w0),Gt(n,"}",S0),Gt(n,"[",IC),Gt(n,"]",zC),Gt(n,"(",UC),Gt(n,")",BC),Gt(n,"<",HC),Gt(n,">",qC),Gt(n,"(",$C),Gt(n,")",VC),Gt(n,"「",GC),Gt(n,"」",WC),Gt(n,"『",KC),Gt(n,"』",YC),Gt(n,"<",XC),Gt(n,">",QC),Gt(n,"&",ZC),Gt(n,"*",eP),Gt(n,"@",lh),Gt(n,"`",nP),Gt(n,"^",rP),Gt(n,":",ph),Gt(n,",",Ez),Gt(n,"$",aP),Gt(n,".",id),Gt(n,"=",iP),Gt(n,"!",Dz),Gt(n,"-",Ml),Gt(n,"%",_0),Gt(n,"|",sP),Gt(n,"+",oP),Gt(n,"#",lP),Gt(n,"?",k0),Gt(n,'"',Fz),Gt(n,"/",sd),Gt(n,";",Rz),Gt(n,"~",N0),Gt(n,"_",cP),Gt(n,"\\",tP),Gt(n,"・",ioe);const r=Fa(n,fu,Mz,{[kL]:!0});Fa(r,fu,r);const i=Fa(r,pu,roe,{[v0]:!0}),s=Fa(r,Bv,aoe,{[t0]:!0}),o=Fa(n,pu,yu,{[NL]:!0});Fa(o,fu,i),Fa(o,pu,o),Fa(i,fu,i),Fa(i,pu,i);const l=Fa(n,Bv,TL,{[CL]:!0});Fa(l,pu),Fa(l,fu,s),Fa(l,Bv,l),Fa(s,fu,s),Fa(s,pu),Fa(s,Bv,s);const c=Gt(n,XD,jz,{[WD]:!0}),d=Gt(n,bY,jL,{[WD]:!0}),u=Fa(n,YD,jL,{[WD]:!0});Gt(n,QD,u),Gt(d,XD,c),Gt(d,QD,u),Fa(d,YD,u),Gt(u,bY),Gt(u,XD),Fa(u,YD,u),Gt(u,QD,u);const m=Fa(n,KD,soe,{[noe]:!0});Gt(m,"#"),Fa(m,KD,m),Gt(m,gQe,m);const p=Gt(m,bQe);Gt(p,"#"),Fa(p,KD,m);const f=[[pu,o],[fu,i]],y=[[pu,null],[Bv,l],[fu,s]];for(let v=0;v<sk.length;v++)Jm(n,sk[v],AL,yu,f);for(let v=0;v<ok.length;v++)Jm(n,ok[v],ML,TL,y);xf(AL,{tld:!0,ascii:!0},e),xf(ML,{utld:!0,alpha:!0},e),Jm(n,"file",Bk,yu,f),Jm(n,"mailto",Bk,yu,f),Jm(n,"http",Vb,yu,f),Jm(n,"https",Vb,yu,f),Jm(n,"ftp",Vb,yu,f),Jm(n,"ftps",Vb,yu,f),xf(Bk,{scheme:!0,ascii:!0},e),xf(Vb,{slashscheme:!0,ascii:!0},e),t=t.sort((v,b)=>v[0]>b[0]?1:-1);for(let v=0;v<t.length;v++){const b=t[v][0],_=t[v][1]?{[mQe]:!0}:{[hQe]:!0};b.indexOf("-")>=0?_[PL]=!0:pu.test(b)?fu.test(b)?_[v0]=!0:_[NL]=!0:_[kL]=!0,gY(n,b,b,_)}return gY(n,"localhost",yw,{ascii:!0}),n.jd=new So(dP),{start:n,tokens:Object.assign({groups:e},ooe)}}function loe(t,e){const n=yQe(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o<r;){let l=t,c=null,d=0,u=null,m=-1,p=-1;for(;o<r&&(c=l.go(n[o]));)l=c,l.accepts()?(m=0,p=0,u=l):m>=0&&(m+=n[o].length,p++),d+=n[o].length,s+=n[o].length,o++;s-=m,o-=p,d-=m,i.push({t:u.t,v:e.slice(s-d,s),s:s-d,e:s})}return i}function yQe(t){const e=[],n=t.length;let r=0;for(;r<n;){let i=t.charCodeAt(r),s,o=i<55296||i>56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function Jm(t,e,n,r,i){let s;const o=e.length;for(let l=0;l<o-1;l++){const c=e[l];t.j[c]?s=t.j[c]:(s=new So(r),s.jr=i.slice(),t.j[c]=s),t=s}return s=new So(n),s.jr=i.slice(),t.j[e[o-1]]=s,s}function xY(t){const e=[],n=[];let r=0,i="0123456789";for(;r<t.length;){let s=0;for(;i.indexOf(t[r+s])>=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const vw={defaultProtocol:"http",events:null,format:yY,formatHref:yY,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Lz(t,e=null){let n=Object.assign({},vw);t&&(n=Object.assign(n,t instanceof Lz?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;s<r.length;s++)i.push(r[s].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=i}Lz.prototype={o:vw,ignoreTags:[],defaultRender(t){return t},check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const r=e!=null;let i=this.o[t];return i&&(typeof i=="object"?(i=n.t in i?i[n.t]:vw[t],typeof i=="function"&&r&&(i=i(e,n))):typeof i=="function"&&r&&(i=i(e,n.t,n)),i)},getObj(t,e,n){let r=this.o[t];return typeof r=="function"&&e!=null&&(r=r(e,n.t,n)),r},render(t){const e=t.render(this);return(this.get("render",null,t)||this.defaultRender)(e,t.t,t)}};function yY(t){return t}function coe(t,e){this.t="token",this.v=t,this.tk=e}coe.prototype={isLink:!1,toString(){return this.v},toHref(t){return this.toString()},toFormattedString(t){const e=this.toString(),n=t.get("truncate",e,this),r=t.get("format",e,this);return n&&r.length>n?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=vw.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),c=t.get("target",n,e),d=t.get("rel",n,e),u=t.getObj("attributes",n,e),m=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),c&&(o.target=c),d&&(o.rel=d),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:m}}};function YT(t,e){class n extends coe{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const vY=YT("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),wY=YT("text"),vQe=YT("nl"),lk=YT("url",{isLink:!0,toHref(t=vw.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==yw&&t[1].t===ph}}),Pl=t=>new So(t);function wQe({groups:t}){const e=t.domain.concat([ZC,eP,lh,tP,nP,rP,aP,iP,Ml,Mz,_0,sP,oP,lP,sd,dP,N0,cP]),n=[JC,ph,Ez,id,Dz,_0,k0,Fz,Rz,HC,qC,w0,S0,zC,IC,UC,BC,$C,VC,GC,WC,KC,YC,XC,QC],r=[ZC,JC,eP,tP,nP,rP,aP,iP,Ml,w0,S0,_0,sP,oP,lP,k0,sd,dP,N0,cP],i=Pl(),s=Gt(i,N0);Zn(s,r,s),Zn(s,t.domain,s);const o=Pl(),l=Pl(),c=Pl();Zn(i,t.domain,o),Zn(i,t.scheme,l),Zn(i,t.slashscheme,c),Zn(o,r,s),Zn(o,t.domain,o);const d=Gt(o,lh);Gt(s,lh,d),Gt(l,lh,d),Gt(c,lh,d);const u=Gt(s,id);Zn(u,r,s),Zn(u,t.domain,s);const m=Pl();Zn(d,t.domain,m),Zn(m,t.domain,m);const p=Gt(m,id);Zn(p,t.domain,m);const f=Pl(vY);Zn(p,t.tld,f),Zn(p,t.utld,f),Gt(d,yw,f);const y=Gt(m,Ml);Gt(y,Ml,y),Zn(y,t.domain,m),Zn(f,t.domain,m),Gt(f,id,p),Gt(f,Ml,y);const v=Gt(f,ph);Zn(v,t.numeric,vY);const b=Gt(o,Ml),g=Gt(o,id);Gt(b,Ml,b),Zn(b,t.domain,o),Zn(g,r,s),Zn(g,t.domain,o);const _=Pl(lk);Zn(g,t.tld,_),Zn(g,t.utld,_),Zn(_,t.domain,o),Zn(_,r,s),Gt(_,id,g),Gt(_,Ml,b),Gt(_,lh,d);const k=Gt(_,ph),P=Pl(lk);Zn(k,t.numeric,P);const N=Pl(lk),M=Pl();Zn(N,e,N),Zn(N,n,M),Zn(M,e,N),Zn(M,n,M),Gt(_,sd,N),Gt(P,sd,N);const A=Gt(l,ph),T=Gt(c,ph),C=Gt(T,sd),F=Gt(C,sd);Zn(l,t.domain,o),Gt(l,id,g),Gt(l,Ml,b),Zn(c,t.domain,o),Gt(c,id,g),Gt(c,Ml,b),Zn(A,t.domain,N),Gt(A,sd,N),Gt(A,k0,N),Zn(F,t.domain,N),Zn(F,e,N),Gt(F,sd,N);const $=[[w0,S0],[IC,zC],[UC,BC],[HC,qC],[$C,VC],[GC,WC],[KC,YC],[XC,QC]];for(let I=0;I<$.length;I++){const[X,L]=$[I],te=Gt(N,X);Gt(M,X,te),Gt(te,L,N);const ae=Pl(lk);Zn(te,e,ae);const ee=Pl();Zn(te,n),Zn(ae,e,ae),Zn(ae,n,ee),Zn(ee,e,ae),Zn(ee,n,ee),Gt(ae,L,N),Gt(ee,L,N)}return Gt(i,yw,_),Gt(i,jz,vQe),{start:i,tokens:ooe}}function SQe(t,e,n){let r=n.length,i=0,s=[],o=[];for(;i<r;){let l=t,c=null,d=null,u=0,m=null,p=-1;for(;i<r&&!(c=l.go(n[i].t));)o.push(n[i++]);for(;i<r&&(d=c||l.go(n[i].t));)c=null,l=d,l.accepts()?(p=0,m=l):p>=0&&p++,i++,u++;if(p<0)i-=u,i<r&&(o.push(n[i]),i++);else{o.length>0&&(s.push(ZD(wY,e,o)),o=[]),i-=p,u-=p;const f=m.t,y=n.slice(i-u,i);s.push(ZD(f,e,y))}}return o.length>0&&s.push(ZD(wY,e,o)),s}function ZD(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const _Qe=typeof console<"u"&&console&&console.warn||(()=>{}),kQe="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",ma={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function NQe(){return So.groups={},ma.scanner=null,ma.parser=null,ma.tokenQueue=[],ma.pluginQueue=[],ma.customSchemes=[],ma.initialized=!1,ma}function SY(t,e=!1){if(ma.initialized&&_Qe(`linkifyjs: already initialized - will not register custom scheme "${t}" ${kQe}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format.
  8293. 1. Must only contain digits, lowercase ASCII letters or "-"
  8294. 2. Cannot start or end with "-"
  8295. 3. "-" cannot repeat`);ma.customSchemes.push([t,e])}function CQe(){ma.scanner=xQe(ma.customSchemes);for(let t=0;t<ma.tokenQueue.length;t++)ma.tokenQueue[t][1]({scanner:ma.scanner});ma.parser=wQe(ma.scanner.tokens);for(let t=0;t<ma.pluginQueue.length;t++)ma.pluginQueue[t][1]({scanner:ma.scanner,parser:ma.parser});return ma.initialized=!0,ma}function Oz(t){return ma.initialized||CQe(),SQe(ma.parser.start,t,loe(ma.scanner.start,t))}Oz.scan=loe;function doe(t,e=null,n=null){if(e&&typeof e=="object"){if(n)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);n=e,e=null}const r=new Lz(n),i=Oz(t),s=[];for(let o=0;o<i.length;o++){const l=i[o];l.isLink&&(!e||l.t===e)&&r.check(l)&&s.push(l.toFormattedObject(r))}return s}var Iz="[\0-   ᠎ -\u2029  ]",PQe=new RegExp(Iz),TQe=new RegExp(`${Iz}$`),AQe=new RegExp(Iz,"g");function MQe(t){return t.length===1?t[0].isLink:t.length===3&&t[1].isLink?["()","[]"].includes(t[0].value+t[2].value):!1}function jQe(t){return new Ma({key:new Ni("autolink"),appendTransaction:(e,n,r)=>{const i=e.some(d=>d.docChanged)&&!n.doc.eq(r.doc),s=e.some(d=>d.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=_se(n.doc,[...e]);if(Mse(l).forEach(({newRange:d})=>{const u=DKe(r.doc,d,f=>f.isTextblock);let m,p;if(u.length>1)m=u[0],p=r.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!TQe.test(f))return;m=u[0],p=r.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&p){const f=p.split(PQe).filter(Boolean);if(f.length<=0)return!1;const y=f[f.length-1],v=m.pos+p.lastIndexOf(y);if(!y)return!1;const b=Oz(y).map(g=>g.toObject(t.defaultProtocol));if(!MQe(b))return!1;b.filter(g=>g.isLink).map(g=>({...g,from:v+g.start+1,to:v+g.end+1})).filter(g=>r.schema.marks.code?!r.doc.rangeHasMark(g.from,g.to,r.schema.marks.code):!0).filter(g=>t.validate(g.value)).filter(g=>t.shouldAutoLink(g.value)).forEach(g=>{kz(g.from,g.to,r.doc).some(_=>_.mark.type===t.type)||o.addMark(g.from,g.to,t.type.create({href:g.href}))})}}),!!o.steps.length)return o}})}function EQe(t){return new Ma({key:new Ni("handleClickLink"),props:{handleClick:(e,n,r)=>{var i,s;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{const c=r.target;if(!c)return!1;const d=t.editor.view.dom;o=c.closest("a"),o&&!d.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(t.enableClickSelection&&(l=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const c=Ase(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 DQe(t){return new Ma({key:new Ni("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(u=>{c+=u.textContent});const d=doe(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 qp(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&n.push(i)}),!t||t.replace(AQe,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var uoe=cp.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"){SY(t);return}SY(t.scheme,t.optionalSlashes)})},onDestroy(){NQe()},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)=>!!qp(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=>!!qp(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=>!!qp(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Ga(this.options.HTMLAttributes,t),0]:["a",Ga(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n,r,i,s;const o=(r=(n=t.attrs)==null?void 0:n.href)!=null?r:"",l=(s=(i=t.attrs)==null?void 0:i.title)!=null?s:"",c=e.renderChildren(t);return l?`[${c}](${o} "${l}")`:`[${c}](${o})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:r=>!!qp(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!qp(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[sg({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,i=doe(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!qp(o,n),protocols:n,defaultProtocol:r}));i.length&&i.forEach(s=>{this.options.shouldAutoLink(s.value)&&e.push({text:s.value,data:{href:s.href},index:s.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push(jQe({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!qp(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(EQe({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(DQe({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),FQe=uoe,RQe=Object.defineProperty,LQe=(t,e)=>{for(var n in e)RQe(t,n,{get:e[n],enumerable:!0})},OQe="listItem",_Y="textStyle",kY=/^\s*([-+*])\s$/,moe=Fo.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",Ga(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,`
  8296. `):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(OQe,this.editor.getAttributes(_Y)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=Wx({find:kY,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Wx({find:kY,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(_Y),editor:this.editor})),[t]}}),hoe=Fo.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",Ga(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)=>Tz(t,e,r=>{var i,s;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((s=(i=r.meta)==null?void 0:i.parentAttrs)==null?void 0:s.start)||1)+r.index}. `:"- "},n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),IQe={};LQe(IQe,{findListItemPos:()=>gS,getNextListDepth:()=>zz,handleBackspace:()=>EL,handleDelete:()=>DL,hasListBefore:()=>poe,hasListItemAfter:()=>zQe,hasListItemBefore:()=>foe,listItemHasSubList:()=>goe,nextListIsDeeper:()=>boe,nextListIsHigher:()=>xoe});var gS=(t,e)=>{const{$from:n}=e.selection,r=ui(t,e.schema);let i=null,s=n.depth,o=n.pos,l=null;for(;s>0&&l===null;)i=n.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},zz=(t,e)=>{const n=gS(t,e);if(!n)return!1;const[,r]=qKe(e,t,n.$pos.pos+4);return r},poe=(t,e,n)=>{const{$anchor:r}=t.selection,i=Math.max(0,r.pos-2),s=t.doc.resolve(i).node();return!(!s||!n.includes(s.type.name))},foe=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-2);return!(i.index()===0||((n=i.nodeBefore)==null?void 0:n.type.name)!==t)},goe=(t,e,n)=>{if(!n)return!1;const r=ui(t,e.schema);let i=!1;return n.descendants(s=>{s.type===r&&(i=!0)}),i},EL=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!Zh(t.state,e)&&poe(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(!Zh(t.state,e)||!WKe(t.state))return!1;const r=gS(e,t.state);if(!r)return!1;const s=t.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=goe(e,t.state,s);return foe(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},boe=(t,e)=>{const n=zz(t,e),r=gS(t,e);return!r||!n?!1:n>r.depth},xoe=(t,e)=>{const n=zz(t,e),r=gS(t,e);return!r||!n?!1:n<r.depth},DL=(t,e)=>{if(!Zh(t.state,e)||!GKe(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:i}=n;return!n.empty&&r.sameParent(i)?!1:boe(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():xoe(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},zQe=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-r.parentOffset-2);return!(i.index()===i.parent.childCount-1||((n=i.nodeAfter)==null?void 0:n.type.name)!==t)},yoe=Yr.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&&DL(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&&DL(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&EL(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&EL(t,n,r)&&(e=!0)}),e}}}}),NY=/^(\s*)(\d+)\.\s+(.*)$/,UQe=/^\s/;function BQe(t){const e=[];let n=0,r=0;for(;n<t.length;){const i=t[n],s=i.match(NY);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(NY))break;if(f.trim()==="")p.push(f),u+=`
  8297. `,m+=1;else if(f.match(UQe))p.push(f),u+=`
  8298. ${f.slice(d+2)}`,m+=1;else break}e.push({indent:d,number:parseInt(l,10),content:u.trim(),raw:p.join(`
  8299. `)}),r=m,n=m}return[e,r]}function voe(t,e,n){var r;const i=[];let s=0;for(;s<t.length;){const o=t[s];if(o.indent===e){const l=o.content.split(`
  8300. `),c=((r=l[0])==null?void 0:r.trim())||"",d=[];c&&d.push({type:"paragraph",raw:c,tokens:n.inlineTokens(c)});const u=l.slice(1).join(`
  8301. `).trim();if(u){const f=n.blockTokens(u);d.push(...f)}let m=s+1;const p=[];for(;m<t.length&&t[m].indent>e;)p.push(t[m]),m+=1;if(p.length>0){const f=Math.min(...p.map(v=>v.indent)),y=voe(p,f,n);d.push({type:"list",ordered:!0,start:p[0].number,items:y,raw:p.map(v=>v.raw).join(`
  8302. `)})}i.push({type:"list_item",raw:o.raw,tokens:d}),s=m}else s+=1}return i}function HQe(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const r=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}var qQe="listItem",CY="textStyle",PY=/^(\d+)\.\s$/,woe=Fo.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",Ga(this.options.HTMLAttributes,n),0]:["ol",Ga(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,r=t.items?HQe(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:r}:{type:"orderedList",content:r}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8303. `):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(/^(\s*)(\d+)\.\s+/),n=e?.index;return n!==void 0?n:-1},tokenize:(t,e,n)=>{var r;const i=t.split(`
  8304. `),[s,o]=BQe(i);if(s.length===0)return;const l=voe(s,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=s[0])==null?void 0:r.number)||1,items:l,raw:i.slice(0,o).join(`
  8305. `)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(qQe,this.editor.getAttributes(CY)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=Wx({find:PY,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=Wx({find:PY,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(CY)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),$Qe=/^\s*(\[([( |x])?\])\s$/,VQe=Fo.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",Ga(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const i=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return Tz(t,e,i)},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),d=m=>{var p,f;l.ariaLabel=((f=(p=this.options.a11y)==null?void 0:p.checkboxLabel)==null?void 0:f.call(p,m,l.checked))||`Task item checkbox for ${m.textContent||"empty task item"}`};d(t),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",m=>m.preventDefault()),l.addEventListener("change",m=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:p}=m.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const y=n();if(typeof y!="number")return!1;const v=f.doc.nodeAt(y);return f.setNodeMarkup(y,void 0,{...v?.attrs,checked:p}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,p)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([m,p])=>{i.setAttribute(m,p)}),i.dataset.checked=t.attrs.checked,l.checked=t.attrs.checked,s.append(l,o),i.append(s,c),Object.entries(e).forEach(([m,p])=>{i.setAttribute(m,p)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:c,update:m=>{if(m.type!==this.type)return!1;i.dataset.checked=m.attrs.checked,l.checked=m.attrs.checked,d(m);const p=r.extensionManager.attributes,f=xw(m,p),y=new Set(Object.keys(f)),v=this.options.HTMLAttributes;return u.forEach(b=>{y.has(b)||(b in v?i.setAttribute(b,v[b]):i.removeAttribute(b))}),Object.entries(f).forEach(([b,g])=>{g==null?b in v?i.setAttribute(b,v[b]):i.removeAttribute(b):i.setAttribute(b,g)}),u=y,!0}}}},addInputRules(){return[Wx({find:$Qe,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),GQe=Fo.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",Ga(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,`
  8306. `):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return n!==void 0?n:-1},tokenize(t,e,n){const r=s=>{const o=SL(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,c)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:n.inlineTokens(l.mainContent),nestedTokens:c}),customNestedParser:r},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(s)},i=SL(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:n.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},n);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Yr.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(moe.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(hoe.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(yoe.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(woe.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(VQe.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(GQe.configure(this.options.taskList)),t}});var TY="&nbsp;",WQe=" ",KQe=Fo.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Ga(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(n.length===1&&n[0].type==="image")return e.parseChildren([n[0]]);const r=e.parseInline(n);return r.length===1&&r[0].type==="text"&&(r[0].text===TY||r[0].text===WQe)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(t,e)=>{if(!t)return"";const n=Array.isArray(t.content)?t.content:[];return n.length===0?TY:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),YQe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,XQe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,QQe=cp.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",Ga(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[Gx({find:YQe,type:this.type})]},addPasteRules(){return[sg({find:XQe,type:this.type})]}}),ZQe=Fo.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),Soe=cp.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",Ga(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()}}}),JQe=Soe;function eZe(t={}){return new Ma({view(e){return new tZe(e,t)}})}class tZe{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(n){let m=e.nodeBefore,p=e.nodeAfter;if(m||p){let f=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(f){let y=f.getBoundingClientRect(),v=m?y.bottom:y.top;m&&p&&(v=(v+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*l;r={left:y.left,right:y.right,top:v-b,bottom:v+b}}}}if(!r){let m=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*o;r={left:m.left-p,right:m.left+p,top:m.top,bottom:m.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let m=c.getBoundingClientRect(),p=m.width/c.offsetWidth,f=m.height/c.offsetHeight;d=m.left-c.scrollLeft*p,u=m.top-c.scrollTop*f}this.element.style.left=(r.left-d)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,n,e):i;if(n&&!s){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=pie(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 za extends nr{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return za.valid(r)?new za(r):nr.near(r)}content(){return ln.empty}eq(e){return e instanceof za&&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 za(e.resolve(n.pos))}getBookmark(){return new Uz(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!nZe(e)||!rZe(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let i=n.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&za.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(za.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!Tn.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*n),r=!1;continue e}break}s=o,i+=n;let l=e.doc.resolve(i);if(za.valid(l))return l}return null}}}za.prototype.visible=!1;za.findFrom=za.findGapCursorFrom;nr.jsonID("gapcursor",za);class Uz{constructor(e){this.pos=e}map(e){return new Uz(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return za.valid(n)?new za(n):nr.near(n)}}function _oe(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function nZe(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||_oe(i.type))return!0;if(i.inlineContent)return!1}}return!0}function rZe(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||_oe(i.type))return!0;if(i.inlineContent)return!1}}return!0}function aZe(){return new Ma({props:{decorations:lZe,createSelectionBetween(t,e,n){return e.pos==n.pos&&za.valid(n)?new za(n):null},handleClick:sZe,handleKeyDown:iZe,handleDOMEvents:{beforeinput:oZe}}})}const iZe=fse({ArrowLeft:ck("horiz",-1),ArrowRight:ck("horiz",1),ArrowUp:ck("vert",-1),ArrowDown:ck("vert",1)});function ck(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof Bn){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let d=za.findGapCursorFrom(l,e,c);return d?(i&&i(r.tr.setSelection(new za(d))),!0):!1}}function sZe(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!za.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});return i&&i.inside>-1&&Tn.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new za(r))),!0)}function oZe(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof za))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let i=qt.empty;for(let o=r.length-1;o>=0;o--)i=qt.from(r[o].createAndFill(null,i));let s=t.state.tr.replace(n.pos,n.pos,new ln(i,0,0));return s.setSelection(Bn.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function lZe(t){if(!(t.selection instanceof za))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",ka.create(t.doc,[Xs.widget(t.selection.head,e,{key:"gapcursor"})])}var uP=200,Ii=function(){};Ii.prototype.append=function(e){return e.length?(e=Ii.from(e),!this.length&&e||e.length<uP&&this.leafAppend(e)||this.length<uP&&e.leafPrepend(this)||this.appendInner(e)):this};Ii.prototype.prepend=function(e){return e.length?Ii.from(e).append(this):this};Ii.prototype.appendInner=function(e){return new cZe(this,e)};Ii.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?Ii.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};Ii.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Ii.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};Ii.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},n,r),i};Ii.from=function(e){return e instanceof Ii?e:e&&e.length?new koe(e):Ii.empty};var koe=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var c=s;c<o;c++)if(i(this.values[c],l+c)===!1)return!1},e.prototype.forEachInvertedInner=function(i,s,o,l){for(var c=s-1;c>=o;c--)if(i(this.values[c],l+c)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=uP)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=uP)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})(Ii);Ii.empty=new koe([]);var cZe=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,i,s,o){var l=this.left.length;if(i<l&&this.left.forEachInner(r,i,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(r,Math.min(i,l),s,o)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var s=this.left.length;return i<=s?this.left.slice(r,i):r>=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(Ii);const dZe=500;class Nc{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;n&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,c,d=[],u=[];return this.items.forEach((m,p)=>{if(!m.step){i||(i=this.remapping(r,p+1),s=i.maps.length),s--,u.push(m);return}if(i){u.push(new od(m.map));let f=m.step.map(i.slice(s)),y;f&&o.maybeStep(f).doc&&(y=o.mapping.maps[o.mapping.maps.length-1],d.push(new od(y,void 0,void 0,d.length+u.length))),s--,y&&i.appendMap(y,s)}else o.maybeStep(m.step);if(m.selection)return l=i?m.selection.map(i.slice(s)):m.selection,c=new Nc(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,r,i){let s=[],o=this.eventCount,l=this.items,c=!i&&l.length?l.get(l.length-1):null;for(let u=0;u<e.steps.length;u++){let m=e.steps[u].invert(e.docs[u]),p=new od(e.mapping.maps[u],m,n),f;(f=c&&c.merge(p))&&(p=f,u?s.pop():l=l.slice(0,l.length-1)),s.push(p),n&&(o++,n=void 0),i||(c=p)}let d=o-r.depth;return d>mZe&&(l=uZe(l,d),o-=d),new Nc(l.append(s),o)}remapping(e,n){let r=new mw;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,n),r}addMaps(e){return this.eventCount==0?this:new Nc(this.items.append(e.map(n=>new od(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(p=>{p.selection&&l--},i);let c=n;this.items.forEach(p=>{let f=s.getMirror(--c);if(f==null)return;o=Math.min(o,f);let y=s.maps[f];if(p.step){let v=e.steps[f].invert(e.docs[f]),b=p.selection&&p.selection.map(s.slice(c+1,f));b&&l++,r.push(new od(y,v,b))}else r.push(new od(y))},i);let d=[];for(let p=n;p<o;p++)d.push(new od(s.maps[p]));let u=this.items.slice(0,i).append(d).append(r),m=new Nc(u,l);return m.emptyItemCount()>dZe&&(m=m.compress(this.items.length-r.length)),m}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let c=o.step.map(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=o.selection&&o.selection.map(n.slice(r));u&&s++;let m=new od(d.invert(),c,u),p,f=i.length-1;(p=i.length&&i[f].merge(m))?i[f]=p:i.push(m)}}else o.map&&r--},this.items.length,0),new Nc(Ii.from(i.reverse()),s)}}Nc.empty=new Nc(Ii.empty,0);function uZe(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}class od{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new od(n.getMap().invert(),n,this.selection)}}}class ch{constructor(e,n,r,i,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const mZe=20;function hZe(t,e,n,r){let i=n.getMeta(Ef),s;if(i)return i.historyState;n.getMeta(gZe)&&(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(Ef))return o.getMeta(Ef).redo?new ch(t.done.addTransform(n,void 0,r,Hk(e)),t.undone,AY(n.mapping.maps),t.prevTime,t.prevComposition):new ch(t.done,t.undone.addTransform(n,void 0,r,Hk(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),c=t.prevTime==0||!o&&t.prevComposition!=l&&(t.prevTime<(n.time||0)-r.newGroupDelay||!pZe(n,t.prevRanges)),d=o?JD(t.prevRanges,n.mapping):AY(n.mapping.maps);return new ch(t.done.addTransform(n,c?e.selection.getBookmark():void 0,r,Hk(e)),Nc.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),JD(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new ch(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),JD(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function pZe(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&i>=e[s]&&(n=!0)}),n}function AY(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,s,o)=>e.push(s,o));return e}function JD(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let i=e.map(t[r],1),s=e.map(t[r+1],-1);i<=s&&n.push(i,s)}return n}function fZe(t,e,n){let r=Hk(e),i=Ef.get(e).spec.config,s=(n?t.undone:t.done).popEvent(e,r);if(!s)return null;let o=s.selection.resolve(s.transform.doc),l=(n?t.done:t.undone).addTransform(s.transform,e.selection.getBookmark(),i,r),c=new ch(n?l:s.remaining,n?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(Ef,{redo:n,historyState:c})}let e3=!1,MY=null;function Hk(t){let e=t.plugins;if(MY!=e){e3=!1,MY=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){e3=!0;break}}return e3}const Ef=new Ni("history"),gZe=new Ni("closeHistory");function bZe(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new Ma({key:Ef,state:{init(){return new ch(Nc.empty,Nc.empty,null,0,-1)},apply(e,n,r){return hZe(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,i=r=="historyUndo"?Coe:r=="historyRedo"?Poe:null;return!i||!e.editable?!1:(n.preventDefault(),i(e.state,e.dispatch))}}}})}function Noe(t,e){return(n,r)=>{let i=Ef.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let s=fZe(i,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const Coe=Noe(!1,!0),Poe=Noe(!0,!0);Yr.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new Ma({key:new Ni("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const i=this.options.limit;if(i==null||i===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>i){const o=s-i,l=0,c=o;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const d=r.tr.deleteRange(l,c);return t=!0,d}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-r,d=l-c,u=l;return e.deleteRange(d,u),!(this.storage.characters({node:e.doc})>r)}})]}});var xZe=Yr.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[eZe(this.options)]}});Yr.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Ma({key:new Ni("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!n||!r)return ka.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(Xs.node(d,d+c.nodeSize,{class:this.options.className}))}),ka.create(t,s)}}})]}});var yZe=Yr.create({name:"gapCursor",addProseMirrorPlugins(){return[aZe()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Lr(Sn(t,"allowGapCursor",n)))!=null?e:null}}}),jY="placeholder";function vZe(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}Yr.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:jY,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${vZe(this.options.dataAttribute)}`:`data-${jY}`;return[new Ma({key:new Ni("placeholder"),props:{decorations:({doc:e,selection:n})=>{const r=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:i}=n,s=[];if(!r)return null;const o=this.editor.isEmpty;return e.descendants((l,c)=>{const d=i>=c&&i<=c+l.nodeSize,u=!l.isLeaf&&GT(l);if((d||!this.options.showOnlyCurrent)&&u){const m=[this.options.emptyNodeClass];o&&m.push(this.options.emptyEditorClass);const p=Xs.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}),ka.create(e,s)}}})]}});Yr.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new Ma({key:new Ni("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||jse(n.selection)||t.view.dragging?null:ka.create(n.doc,[Xs.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function EY({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var wZe=Yr.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Ni(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(n).includes(i.name));return[new Ma({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!EY({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!EY({node:o,types:r})}}})]}}),SZe=Yr.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>Coe(t,e),redo:()=>({state:t,dispatch:e})=>Poe(t,e)}},addProseMirrorPlugins(){return[bZe(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()}}}),_Ze=Yr.create({name:"starterKit",addExtensions(){var t,e,n,r;const i=[];return this.options.bold!==!1&&i.push(KXe.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(qXe.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(moe.configure(this.options.bulletList)),this.options.code!==!1&&i.push(QXe.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(eQe.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(tQe.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(xZe.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(yZe.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(nQe.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(rQe.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(SZe.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(aQe.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(cQe.configure(this.options.italic)),this.options.listItem!==!1&&i.push(hoe.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(yoe.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&i.push(uoe.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(woe.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(KQe.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(QQe.configure(this.options.strike)),this.options.text!==!1&&i.push(ZQe.configure(this.options.text)),this.options.underline!==!1&&i.push(Soe.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&i.push(wZe.configure((r=this.options)==null?void 0:r.trailingNode)),i}}),kZe=_Ze,NZe=Yr.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")}}}),CZe=NZe,PZe=20,Toe=(t,e=0)=>{const n=[];return!t.children.length||e>PZe||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...Toe(r,e+1))}),n},TZe=t=>{if(!t.children.length)return;const e=Toe(t);e&&e.forEach(n=>{var r,i;const s=n.getAttribute("style"),o=(i=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:i.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},Aoe=cp.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&TZe(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Ga(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),AZe=Yr.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="background-color")return l.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),Moe=Yr.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="color")return l.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),MZe=Yr.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()}}}),jZe=Yr.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()}}}),EZe=Yr.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()}}});Yr.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(AZe.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(Moe.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(MZe.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(jZe.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(EZe.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(Aoe.configure(this.options.textStyle)),t}});var DZe=Moe,FZe=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,RZe=Fo.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",Ga(this.options.HTMLAttributes,t)]},parseMarkdown:(t,e)=>e.createNode("image",{src:t.href,title:t.title,alt:t.text}),renderMarkdown:t=>{var e,n,r,i,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(i=(r=t.attrs)==null?void 0:r.alt)!=null?i:"",d=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return d?`![${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:r}=this.options.resize;return({node:i,getPos:s,HTMLAttributes:o,editor:l})=>{const c=document.createElement("img");Object.entries(o).forEach(([m,p])=>{if(p!=null)switch(m){case"width":case"height":break;default:c.setAttribute(m,p);break}}),c.src=o.src;const d=new DYe({element:c,editor:l,node:i,getPos:s,onResize:(m,p)=>{c.style.width=`${m}px`,c.style.height=`${p}px`},onCommit:(m,p)=>{const f=s();f!==void 0&&this.editor.chain().setNodeSelection(f).updateAttributes(this.name,{width:m,height:p}).run()},onUpdate:(m,p,f)=>m.type===i.type,options:{directions:t,min:{width:e,height:n},preserveAspectRatio:r===!0}}),u=d.dom;return u.style.visibility="hidden",u.style.pointerEvents="none",c.onload=()=>{u.style.visibility="",u.style.pointerEvents=""},d}},addCommands(){return{setImage:t=>({commands:e})=>e.insertContent({type:this.name,attrs:t})}},addInputRules(){return[Kse({find:FZe,type:this.type,getAttributes:t=>{const[,,e,n,r]=t;return{src:n,alt:e,title:r}}})]}}),LZe=RZe;function FL({content:t,onChange:e,placeholder:n}){const{t:r}=Lt(),i=IXe({extensions:[kZe.configure({heading:!1,codeBlock:!1,code:!1}),JQe,FQe.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),CZe.configure({types:["paragraph"]}),Aoe,DZe,LZe.configure({HTMLAttributes:{style:"max-width: 100%; height: auto;"}})],content:t,onUpdate:({editor:l})=>{e(l.getHTML())},editorProps:{attributes:{class:"prose prose-invert prose-sm max-w-none focus:outline-none min-h-[120px] px-3 py-2",placeholder:n||""}}});if(!i)return null;const s=({onClick:l,isActive:c=!1,children:d,title:u})=>a.jsx("button",{type:"button",onClick:l,title:u,className:`p-1.5 rounded hover:bg-bambu-dark-tertiary transition-colors ${c?"bg-bambu-dark-tertiary text-bambu-green":"text-bambu-gray"}`,children:d}),o=()=>{const l=window.prompt("Enter URL:");l&&i.chain().focus().setLink({href:l}).run()};return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[a.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[a.jsx(s,{onClick:()=>i.chain().focus().toggleBold().run(),isActive:i.isActive("bold"),title:r("richTextEditor.bold"),children:a.jsx(ope,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleItalic().run(),isActive:i.isActive("italic"),title:r("richTextEditor.italic"),children:a.jsx(gge,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleUnderline().run(),isActive:i.isActive("underline"),title:r("richTextEditor.underline"),children:a.jsx(dxe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().toggleBulletList().run(),isActive:i.isActive("bulletList"),title:r("richTextEditor.bulletList"),children:a.jsx(Ew,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleOrderedList().run(),isActive:i.isActive("orderedList"),title:r("richTextEditor.numberedList"),children:a.jsx(nN,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("left").run(),isActive:i.isActive({textAlign:"left"}),title:r("richTextEditor.alignLeft"),children:a.jsx(nxe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("center").run(),isActive:i.isActive({textAlign:"center"}),title:r("richTextEditor.alignCenter"),children:a.jsx(Zbe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("right").run(),isActive:i.isActive({textAlign:"right"}),title:r("richTextEditor.alignRight"),children:a.jsx(exe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:o,isActive:i.isActive("link"),title:r("richTextEditor.addLink"),children:a.jsx(ny,{className:"w-4 h-4"})}),i.isActive("link")&&a.jsx(s,{onClick:()=>i.chain().focus().unsetLink().run(),title:r("richTextEditor.removeLink"),children:a.jsx(qh,{className:"w-4 h-4"})})]}),a.jsx(Qse,{editor:i})]})}function joe({archiveId:t,archiveName:e,onClose:n}){const r=mn(),[i,s]=w.useState(!1),[o,l]=w.useState(null),[c,d]=w.useState({}),{data:u,isLoading:m,error:p}=et({queryKey:["archive-project-page",t],queryFn:()=>pe.getArchiveProjectPage(t)}),f=lt({mutationFn:N=>pe.updateArchiveProjectPage(t,N),onSuccess:()=>{r.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),d({})}});w.useEffect(()=>{const N=M=>{M.key==="Escape"&&(o!==null?l(null):i?g():n())};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[o,i,n]);const y=[...u?.model_pictures||[],...u?.profile_pictures||[]],v=()=>{d({title:u?.title||"",description:u?.description||"",designer:u?.designer||"",license:u?.license||"",profile_title:u?.profile_title||"",profile_description:u?.profile_description||""}),s(!0)},b=()=>{f.mutate(c)},g=()=>{s(!1),d({})},_=N=>Bae.sanitize(N,{ALLOWED_TAGS:["p","br","b","strong","i","em","u","a","ul","ol","li","figure","img"],ALLOWED_ATTR:["href","src","target","rel","style"],ADD_ATTR:["target"]}),k=u&&(u.title||u.description||u.designer||u.profile_title||y.length>0),P=N=>{N.target===N.currentTarget&&n()};return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:P,children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&a.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[!i&&k&&a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:v,children:[a.jsx(Of,{className:"w-4 h-4 mr-1"}),"Edit"]}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:g,children:"Cancel"}),a.jsxs(Ie,{variant:"primary",size:"sm",onClick:b,disabled:f.isPending,children:[a.jsx(cs,{className:"w-4 h-4 mr-1"}),"Save"]})]}),a.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[m&&a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),p&&a.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),u&&!k&&a.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[a.jsx(Ms,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"No project page data found in this 3MF file."}),a.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),u&&k&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-4",children:[i?a.jsx("input",{type:"text",value:c.title||"",onChange:N=>d({...c,title:N.target.value}),placeholder:"Title",className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-4 py-2 text-white text-xl font-semibold"}):u.title&&a.jsx("h3",{className:"text-xl font-semibold text-white",children:u.title}),a.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wu,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.designer||"",onChange:N=>d({...c,designer:N.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.designer&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(Wu,{className:"w-4 h-4"}),a.jsx("span",{children:u.designer}),u.designer_user_id&&a.jsx("a",{href:`https://makerworld.com/en/@${u.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:a.jsx(sa,{className:"w-3 h-3"})})]}),u.creation_date&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(Wr,{className:"w-4 h-4"}),a.jsx("span",{children:u.creation_date})]}),i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ms,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.license||"",onChange:N=>d({...c,license:N.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.license&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(Ms,{className:"w-4 h-4"}),a.jsx("span",{children:u.license})]}),u.origin&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:u.origin})]})]}),(u.description||i)&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),i?a.jsx(FL,{content:c.description||"",onChange:N=>d({...c,description:N}),placeholder:"Enter description..."}):a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(u.description||"")}})]}),(u.profile_title||u.profile_description||i)&&a.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),i?a.jsxs("div",{className:"space-y-2",children:[a.jsx("input",{type:"text",value:c.profile_title||"",onChange:N=>d({...c,profile_title:N.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),a.jsx(FL,{content:c.profile_description||"",onChange:N=>d({...c,profile_description:N}),placeholder:"Profile description..."})]}):a.jsxs(a.Fragment,{children:[u.profile_title&&a.jsx("p",{className:"text-white font-medium",children:u.profile_title}),u.profile_description&&a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(u.profile_description)}}),u.profile_user_name&&a.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",u.profile_user_name]})]})]}),y.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[a.jsx(Vu,{className:"w-4 h-4"}),"Images (",y.length,")"]}),a.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:y.map((N,M)=>a.jsx("button",{onClick:()=>l(M),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:a.jsx("img",{src:N.url,alt:N.name,className:"w-full h-full object-cover"})},N.path))})]}),u.design_model_id&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("a",{href:`https://makerworld.com/en/models/${u.design_model_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-bambu-green hover:underline",children:[a.jsx(sa,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&y[o]&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[a.jsx("button",{onClick:N=>{N.stopPropagation(),l(Math.max(0,o-1))},disabled:o===0,className:"absolute left-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(ol,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:y[o].url,alt:y[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:N=>N.stopPropagation()}),a.jsx("button",{onClick:N=>{N.stopPropagation(),l(Math.min(y.length-1,o+1))},disabled:o===y.length-1,className:"absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(Va,{className:"w-6 h-6 text-white"})}),a.jsx("button",{onClick:()=>l(null),className:"absolute top-4 right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-6 h-6 text-white"})}),a.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",y.length]})]})]})}const OZe=[.25,.5,.75,1,1.5,2,3,4];function IZe({archiveId:t,timelapseSrc:e,onClose:n,onSave:r}){const{showToast:i}=xn(),s=w.useRef(null),o=w.useRef(null),[l,c]=w.useState(!1),[d,u]=w.useState(0),[m,p]=w.useState(0),[f,y]=w.useState(0),[v,b]=w.useState(0),[g,_]=w.useState(1),[k,P]=w.useState(null),[N,M]=w.useState(null),[A,T]=w.useState(.8),[C,F]=w.useState(!1),{data:$,isLoading:I}=et({queryKey:["timelapse-info",t],queryFn:()=>pe.getTimelapseInfo(t)}),{data:X}=et({queryKey:["timelapse-thumbnails",t],queryFn:()=>pe.getTimelapseThumbnails(t,15)}),L=lt({mutationFn:()=>pe.processTimelapse(t,{trimStart:f,trimEnd:v,speed:g,saveMode:"replace"},k||void 0),onSuccess:K=>{i(K.message,"success"),r?.(),n()},onError:K=>{i(K.message||"Processing failed","error")}});w.useEffect(()=>{$?.duration&&v===0&&b($.duration)},[$?.duration,v]),w.useEffect(()=>{const K=ne=>{ne.key==="Escape"&&n()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[n]),w.useEffect(()=>{const K=s.current;if(!K)return;const ne=()=>{const B=K.currentTime;u(B),B>=v&&(K.currentTime=f)},oe=()=>{p(K.duration),v===0&&b(K.duration)},be=()=>c(!0),_e=()=>c(!1);return K.addEventListener("timeupdate",ne),K.addEventListener("durationchange",oe),K.addEventListener("play",be),K.addEventListener("pause",_e),()=>{K.removeEventListener("timeupdate",ne),K.removeEventListener("durationchange",oe),K.removeEventListener("play",be),K.removeEventListener("pause",_e)}},[f,v]),w.useEffect(()=>{const K=o.current,ne=s.current;!K||!ne||!N||(K.currentTime=ne.currentTime,K.playbackRate=ne.playbackRate,l&&!C?K.play().catch(()=>{}):K.pause())},[l,N,C]),w.useEffect(()=>{o.current&&(o.current.volume=C?0:A)},[A,C]),w.useEffect(()=>{s.current&&(s.current.playbackRate=g),o.current&&(o.current.playbackRate=g)},[g]);const te=w.useCallback(()=>{const K=s.current;K&&(l?K.pause():(K.currentTime<f&&(K.currentTime=f),K.play()))},[l,f]),ae=K=>{const ne=s.current;ne&&(ne.currentTime=Math.max(f,Math.min(v,K)))},ee=K=>{const ne=K.target.files?.[0];ne&&(N&&URL.revokeObjectURL(N),P(ne),M(URL.createObjectURL(ne)))},me=()=>{N&&URL.revokeObjectURL(N),P(null),M(null)};w.useEffect(()=>()=>{N&&URL.revokeObjectURL(N)},[N]);const le=v-f,ue=le/g;return I?a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"flex items-center gap-3 text-white",children:[a.jsx(ct,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-5xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"primary",size:"sm",onClick:()=>L.mutate(),disabled:L.isPending,children:L.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),"Save"]})}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[a.jsxs("div",{className:"relative",children:[a.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:te,muted:!!N}),!l&&a.jsx("button",{onClick:te,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:a.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:a.jsx(Ds,{className:"w-8 h-8 text-white"})})}),N&&a.jsx("audio",{ref:o,src:N,loop:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(_be,{className:"w-4 h-4"}),a.jsx("span",{children:"Trim"}),a.jsxs("span",{className:"ml-auto",children:[nh(f)," - ",nh(v)," (",nh(le),")"]})]}),a.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 flex",children:X?.thumbnails.map((K,ne)=>a.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${K})`}},ne))}),a.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${f/m*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(m-v)/m*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${f/m*100}%`,right:`${(m-v)/m*100}%`}}),a.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${d/m*100}%`}}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:f,onChange:K=>{const ne=parseFloat(K.target.value);ne<v-1&&(y(ne),s.current&&s.current.currentTime<ne&&(s.current.currentTime=ne))},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 50% 0 0)"}}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:v,onChange:K=>{const ne=parseFloat(K.target.value);ne>f+1&&b(ne)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:d,onChange:K=>ae(parseFloat(K.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8307. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8308. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8309. [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("div",{className:"flex items-center justify-center gap-2",children:a.jsx("button",{onClick:te,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Fw,{className:"w-5 h-5 text-white"}):a.jsx(Ds,{className:"w-5 h-5 text-white"})})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Aw,{className:"w-4 h-4"}),a.jsx("span",{children:"Speed"}),a.jsxs("span",{className:"ml-auto",children:[g,"x (output: ",nh(ue),")"]})]}),a.jsx("div",{className:"flex gap-1",children:OZe.map(K=>a.jsxs("button",{onClick:()=>_(K),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${g===K?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[K,"x"]},K))})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(H3,{className:"w-4 h-4"}),a.jsx("span",{children:"Music Overlay"})]}),k?a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(H3,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:k.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(k.size/1024/1024).toFixed(1)," MB"]})]}),a.jsx("button",{onClick:()=>F(!C),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:C?a.jsx(yxe,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(bxe,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("input",{type:"range",min:0,max:1,step:.1,value:A,onChange:K=>T(parseFloat(K.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8310. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8311. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),a.jsx("button",{onClick:me,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:a.jsx(un,{className:"w-4 h-4 text-red-400"})})]}):a.jsxs("label",{className:"flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green/50 transition-colors",children:[a.jsx(Ca,{className:"w-8 h-8 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),a.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),a.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:ee,className:"hidden"})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Original:"})," ",nh(m)," @ ",$?.width,"x",$?.height]}),a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Output:"})," ",nh(ue)," @ ",g,"x speed",k&&" + music overlay"]})]})]}),L.isPending&&a.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[a.jsx(ct,{className:"w-12 h-12 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const zZe=[.25,.5,.75,1,1.5,2,3,4];function Eoe({src:t,title:e,downloadFilename:n,archiveId:r,onClose:i,onEdit:s}){const o=w.useRef(null),[l,c]=w.useState(!0),[d,u]=w.useState(1),[m,p]=w.useState(0),[f,y]=w.useState(0),[v,b]=w.useState(!1);w.useEffect(()=>{const M=o.current;M&&(M.playbackRate=d)},[d]),w.useEffect(()=>{const M=A=>{A.key==="Escape"&&i()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[i]),w.useEffect(()=>{const M=o.current;if(!M)return;const A=()=>p(M.currentTime),T=()=>y(M.duration),C=()=>c(!0),F=()=>c(!1);return M.addEventListener("timeupdate",A),M.addEventListener("durationchange",T),M.addEventListener("play",C),M.addEventListener("pause",F),()=>{M.removeEventListener("timeupdate",A),M.removeEventListener("durationchange",T),M.removeEventListener("play",C),M.removeEventListener("pause",F)}},[]);const g=()=>{const M=o.current;M&&(l?M.pause():M.play())},_=M=>{const A=o.current;A&&(A.currentTime=parseFloat(M.target.value))},k=()=>{const M=o.current;M&&(M.currentTime=Math.max(0,M.currentTime-5))},P=()=>{const M=o.current;M&&(M.currentTime=Math.min(f,M.currentTime+5))},N=()=>{const M=document.createElement("a");M.href=t,M.download=n,M.click()};return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),e]}),a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>b(!0),children:[a.jsx(Za,{className:"w-4 h-4"}),"Edit"]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:N,children:[a.jsx(va,{className:"w-4 h-4"}),"Download"]}),a.jsx("button",{onClick:i,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"p-4",children:[a.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:g}),a.jsxs("div",{className:"mt-4 space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:nh(m)}),a.jsx("input",{type:"range",min:0,max:f||100,value:m,onChange:_,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8312. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8313. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8314. [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("span",{className:"text-xs text-bambu-gray w-12",children:nh(f)})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:k,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:a.jsx(Rbe,{className:"w-5 h-5 text-bambu-gray"})}),a.jsx("button",{onClick:g,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Fw,{className:"w-5 h-5 text-white"}):a.jsx(Ds,{className:"w-5 h-5 text-white"})}),a.jsx("button",{onClick:P,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:a.jsx(CP,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),a.jsx("div",{className:"flex gap-1",children:zZe.map(M=>a.jsxs("button",{onClick:()=>u(M),className:`px-2 py-1 text-xs rounded transition-colors ${d===M?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[M,"x"]},M))})]})]})]})]})]}),v&&r&&a.jsx(IZe,{archiveId:r,timelapseSrc:t,onClose:()=>b(!1),onSave:s})]})}function UZe({archiveIds:t,onClose:e}){w.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:r,error:i}=et({queryKey:["archive-comparison",t],queryFn:()=>pe.compareArchives(t)});return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[90vh] flex flex-col border border-bambu-dark-tertiary",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i?a.jsxs("div",{className:"text-center py-12 text-red-400",children:[a.jsx(Ln,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"Failed to load comparison"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:i instanceof Error?i.message:"Unknown error"})]}):n?a.jsx(BZe,{comparison:n}):null}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsx(Ie,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function BZe({comparison:t}){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{className:"text-left text-sm text-bambu-gray font-medium pb-2 pr-4 min-w-[150px]",children:"Setting"}),t.archives.map(e=>a.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[a.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),a.jsx("div",{className:`text-xs ${e.status==="completed"?"text-status-ok":e.status==="failed"?"text-status-error":"text-bambu-gray"}`,children:e.status})]},e.id))]})}),a.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>a.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[a.jsx("td",{className:"py-2 pr-4 text-sm",children:a.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&a.jsx(Ln,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),a.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>a.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??a.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&a.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&a.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[a.jsx(Ln,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),a.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>a.jsxs("li",{children:[a.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&a.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[a.jsx(Kr,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[a.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),a.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?a.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>a.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[a.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",a.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):a.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:a.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function HZe(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4);if(i<1)return"Just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function qZe({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:i,isDiscarding:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(t.tags||""),[u,m]=w.useState(t.notes||""),[p,f]=w.useState(t.project_id),[y,v]=w.useState(!1);return a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(yf,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx("span",{children:_o(t.file_size)}),a.jsx("span",{children:"·"}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),HZe(t.uploaded_at)]}),t.source_ip&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?a.jsx(Yl,{className:"w-5 h-5"}):a.jsx(Fn,{className:"w-5 h-5"})}),a.jsx(Ie,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:u,project_id:p||void 0}),disabled:i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(Qs,{className:"w-4 h-4"}),"Archive"]})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>v(!0),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4 text-red-400"})})]})]}),y&&a.jsx(kn,{title:"Discard Upload",message:`Are you sure you want to discard "${t.filename}"? This cannot be undone.`,confirmText:"Discard",variant:"danger",onConfirm:()=>{r(t.id),v(!1)},onCancel:()=>v(!1)}),o&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),a.jsx("input",{type:"text",value:c,onChange: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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),a.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),a.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:[a.jsx("option",{value:"",children:"No project"}),e.map(b=>a.jsx("option",{value:b.id,children:b.name},b.id))]})]})]})]})})}function $Ze(){const t=mn(),{showToast:e}=xn(),[n,r]=w.useState(!1),[i,s]=w.useState(!1),[o,l]=w.useState(new Set),[c,d]=w.useState(new Set),{data:u,isLoading:m}=et({queryKey:["pending-uploads"],queryFn:zb.list,refetchInterval:1e4}),{data:p}=et({queryKey:["projects"],queryFn:()=>pe.getProjects()}),f=lt({mutationFn:({id:g,data:_})=>zb.archive(g,_),onMutate:({id:g})=>{l(_=>new Set(_).add(g))},onSettled:(g,_,{id:k})=>{l(P=>{const N=new Set(P);return N.delete(k),N})},onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${g.print_name}`)},onError:g=>{e(g.message||"Failed to archive","error")}}),y=lt({mutationFn:g=>zb.discard(g),onMutate:g=>{d(_=>new Set(_).add(g))},onSettled:(g,_,k)=>{d(P=>{const N=new Set(P);return N.delete(k),N})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:g=>{e(g.message||"Failed to discard","error")}}),v=lt({mutationFn:zb.archiveAll,onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${g.archived} files${g.failed>0?`, ${g.failed} failed`:""}`)},onError:g=>{e(g.message||"Failed to archive all","error")}}),b=lt({mutationFn:zb.discardAll,onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${g.discarded} files`)},onError:g=>{e(g.message||"Failed to discard all","error")}});return m?a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!u||u.length===0?null:a.jsxs("div",{className:"mb-6",children:[a.jsxs(Dt,{className:"border-l-4 border-l-yellow-500",children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ca,{className:"w-5 h-5 text-yellow-500"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",u.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:v.isPending,children:v.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(Qs,{className:"w-4 h-4"}),"Archive All"]})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:b.isPending,children:b.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(un,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),a.jsxs(Rt,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"These files were uploaded via the virtual printer. Review and archive them to add to your collection."}),a.jsx("div",{className:"space-y-3",children:u.map(g=>a.jsx(qZe,{upload:g,projects:p||[],onArchive:(_,k)=>f.mutate({id:_,data:k}),onDiscard:_=>y.mutate(_),isArchiving:o.has(g.id),isDiscarding:c.has(g.id)},g.id))})]})]}),n&&a.jsx(kn,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${u.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{v.mutate(),r(!1)},onCancel:()=>r(!1)}),i&&a.jsx(kn,{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 VZe({onClose:t}){const e=mn(),{showToast:n}=xn(),[r,i]=w.useState(""),[s,o]=w.useState(null),[l,c]=w.useState(""),[d,u]=w.useState(null),[m,p]=w.useState("count");w.useEffect(()=>{const C=F=>{F.key==="Escape"&&(s?o(null):d?u(null):t())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,s,d]);const{data:f,isLoading:y}=et({queryKey:["tags"],queryFn:pe.getTags}),v=lt({mutationFn:({oldName:C,newName:F})=>pe.renameTag(C,F),onSuccess:(C,{oldName:F,newName:$})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${F}" to "${$}" in ${C.affected} archive${C.affected!==1?"s":""}`),o(null)},onError:C=>{n(C.message||"Failed to rename tag","error")}}),b=lt({mutationFn:C=>pe.deleteTag(C),onSuccess:(C,F)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${F}" from ${C.affected} archive${C.affected!==1?"s":""}`),u(null)},onError:C=>{n(C.message||"Failed to delete tag","error")}}),g=C=>{o(C.name),c(C.name),u(null)},_=()=>{o(null),c("")},k=()=>{if(!s||!l.trim())return;const C=l.trim();if(C===s){_();return}v.mutate({oldName:s,newName:C})},P=C=>{C.key==="Enter"?(C.preventDefault(),k()):C.key==="Escape"&&(C.preventDefault(),_())},N=C=>{u(C),o(null)},M=()=>{d&&b.mutate(d)},A=f?.filter(C=>C.name.toLowerCase().includes(r.toLowerCase())).sort((C,F)=>m==="count"&&F.count-C.count||C.name.localeCompare(F.name)),T=f?.reduce((C,F)=>C+F.count,0)||0;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search tags...",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:r,onChange:C=>i(C.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:m,onChange:C=>p(C.target.value),children:[a.jsx("option",{value:"count",children:"Sort by Count"}),a.jsx("option",{value:"name",children:"Sort by Name"})]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[f.length," tag",f.length!==1?"s":""," across ",T," usage",T!==1?"s":""]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:y?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):A?.length?a.jsx("div",{className:"space-y-2",children:A.map(C=>a.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors group",children:s===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx("input",{type:"text",className:"flex-1 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-green rounded text-white text-sm focus:outline-none",value:l,onChange:F=>c(F.target.value),onKeyDown:P,autoFocus:!0}),a.jsx(Ie,{size:"sm",variant:"primary",onClick:k,disabled:!l.trim()||v.isPending,className:"p-1.5",children:v.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:_,className:"p-1.5",children:a.jsx(Bt,{className:"w-4 h-4"})})]}):d===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',C.name,'" from ',C.count," archive",C.count!==1?"s":"","?"]}),a.jsx(Ie,{size:"sm",variant:"danger",onClick:M,disabled:b.isPending,className:"p-1.5",children:b.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"})}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"p-1.5",children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.jsxs(a.Fragment,{children:[a.jsx(Gu,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-white flex-1 truncate",children:C.name}),a.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:C.count}),a.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:()=>g(C),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(C.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:a.jsx(un,{className:"w-4 h-4"})})]})]})},C.name))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsx(Ie,{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)}function Doe(t){if(!t)return;const e=t.toLowerCase();return e.endsWith(".3mf")?"3mf":e.endsWith(".stl")?"stl":e.endsWith(".gcode")||e.includes(".gcode.")?"gcode":e.split(".").pop()}async function gh(t,e,n,r){try{if(n==="source"){const{token:i}=await pe.createSourceSlicerToken(t),s=pe.getSourceSlicerDownloadUrl(t,i,e);pf(`${window.location.origin}${s}`,r)}else{const{token:i}=await pe.createArchiveSlicerToken(t),s=pe.getArchiveSlicerDownloadUrl(t,i,e);pf(`${window.location.origin}${s}`,r)}}catch{const i=n==="source"?pe.getSource3mfForSlicer(t,e):pe.getArchiveForSlicer(t,e);pf(`${window.location.origin}${i}`,r)}}function GZe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",currency:d,t:u,onNavigateToArchive:m}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const p=mn(),{showToast:f}=xn(),{hasPermission:y,canModify:v}=_r(),b=Eae(),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[A,T]=w.useState(!1),[C,F]=w.useState(!1),[$,I]=w.useState(!1),[X,L]=w.useState([]),[te,ae]=w.useState(!1),[ee,me]=w.useState(!1),[le,ue]=w.useState(!1),[K,ne]=w.useState(!1),[oe,be]=w.useState(!1),[_e,B]=w.useState(!1),[Y,D]=w.useState(!1),[j,z]=w.useState(null),[W,q]=w.useState(null),[de,O]=w.useState(!1),G=w.useRef(null),Q=w.useRef(null),V=w.useRef(null),{data:J}=et({queryKey:["archive-plates",t.id],queryFn:()=>pe.getArchivePlates(t.id),enabled:de,staleTime:300*1e3}),ie=t.duplicate_sequence??0,he=t.original_archive_id??null,fe=J?.plates??[],se=J?.is_multi_plate??!1,U=W??0,R=lt({mutationFn:()=>pe.deleteArchiveTimelapse(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseRemoved"))},onError:ce=>{f(ce.message||u("archives.toast.failedRemoveTimelapse"),"error")}}),re=lt({mutationFn:ce=>pe.uploadArchiveTimelapse(t.id,ce),onSuccess:ce=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseUploaded",{filename:ce.filename}))},onError:ce=>{f(ce.message||u("archives.toast.failedUploadTimelapse"),"error")}}),xe=lt({mutationFn:ce=>pe.uploadSource3mf(t.id,ce),onSuccess:ce=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.source3mfAttached",{filename:ce.filename}))},onError:ce=>{f(ce.message||u("archives.toast.failedUploadSource3mf"),"error")}}),we=lt({mutationFn:()=>pe.deleteSource3mf(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.source3mfRemoved"))},onError:ce=>{f(ce.message||u("archives.toast.failedRemoveSource3mf"),"error")}}),ye=lt({mutationFn:ce=>pe.uploadF3d(t.id,ce),onSuccess:ce=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.f3dAttached",{filename:ce.filename}))},onError:ce=>{f(ce.message||u("archives.toast.failedUploadF3d"),"error")}}),Ae=lt({mutationFn:()=>pe.deleteF3d(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.f3dRemoved"))},onError:ce=>{f(ce.message||u("archives.toast.failedRemoveF3d"),"error")}}),ve=lt({mutationFn:()=>pe.scanArchiveTimelapse(t.id),onSuccess:ce=>{ce.status==="attached"?(p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseAttached",{filename:ce.filename}))):ce.status==="exists"?f(u("archives.toast.timelapseAlreadyAttached")):ce.status==="not_found"&&ce.available_files&&ce.available_files.length>0?(L(ce.available_files),I(!0)):f(ce.message||u("archives.toast.noMatchingTimelapse"),"warning")},onError:ce=>{f(ce.message||u("archives.toast.failedScanTimelapse"),"error")}}),Te=lt({mutationFn:ce=>pe.selectArchiveTimelapse(t.id,ce),onSuccess:ce=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseAttached",{filename:ce.filename})),I(!1),L([])},onError:ce=>{f(ce.message||u("archives.toast.failedAttachTimelapse"),"error")}}),Fe=lt({mutationFn:()=>pe.deleteArchive(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.archiveDeleted"))},onError:()=>{f(u("archives.toast.failedDeleteArchive"),"error")}}),Ee=lt({mutationFn:()=>pe.toggleFavorite(t.id),onSuccess:ce=>{p.invalidateQueries({queryKey:["archives"]}),f(ce.is_favorite?u("archives.toast.addedToFavorites"):u("archives.toast.removedFromFavorites"))}}),{data:Se}=et({queryKey:["archive-folders",t.id],queryFn:()=>pe.getLibraryFoldersByArchive(t.id)}),je=lt({mutationFn:ce=>pe.updateArchive(t.id,{project_id:ce}),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),p.invalidateQueries({queryKey:["projects"]}),f(u("archives.toast.projectUpdated"))},onError:()=>{f(u("archives.toast.failedUpdateProject"),"error")}}),qe=ce=>{ce.preventDefault(),z({x:ce.clientX,y:ce.clientY})},Ye=[...fh(t)?[{label:u("archives.menu.print"),icon:a.jsx(Pr,{className:"w-4 h-4"}),onClick:()=>P(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:u("archives.permission.noReprint"):u("archives.card.noFileForReprint")},{label:u("archives.menu.schedule"),icon:a.jsx(Wr,{className:"w-4 h-4"}),onClick:()=>ne(!0),disabled:!t.file_path||!y("queue:create"),title:t.file_path?y("queue:create")?void 0:u("archives.permission.noAddToQueue"):u("archives.card.noFileForReprint")},{label:u("archives.menu.openInBambuStudio"),icon:a.jsx(sa,{className:"w-4 h-4"}),onClick:()=>{const ce=t.print_name||t.filename||"model";gh(t.id,ce,"file",c)},disabled:!t.file_path,title:t.file_path?void 0:u("archives.card.noFileForReprint")}]:[{label:u("archives.menu.slice"),icon:a.jsx(sa,{className:"w-4 h-4"}),onClick:()=>{const ce=t.print_name||t.filename||"model";gh(t.id,ce,"file",c)}}],{label:t.external_url?u("archives.menu.externalLink"):u("archives.menu.viewOnMakerWorld"),icon:a.jsx(yd,{className:"w-4 h-4"}),onClick:()=>{const ce=t.external_url||t.makerworld_url;ce&&window.open(ce,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.preview3d"),icon:a.jsx(si,{className:"w-4 h-4"}),onClick:()=>_(!0)},{label:u("archives.menu.viewTimelapse"),icon:a.jsx(jh,{className:"w-4 h-4"}),onClick:()=>F(!0),disabled:!t.timelapse_path},{label:u("archives.menu.scanForTimelapse"),icon:a.jsx(iN,{className:"w-4 h-4"}),onClick:()=>ve.mutate(),disabled:!t.printer_id||!!t.timelapse_path||ve.isPending||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.uploadTimelapse"),icon:a.jsx(Ca,{className:"w-4 h-4"}),onClick:()=>V.current?.click(),disabled:!!t.timelapse_path||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:u("archives.menu.removeTimelapse"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>D(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?u("archives.menu.downloadSource3mf"):u("archives.menu.uploadSource3mf"),icon:a.jsx(Jk,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?pe.downloadSource3mf(t.id).catch(ce=>{console.error("Source 3MF download failed:",ce)}):G.current?.click()},disabled:!t.source_3mf_path&&!v("archives","update",t.created_by_id),title:!t.source_3mf_path&&!v("archives","update",t.created_by_id)?u("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:u("archives.menu.replaceSource3mf"),icon:a.jsx(Ca,{className:"w-4 h-4"}),onClick:()=>G.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.removeSource3mf"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>be(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?u("archives.menu.replaceF3d"):u("archives.menu.uploadF3d"),icon:a.jsx(si,{className:"w-4 h-4"}),onClick:()=>Q.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:u("archives.menu.downloadF3d"),icon:a.jsx(va,{className:"w-4 h-4"}),onClick:()=>{pe.downloadF3d(t.id).catch(ce=>{console.error("F3D download failed:",ce)})}},{label:u("archives.menu.removeF3d"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>B(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.download"),icon:a.jsx(va,{className:"w-4 h-4"}),onClick:()=>{pe.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ce=>{console.error("Archive download failed:",ce)})},disabled:!y("archives:read"),title:y("archives:read")?void 0:u("archives.permission.noDownload")},{label:u("archives.menu.copyDownloadLink"),icon:a.jsx(Mo,{className:"w-4 h-4"}),onClick:()=>{const ce=`${window.location.origin}${pe.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ce).then(()=>{f(u("archives.toast.linkCopied"))}).catch(()=>{f(u("archives.toast.failedCopyLink"),"error")})},disabled:!y("archives:read"),title:y("archives:read")?void 0:u("archives.permission.noCopyLink")},{label:u("archives.menu.qrCode"),icon:a.jsx(yQ,{className:"w-4 h-4"}),onClick:()=>ae(!0)},{label:t.photos?.length?u("archives.menu.viewPhotosCount",{count:t.photos.length}):u("archives.menu.viewPhotos"),icon:a.jsx(yx,{className:"w-4 h-4"}),onClick:()=>me(!0),disabled:!t.photos?.length},{label:u("archives.menu.projectPage"),icon:a.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>ue(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?u("archives.menu.removeFromFavorites"):u("archives.menu.addToFavorites"),icon:a.jsx(If,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Ee.mutate(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.edit"),icon:a.jsx(Za,{className:"w-4 h-4"}),onClick:()=>T(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:u("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(js,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:u("archives.menu.addToProject"),icon:a.jsx(js,{className:"w-4 h-4"}),onClick:()=>{},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives"),submenu:(()=>{const ce=[];if(t.project_id&&ce.push({label:u("archives.menu.removeFromProject"),icon:a.jsx(Bt,{className:"w-4 h-4"}),onClick:()=>je.mutate(null),disabled:!v("archives","update",t.created_by_id)}),!s)ce.push({label:u("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const ze=s.filter(Ne=>Ne.status==="active");ze.length===0?ce.push({label:u("archives.menu.noProjectsAvailable"),icon:a.jsx(js,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):ze.forEach(Ne=>{ce.push({label:Ne.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:Ne.color||"#888"}}),onClick:()=>je.mutate(Ne.id),disabled:t.project_id===Ne.id||!v("archives","update",t.created_by_id)})})}return ce})()},{label:u(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(us,{className:"w-4 h-4"}):a.jsx(eo,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.delete"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>M(!0),danger:!0,disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?void 0:u("archives.permission.noDelete")}];return a.jsxs(Dt,{"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:qe,onClick:i?()=>r(t.id):void 0,children:[i&&a.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:ce=>{ce.stopPropagation(),r(t.id)},children:n?a.jsx(us,{className:"w-5 h-5 text-bambu-green"}):a.jsx(eo,{className:"w-5 h-5 text-white"})}),a.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),children:[t.thumbnail_path?a.jsx("img",{src:W!==null&&fe.length>0?pe.getArchivePlateThumbnail(t.id,fe[U]?.index??0):pe.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(Vu,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),se&&fe.length>1&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:ce=>{ce.stopPropagation(),q(ze=>{const Ne=ze??0;return Ne>0?Ne-1:fe.length-1})},title:u("archives.card.previousPlate"),children:a.jsx(ol,{className:"w-4 h-4 text-white"})}),a.jsx("button",{className:`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:ce=>{ce.stopPropagation(),q(ze=>{const Ne=ze??0;return Ne<fe.length-1?Ne+1:0})},title:u("archives.card.nextPlate"),children:a.jsx(Va,{className:"w-4 h-4 text-white"})}),a.jsx("div",{className:`absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-1 px-2 py-1 rounded-full bg-black/50 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:fe.map((ce,ze)=>a.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${ze===U?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:Ne=>{Ne.stopPropagation(),q(ze)},title:ce.name||u("archives.card.plateNumber",{index:ce.index})},ce.index))})]}),a.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"} ${i?"left-10":""}`,onClick:ce=>{ce.stopPropagation();const ze=ce.currentTarget.getBoundingClientRect();z({x:ze.left,y:ze.bottom+4})},title:u("archives.card.moreOptions"),children:a.jsx(Mh,{className:"w-5 h-5 text-white"})}),a.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${v("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:ce=>{ce.stopPropagation(),v("archives","update",t.created_by_id)&&Ee.mutate()},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?t.is_favorite?u("archives.card.removeFromFavorites"):u("archives.card.addToFavorites"):u("archives.permission.noUpdateArchives"),children:a.jsx(If,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${v("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&a.jsx("div",{className:"absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white",children:t.status==="aborted"?u("archives.card.cancelled"):u("archives.card.failed")}),t.duplicate_count>0&&ie>0&&he&&a.jsxs("button",{onClick:ce=>{ce.stopPropagation(),m?.(he)},className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 hover:bg-purple-600/90 text-white flex items-center gap-1 transition-colors cursor-pointer",title:u("archives.viewOriginalPrint",{id:he}),children:[a.jsx(Mo,{className:"w-3 h-3"}),"#",ie]}),t.duplicate_count>0&&ie===0&&a.jsxs("span",{className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[a.jsx(fQ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.source_3mf_path&&a.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ce=>{ce.stopPropagation();const ze=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source";gh(t.id,ze,"source",c)},title:u("archives.card.openSource3mf"),children:a.jsx(Jk,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&a.jsx("button",{className:`absolute bottom-2 ${t.source_3mf_path?"left-12":"left-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:ce=>{ce.stopPropagation(),pe.downloadF3d(t.id).catch(ze=>{console.error("F3D download failed:",ze)})},title:u("archives.card.downloadF3d"),children:a.jsx(si,{className:"w-4 h-4 text-cyan-400"})}),a.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ce=>{ce.stopPropagation(),_(!0)},title:u("archives.card.preview3d"),children:a.jsx(ea,{className:"w-4 h-4 text-white"})}),t.timelapse_path&&a.jsx("button",{className:"absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ce=>{ce.stopPropagation(),F(!0)},title:u("archives.card.viewTimelapse"),children:a.jsx(jh,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&a.jsxs("button",{className:`absolute bottom-2 ${t.timelapse_path?"right-[5.5rem]":"right-12"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:ce=>{ce.stopPropagation(),me(!0)},title:t.photos.length===1?u("archives.card.viewPhoto"):u("archives.card.viewPhotos",{count:t.photos.length}),children:[a.jsx(yx,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&a.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center",children:t.photos.length})]}),Se&&Se.length>0&&a.jsx(vo,{to:`/files?folder=${Se[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ce=>ce.stopPropagation(),title:u("archives.card.openFolder",{name:Se[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:a.jsx(Fc,{className:"w-4 h-4 text-yellow-400"})})]}),a.jsxs(Rt,{className:"p-4 flex-1 flex flex-col",children:[a.jsxs("p",{className:"text-[10px] text-bambu-gray/70 mb-1",children:["#",t.id]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[a.jsx("h3",{className:"min-w-0 font-medium text-white truncate",children:t.print_name||t.filename}),a.jsx(Ie,{variant:"ghost",size:"sm",className:"p-1 sm:p-1.5 shrink-0",onClick:()=>T(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?u("archives.card.edit"):u("archives.card.noPermissionEdit"),children:a.jsx(Za,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:e}),a.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${fh(t)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:fh(t)?u("archives.card.slicedFile"):u("archives.card.sourceFile"),children:fh(t)?u("archives.card.gcode"):u("archives.card.source")}),t.content_hash&&a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono bg-bambu-dark-tertiary/50 text-bambu-gray-light opacity-0 transition-opacity duration-150 group-hover:opacity-100",title:`SHA256: ${t.content_hash}`,children:t.content_hash.slice(0,8).toUpperCase()}),t.project_name&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(ce=>ce.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(ce=>ce.id===t.project_id)?.color||"#6b7280"},title:u("archives.card.project",{name:t.project_name}),children:t.project_name})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]",children:[(t.print_time_seconds||t.actual_time_seconds)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${ls(t.print_time_seconds||0)}
  8315. Actual: ${ls(t.actual_time_seconds||0)}
  8316. Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ls(t.actual_time_seconds)}`:`Estimated: ${ls(t.print_time_seconds||0)}`,children:[a.jsx(rr,{className:"w-3 h-3"}),ls(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&a.jsxs("span",{className:`text-[10px] px-1 rounded ${t.time_accuracy>=95&&t.time_accuracy<=105?"bg-bambu-green/20 text-bambu-green":t.time_accuracy>105?"bg-blue-500/20 text-blue-400":"bg-orange-500/20 text-orange-400"}`,children:[t.time_accuracy>100?"+":"",(t.time_accuracy-100).toFixed(0),"%"]})]}),t.filament_used_grams&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Na,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.cost!=null||t.energy_cost!=null)&&a.jsxs("div",{className:"flex items-center gap-3 text-bambu-gray",children:[t.cost!=null&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(tfe,{className:"w-3 h-3"}),d,t.cost.toFixed(2)]}),t.energy_cost!=null&&a.jsxs("div",{className:"flex items-center gap-1.5",title:`${u("stats.energyUsed")}: ${t.energy_kwh?.toFixed(3)||"N/A"} kWh`,children:[a.jsx(Xl,{className:"w-3 h-3"}),d,t.energy_cost.toFixed(2)]})]}),(t.layer_height||t.total_layers)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(ea,{className:"w-3 h-3"}),t.total_layers&&a.jsx("span",{children:t.total_layers===1?u("archives.card.layer",{count:t.total_layers}):u("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&a.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count}),children:[a.jsx(si,{className:"w-3 h-3"}),t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:u("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(Pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&a.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[a.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ce,ze)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:ce},title:ce},ze))})]})]}),(t.tags||t.notes)&&a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&a.jsx("div",{className:"flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs",title:t.notes,children:a.jsx(SQ,{className:"w-3 h-3"})}),t.tags?.split(",").map((ce,ze)=>a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:ce.trim()},ze))]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("span",{children:Bf(t.created_at,l)}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1",title:u("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx(Wu,{className:"w-3 h-3"}),t.created_by_username]}),a.jsx("span",{children:_o(t.file_size)})]})]}),a.jsxs("div",{className:"flex gap-1 mt-3",children:[fh(t)?a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>P(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:u("archives.card.noPermissionReprint"):u("archives.card.noFileForReprint"),children:[a.jsx(Pr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.reprint")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>ne(!0),disabled:!t.file_path||!y("queue:create"),title:t.file_path?y("queue:create")?u("archives.card.schedulePrint"):u("archives.permission.noAddToQueue"):u("archives.card.noFileForReprint"),children:[a.jsx(Wr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.schedule")})]}),a.jsx(Ie,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ce=t.print_name||t.filename||"model";gh(t.id,ce,"file",c)},title:u("archives.card.openInBambuStudio"),children:a.jsx(sa,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):a.jsxs(Ie,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>{const ce=t.print_name||t.filename||"model";gh(t.id,ce,"file",c)},title:u("archives.card.openInBambuStudioToSlice"),children:[a.jsx(sa,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.slice")})]}),a.jsx(Ie,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ce=t.external_url||t.makerworld_url;ce&&window.open(ce,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?u("archives.card.externalLink"):t.makerworld_url?u("archives.card.makerWorld",{designer:t.designer||u("archives.card.viewProject")}):u("archives.card.noExternalLink"),children:a.jsx(yd,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),a.jsx(Ie,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{pe.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ce=>{console.error("Archive download failed:",ce)})},title:u("archives.card.download"),children:a.jsx(va,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>M(!0),disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?u("archives.card.delete"):u("archives.card.noPermissionDelete"),children:a.jsx(un,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),A&&a.jsx(Dae,{archive:t,onClose:()=>T(!1)}),g&&a.jsx(ez,{archiveId:t.id,title:t.print_name||t.filename,fileType:Doe(t.filename),onClose:()=>_(!1)}),k&&a.jsx(kd,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>P(!1)}),N&&a.jsx(kn,{title:u("archives.modal.deleteArchive"),message:u("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Fe.mutate(),M(!1)},onCancel:()=>M(!1)}),oe&&a.jsx(kn,{title:u("archives.modal.removeSource3mf"),message:u("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{we.mutate(),be(!1)},onCancel:()=>be(!1)}),_e&&a.jsx(kn,{title:u("archives.modal.removeF3d"),message:u("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Ae.mutate(),B(!1)},onCancel:()=>B(!1)}),Y&&a.jsx(kn,{title:u("archives.modal.removeTimelapse"),message:u("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{R.mutate(),D(!1)},onCancel:()=>D(!1)}),j&&a.jsx(Fae,{x:j.x,y:j.y,items:Ye,onClose:()=>z(null)}),C&&t.timelapse_path&&a.jsx(Eoe,{src:pe.getArchiveTimelapse(t.id),title:u("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>F(!1),onEdit:()=>{p.invalidateQueries({queryKey:["archives"]}),F(!1)}}),$&&X.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:u("archives.modal.selectTimelapse")}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:u("archives.modal.selectTimelapseDesc")})]}),a.jsx("button",{onClick:()=>{I(!1),L([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:X.map(ce=>a.jsxs("button",{onClick:()=>Te.mutate(ce.name),disabled:Te.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50",children:[a.jsx(jh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:ce.name}),a.jsxs("p",{className:"text-sm text-gray-400",children:[_o(ce.size),ce.mtime&&` • ${Bf(ce.mtime,l)}`]})]})]},ce.name))}),a.jsx("div",{className:"p-4 border-t border-gray-700",children:a.jsx(Ie,{variant:"secondary",onClick:()=>{I(!1),L([])},className:"w-full",children:"Cancel"})})]})}),te&&a.jsx(Rae,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ae(!1)}),ee&&t.photos&&t.photos.length>0&&a.jsx(Lae,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>me(!1),onDelete:async ce=>{try{await pe.deleteArchivePhoto(t.id,ce),p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.photoDeleted"))}catch{f(u("archives.toast.failedDeletePhoto"),"error")}}}),le&&a.jsx(joe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ue(!1)}),K&&a.jsx(kd,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ne(!1)}),a.jsx("input",{ref:G,type:"file",accept:".3mf",className:"hidden",onChange:ce=>{const ze=ce.target.files?.[0];ze&&xe.mutate(ze),ce.target.value=""}}),a.jsx("input",{ref:Q,type:"file",accept:".f3d",className:"hidden",onChange:ce=>{const ze=ce.target.files?.[0];ze&&ye.mutate(ze),ce.target.value=""}}),a.jsx("input",{ref:V,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ce=>{const ze=ce.target.files?.[0];ze&&re.mutate(ze),ce.target.value=""}})]})}function WZe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c,onNavigateToArchive:d}){const u=mn(),{showToast:m}=xn(),{hasPermission:p,canModify:f}=_r(),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(!1),[M,A]=w.useState(!1),[T,C]=w.useState(!1),[F,$]=w.useState(!1),[I,X]=w.useState([]),[L,te]=w.useState(!1),[ae,ee]=w.useState(!1),[me,le]=w.useState(!1),[ue,K]=w.useState(!1),[ne,oe]=w.useState(!1),[be,_e]=w.useState(!1),[B,Y]=w.useState(null),D=w.useRef(null),j=w.useRef(null),z=w.useRef(null),W=t.duplicate_sequence??0,q=t.original_archive_id??null,de=lt({mutationFn:()=>pe.deleteArchiveTimelapse(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveTimelapse"),"error")}}),O=lt({mutationFn:ye=>pe.uploadArchiveTimelapse(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseUploaded",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadTimelapse"),"error")}}),G=lt({mutationFn:ye=>pe.uploadSource3mf(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfAttached",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadSource3mf"),"error")}}),Q=lt({mutationFn:()=>pe.deleteSource3mf(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),V=lt({mutationFn:ye=>pe.uploadF3d(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dAttached",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadF3d"),"error")}}),J=lt({mutationFn:()=>pe.deleteF3d(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveF3d"),"error")}}),ie=lt({mutationFn:()=>pe.scanArchiveTimelapse(t.id),onSuccess:ye=>{ye.status==="attached"?(u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:ye.filename}))):ye.status==="exists"?m(c("archives.toast.timelapseAlreadyAttached")):ye.status==="not_found"&&ye.available_files&&ye.available_files.length>0?(X(ye.available_files),$(!0)):m(ye.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:ye=>{m(ye.message||c("archives.toast.failedScanTimelapse"),"error")}}),he=lt({mutationFn:ye=>pe.selectArchiveTimelapse(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:ye.filename})),$(!1),X([])},onError:ye=>{m(ye.message||c("archives.toast.failedAttachTimelapse"),"error")}}),fe=lt({mutationFn:()=>pe.deleteArchive(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.archiveDeleted"))},onError:()=>{m(c("archives.toast.failedDeleteArchive"),"error")}}),se=lt({mutationFn:()=>pe.toggleFavorite(t.id),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(ye.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:U}=et({queryKey:["archive-folders",t.id],queryFn:()=>pe.getLibraryFoldersByArchive(t.id)}),R=lt({mutationFn:ye=>pe.updateArchive(t.id,{project_id:ye}),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),u.invalidateQueries({queryKey:["projects"]}),m(c("archives.toast.projectUpdated"))},onError:()=>{m(c("archives.toast.failedUpdateProject"),"error")}}),re=ye=>{ye.preventDefault(),Y({x:ye.clientX,y:ye.clientY})},we=[...fh(t)?[{label:c("archives.menu.print"),icon:a.jsx(Pr,{className:"w-4 h-4"}),onClick:()=>k(!0),disabled:!t.file_path||!f("archives","reprint",t.created_by_id),title:t.file_path?f("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint"):c("archives.card.noFileForReprint")},{label:c("archives.menu.schedule"),icon:a.jsx(Wr,{className:"w-4 h-4"}),onClick:()=>N(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?void 0:c("archives.permission.noAddToQueue"):c("archives.card.noFileForReprint")},{label:c("archives.menu.openInBambuStudio"),icon:a.jsx(sa,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";gh(t.id,ye,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:c("archives.card.noFileForReprint")}]:[{label:c("archives.menu.slice"),icon:a.jsx(sa,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";gh(t.id,ye,"file",l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:a.jsx(yd,{className:"w-4 h-4"}),onClick:()=>{const ye=t.external_url||t.makerworld_url;ye&&window.open(ye,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:a.jsx(si,{className:"w-4 h-4"}),onClick:()=>A(!0)},{label:c("archives.menu.viewTimelapse"),icon:a.jsx(jh,{className:"w-4 h-4"}),onClick:()=>C(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:a.jsx(iN,{className:"w-4 h-4"}),onClick:()=>ie.mutate(),disabled:!t.printer_id||!!t.timelapse_path||ie.isPending||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.uploadTimelapse"),icon:a.jsx(Ca,{className:"w-4 h-4"}),onClick:()=>z.current?.click(),disabled:!!t.timelapse_path||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:c("archives.menu.removeTimelapse"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>_e(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?c("archives.menu.downloadSource3mf"):c("archives.menu.uploadSource3mf"),icon:a.jsx(Jk,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?pe.downloadSource3mf(t.id).catch(ye=>{console.error("Source 3MF download failed:",ye)}):D.current?.click()},disabled:!t.source_3mf_path&&!f("archives","update",t.created_by_id),title:!t.source_3mf_path&&!f("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:a.jsx(Ca,{className:"w-4 h-4"}),onClick:()=>D.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>K(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?c("archives.menu.replaceF3d"):c("archives.menu.uploadF3d"),icon:a.jsx(si,{className:"w-4 h-4"}),onClick:()=>j.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:a.jsx(va,{className:"w-4 h-4"}),onClick:()=>{pe.downloadF3d(t.id).catch(ye=>{console.error("F3D download failed:",ye)})}},{label:c("archives.menu.removeF3d"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>oe(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:a.jsx(va,{className:"w-4 h-4"}),onClick:()=>{pe.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:a.jsx(Mo,{className:"w-4 h-4"}),onClick:()=>{const ye=`${window.location.origin}${pe.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ye).then(()=>{m(c("archives.toast.linkCopied"))}).catch(()=>{m(c("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:a.jsx(yQ,{className:"w-4 h-4"}),onClick:()=>te(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:a.jsx(yx,{className:"w-4 h-4"}),onClick:()=>ee(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:a.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>le(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:a.jsx(If,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>se.mutate(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:a.jsx(Za,{className:"w-4 h-4"}),onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:c("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(js,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:a.jsx(js,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const ye=[];if(t.project_id&&ye.push({label:c("archives.menu.removeFromProject"),icon:a.jsx(Bt,{className:"w-4 h-4"}),onClick:()=>R.mutate(null)}),!s)ye.push({label:c("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const Ae=s.filter(ve=>ve.status==="active");Ae.length===0?ye.push({label:c("archives.menu.noProjectsAvailable"),icon:a.jsx(js,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):Ae.forEach(ve=>{ye.push({label:ve.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:ve.color||"#888"}}),onClick:()=>R.mutate(ve.id),disabled:t.project_id===ve.id})})}return ye})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(us,{className:"w-4 h-4"}):a.jsx(eo,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:a.jsx(un,{className:"w-4 h-4"}),onClick:()=>g(!0),danger:!0,disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return a.jsxs(a.Fragment,{children:[a.jsxs("div",{"data-archive-id":t.id,className:`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${n?"bg-bambu-green/10":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"-4px"}:void 0,onContextMenu:re,children:[a.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[i&&a.jsx("button",{onClick:()=>r(t.id),children:n?a.jsx(us,{className:"w-4 h-4 text-bambu-green"}):a.jsx(eo,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?a.jsx("img",{src:pe.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):a.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:a.jsx(Vu,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),a.jsxs("div",{className:"col-span-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0",children:t.status==="aborted"?c("archives.card.cancelled"):c("archives.card.failed")}),t.duplicate_count>0&&W>0&&q&&a.jsxs("button",{onClick:ye=>{ye.stopPropagation(),d?.(q)},className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 hover:bg-purple-600/90 text-white flex-shrink-0 transition-colors flex items-center gap-1",title:c("archives.viewOriginalPrint",{id:q}),children:[a.jsx(Mo,{className:"w-3 h-3"}),"#",W]}),t.duplicate_count>0&&W===0&&a.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 text-white flex-shrink-0 flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[a.jsx(fQ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.timelapse_path&&a.jsx("span",{title:c("archives.list.hasTimelapse"),children:a.jsx(jh,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),U&&U.length>0&&a.jsx(vo,{to:`/files?folder=${U[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:U[0].name}),onClick:ye=>ye.stopPropagation(),children:a.jsx(Fc,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&a.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(Pr,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ye,Ae)=>a.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-black/20",style:{backgroundColor:ye},title:ye},Ae))})]})]}),a.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),a.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[a.jsx("div",{children:Uf(t.created_at)}),t.created_by_username&&a.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx(Wu,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:_o(t.file_size)}),a.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[fh(t)&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>k(!0),disabled:!f("archives","reprint",t.created_by_id),title:f("archives","reprint",t.created_by_id)?c("archives.card.reprint"):c("archives.card.noPermissionReprint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:a.jsx(Ds,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{const ye=t.print_name||t.filename||"model";gh(t.id,ye,"file",l)},title:c("archives.card.openInBambuStudio"),children:a.jsx(sa,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:a.jsx(yd,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{pe.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},title:c("archives.card.download"),children:a.jsx(va,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>g(!0),disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:a.jsx(un,{className:"w-4 h-4 text-red-400"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:ye=>{const Ae=ye.currentTarget.getBoundingClientRect();Y({x:Ae.left,y:Ae.bottom+4})},title:c("archives.card.moreOptions"),children:a.jsx(Mh,{className:"w-4 h-4"})})]})]}),y&&a.jsx(Dae,{archive:t,onClose:()=>v(!1)}),M&&a.jsx(ez,{archiveId:t.id,title:t.print_name||t.filename,fileType:Doe(t.filename),onClose:()=>A(!1)}),_&&a.jsx(kd,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>k(!1)}),b&&a.jsx(kn,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{fe.mutate(),g(!1)},onCancel:()=>g(!1)}),ue&&a.jsx(kn,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Q.mutate(),K(!1)},onCancel:()=>K(!1)}),ne&&a.jsx(kn,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{J.mutate(),oe(!1)},onCancel:()=>oe(!1)}),be&&a.jsx(kn,{title:c("archives.modal.removeTimelapse"),message:c("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{de.mutate(),_e(!1)},onCancel:()=>_e(!1)}),B&&a.jsx(Fae,{x:B.x,y:B.y,items:we,onClose:()=>Y(null)}),T&&t.timelapse_path&&a.jsx(Eoe,{src:pe.getArchiveTimelapse(t.id),title:c("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>C(!1),onEdit:()=>{u.invalidateQueries({queryKey:["archives"]}),C(!1)}}),F&&I.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:c("archives.modal.selectTimelapse")}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:c("archives.modal.selectTimelapseDesc")})]}),a.jsx("button",{onClick:()=>{$(!1),X([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:I.map(ye=>a.jsxs("button",{onClick:()=>he.mutate(ye.name),disabled:he.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[a.jsx("div",{className:"font-medium text-white",children:ye.name}),a.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[a.jsx("span",{children:_o(ye.size)}),ye.mtime&&a.jsx("span",{children:Uf(ye.mtime)})]})]},ye.name))})]})}),L&&a.jsx(Rae,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>te(!1)}),ae&&t.photos&&a.jsx(Lae,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>ee(!1),onDelete:async ye=>{try{await pe.deleteArchivePhoto(t.id,ye),u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.photoDeleted"))}catch{m(c("archives.toast.failedDeletePhoto"),"error")}}}),me&&a.jsx(joe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>le(!1)}),P&&a.jsx(kd,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>N(!1)}),a.jsx("input",{ref:D,type:"file",accept:".3mf",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&G.mutate(Ae),ye.target.value=""}}),a.jsx("input",{ref:j,type:"file",accept:".f3d",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&V.mutate(Ae),ye.target.value=""}}),a.jsx("input",{ref:z,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&O.mutate(Ae),ye.target.value=""}})]})}const KZe=[{id:"all",label:"All Archives",icon:a.jsx(Fc,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:a.jsx(rr,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:a.jsx(Wr,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:a.jsx(Wr,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:a.jsx(If,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:a.jsx(qa,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:a.jsx(Mo,{className:"w-4 h-4"})}];function YZe(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i}=_r(),s=w.useRef(null),[o,l]=w.useState(""),[c,d]=w.useState(()=>{const He=localStorage.getItem("archiveFilterPrinter");return He?Number(He):null}),[u,m]=w.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,f]=w.useState(()=>{const He=localStorage.getItem("archiveFilterColors");return He?new Set(JSON.parse(He)):new Set}),[y,v]=w.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[b,g]=w.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[_,k]=w.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[P,N]=w.useState(()=>localStorage.getItem("archiveHideDuplicates")==="true"),[M,A]=w.useState(()=>localStorage.getItem("archiveFilterTag")),[T,C]=w.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[F,$]=w.useState(!1),[I,X]=w.useState([]),[L,te]=w.useState(!1),[ae,ee]=w.useState(new Set),[me,le]=w.useState(!1),[ue,K]=w.useState(!1),[ne,oe]=w.useState(!1),[be,_e]=w.useState(!1),[B,Y]=w.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[D,j]=w.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[z,W]=w.useState(()=>localStorage.getItem("archiveCollection")||"all"),[q,de]=w.useState(0),[O,G]=w.useState(()=>{try{const He=localStorage.getItem("archivePageSize");return He?Number(He):50}catch{return 50}}),[Q,V]=w.useState(!1),[J,ie]=w.useState(!1),[he,fe]=w.useState(!1),[se,U]=w.useState(!1),[R,re]=w.useState(null),[xe,we]=w.useState(null),[ye,Ae]=w.useState(()=>localStorage.getItem("logFilterUser")||null),[ve,Te]=w.useState(()=>localStorage.getItem("logFilterStatus")),[Fe,Ee]=w.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[Se,je]=w.useState(()=>localStorage.getItem("logFilterDateTo")||""),[qe,Re]=w.useState(()=>{const He=localStorage.getItem("logOffset");return He?Number(He):0}),[Ye,ce]=w.useState(!1),[ze,Ne]=w.useState(()=>{const He=localStorage.getItem("logPageSize");return He?Number(He):25}),Ge=w.useCallback(He=>{we(He),re(He)},[]);w.useEffect(()=>{if(R){const He=setTimeout(()=>{const Ct=document.querySelector(`[data-archive-id="${R}"]`);Ct?Ct.scrollIntoView({behavior:"smooth",block:"center"}):xe===R&&n(t("archives.originalPrintNotVisible"),"warning"),xe===R&&we(null)},100),St=setTimeout(()=>re(null),5e3);return()=>{clearTimeout(He),clearTimeout(St)}}},[R,xe,n,t]);const{data:$e,isLoading:Pe}=et({queryKey:["archives",c],queryFn:()=>pe.getArchives(c||void 0)}),{data:Me}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:Ve}=et({queryKey:["projects"],queryFn:()=>pe.getProjects()}),{data:tt}=et({queryKey:["settings"],queryFn:pe.getSettings}),{data:ut}=et({queryKey:["users"],queryFn:pe.getUsers,enabled:B==="log"}),{data:xt,isLoading:wt}=et({queryKey:["print-log",c,ye,ve,Fe,Se,o,qe,ze],queryFn:()=>pe.getPrintLog({search:o||void 0,printerId:c||void 0,username:ye||void 0,status:ve||void 0,dateFrom:Fe||void 0,dateTo:Se||void 0,limit:ze,offset:qe}),enabled:B==="log"}),Ht=tt?.time_format||"system",Xt=tt?.preferred_slicer||"bambu_studio",Kt=yo(tt?.currency||"USD"),Ut=lt({mutationFn:async He=>(await Promise.all(He.map(St=>pe.deleteArchive(St))),He.length),onSuccess:He=>{e.invalidateQueries({queryKey:["archives"]}),ee(new Set),n(`${He} archive${He!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),en=lt({mutationFn:()=>pe.clearPrintLog(),onSuccess:He=>{e.invalidateQueries({queryKey:["print-log"]}),Re(0),n(t("archives.log.cleared",{count:He.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});w.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),w.useEffect(()=>{u?localStorage.setItem("archiveFilterMaterial",u):localStorage.removeItem("archiveFilterMaterial")},[u]),w.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),w.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",y)},[y]),w.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",b.toString())},[b]),w.useEffect(()=>{localStorage.setItem("archiveHideFailed",_.toString())},[_]),w.useEffect(()=>{localStorage.setItem("archiveHideDuplicates",P.toString())},[P]),w.useEffect(()=>{M?localStorage.setItem("archiveFilterTag",M):localStorage.removeItem("archiveFilterTag")},[M]),w.useEffect(()=>{localStorage.setItem("archiveFilterFileType",T)},[T]),w.useEffect(()=>{de(0)},[o,c,u,p,y,b,_,P,M,T,D,z]),w.useEffect(()=>{try{localStorage.setItem("archivePageSize",String(O))}catch{}},[O]),w.useEffect(()=>{localStorage.setItem("archiveViewMode",B)},[B]),w.useEffect(()=>{localStorage.setItem("archiveSortBy",D)},[D]),w.useEffect(()=>{localStorage.setItem("archiveCollection",z)},[z]),w.useEffect(()=>{ye?localStorage.setItem("logFilterUser",ye):localStorage.removeItem("logFilterUser")},[ye]),w.useEffect(()=>{ve?localStorage.setItem("logFilterStatus",ve):localStorage.removeItem("logFilterStatus")},[ve]),w.useEffect(()=>{Fe?localStorage.setItem("logFilterDateFrom",Fe):localStorage.removeItem("logFilterDateFrom")},[Fe]),w.useEffect(()=>{Se?localStorage.setItem("logFilterDateTo",Se):localStorage.removeItem("logFilterDateTo")},[Se]),w.useEffect(()=>{localStorage.setItem("logOffset",qe.toString())},[qe]),w.useEffect(()=>{localStorage.setItem("logPageSize",ze.toString())},[ze]);const Ke=new Map(Me?.map(He=>[He.id,He.name])||[]),Ft=[...new Set($e?.flatMap(He=>He.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),Nt=[...new Set($e?.flatMap(He=>He.filament_color?.split(",")||[]).filter(Boolean)||[])],ht=[...new Set($e?.flatMap(He=>He.tags?.split(",").map(St=>St.trim())||[]).filter(Boolean)||[])].sort(),Mt=$e?.filter(He=>{const St=new Date,Ct=Qn(He.created_at)||new Date(0);let Zt=!0;switch(z){case"recent":Zt=St.getTime()-Ct.getTime()<1440*60*1e3;break;case"this-week":Zt=St.getTime()-Ct.getTime()<10080*60*1e3;break;case"this-month":Zt=Ct.getMonth()===St.getMonth()&&Ct.getFullYear()===St.getFullYear();break;case"favorites":Zt=He.is_favorite===!0;break;case"failed":Zt=He.status==="failed"||He.status==="aborted";break;case"duplicates":Zt=He.duplicate_count>0;break}const Jt=(He.print_name||He.filename).toLowerCase().includes(o.toLowerCase()),Nn=!u||He.filament_type?.split(", ").includes(u),vn=He.filament_color?.split(",")||[],yn=p.size===0||(y==="or"?vn.some(Rn=>p.has(Rn)):[...p].every(Rn=>vn.includes(Rn))),an=z==="favorites"||!b||He.is_favorite,rn=z==="failed"||!_||He.status!=="failed"&&He.status!=="aborted",bn=z==="duplicates"||!P||He.duplicate_count===0||He.duplicate_sequence===0,Gn=He.tags?.split(",").map(Rn=>Rn.trim())||[],ar=!M||Gn.includes(M),On=fh(He);return Zt&&Jt&&Nn&&yn&&an&&rn&&bn&&ar&&(T==="all"||T==="gcode"&&On||T==="source"&&!On)}).sort((He,St)=>{switch(D){case"date-desc":return(Qn(St.created_at)?.getTime()||0)-(Qn(He.created_at)?.getTime()||0);case"date-asc":return(Qn(He.created_at)?.getTime()||0)-(Qn(St.created_at)?.getTime()||0);case"name-asc":return(He.print_name||He.filename).localeCompare(St.print_name||St.filename);case"name-desc":return(St.print_name||St.filename).localeCompare(He.print_name||He.filename);case"size-desc":return St.file_size-He.file_size;case"size-asc":return He.file_size-St.file_size;default:return 0}}),Qt=Mt?.length||0,Wt=O===-1,Ue=Wt?Qt||1:O,dt=Math.max(1,Math.ceil(Qt/Ue)),pt=Wt?Mt:Mt?.slice(q*Ue,(q+1)*Ue);w.useEffect(()=>{if(R&&Mt&&!Wt){const He=Mt.findIndex(St=>St.id===R);if(He>=0){const St=Math.floor(He/Ue);St!==q&&de(St)}}},[R]);const De=me||ae.size>0,Le=He=>{ee(St=>{const Ct=new Set(St);return Ct.has(He)?Ct.delete(He):Ct.add(He),Ct})},at=()=>{Mt&&ee(new Set(Mt.map(He=>He.id)))},Ce=()=>{ee(new Set),le(!1)},We=He=>{f(St=>{const Ct=new Set(St);return Ct.has(He)?Ct.delete(He):Ct.add(He),Ct})},Xe=()=>{f(new Set)},Qe=()=>{l(""),d(null),m(null),g(!1),k(!1),N(!1),A(null),C("all")},Ze=o||c||u||b||_||P||M||T!=="all",rt=w.useCallback(He=>{He.preventDefault(),He.dataTransfer.types.includes("Files")&&te(!0)},[]),bt=w.useCallback(He=>{He.preventDefault(),He.currentTarget===He.target&&te(!1)},[]),Pt=w.useCallback(He=>{He.preventDefault(),te(!1);const St=Array.from(He.dataTransfer.files).filter(Ct=>Ct.name.endsWith(".3mf"));St.length>0?(X(St),$(!0)):He.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),vt=w.useCallback(He=>{const St=He.target;if(St.tagName==="INPUT"||St.tagName==="TEXTAREA"||St.isContentEditable){He.key==="Escape"&&St.blur();return}switch(He.key){case"/":He.preventDefault(),s.current?.focus();break;case"u":case"U":!He.metaKey&&!He.ctrlKey&&(He.preventDefault(),$(!0));break;case"Escape":De&&Ce();break}},[De]);return w.useEffect(()=>(document.addEventListener("keydown",vt),()=>document.removeEventListener("keydown",vt)),[vt]),a.jsxs("div",{className:"p-4 md:p-8 relative",onDragOver:rt,onDragLeave:bt,onDrop:Pt,children:[L&&a.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:a.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[a.jsx(Ca,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),a.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),a.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),De&&a.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ce,children:[a.jsx(Bt,{className:"w-4 h-4"}),"Close"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("span",{className:"text-white font-medium",children:[ae.size," selected"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:at,children:"Select All"}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>oe(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(Gu,{className:"w-4 h-4"}),"Tags"]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>_e(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(js,{className:"w-4 h-4"}),"Project"]}),a.jsxs(Ie,{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 He=Array.from(ae);Promise.all(He.map(St=>pe.toggleFavorite(St))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${He.length} archive${He.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[a.jsx(If,{className:"w-4 h-4"}),"Favorite"]}),a.jsxs(Ie,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>K(!0),disabled:!i("archives:delete_own","archives:delete_all"),title:i("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[a.jsx(un,{className:"w-4 h-4"}),"Delete"]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),a.jsx("select",{className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none",value:z,onChange:He=>W(He.target.value),children:KZe.map(He=>a.jsx("option",{value:He.id,children:He.label},He.id))})]}),a.jsxs("p",{className:"text-bambu-gray",children:[Mt?.length||0," of ",$e?.length||0," prints"]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>V(!Q),disabled:J,children:[J?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eN,{className:"w-4 h-4"}),"Export"]}),Q&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:async()=>{V(!1),ie(!0);try{const{blob:He,filename:St}=await pe.exportArchives({format:"csv",printerId:c||void 0,status:z==="failed"?"failed":void 0,search:o||void 0}),Ct=URL.createObjectURL(He),Zt=document.createElement("a");Zt.href=Ct,Zt.download=St,Zt.click(),URL.revokeObjectURL(Ct),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{ie(!1)}},children:[a.jsx(Ms,{className:"w-4 h-4"}),"Export as CSV"]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:async()=>{V(!1),ie(!0);try{const{blob:He,filename:St}=await pe.exportArchives({format:"xlsx",printerId:c||void 0,status:z==="failed"?"failed":void 0,search:o||void 0}),Ct=URL.createObjectURL(He),Zt=document.createElement("a");Zt.href=Ct,Zt.download=St,Zt.click(),URL.revokeObjectURL(Ct),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{ie(!1)}},children:[a.jsx(eN,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),ae.size>=2&&ae.size<=5&&a.jsxs(Ie,{variant:"secondary",onClick:()=>fe(!0),children:[a.jsx(tx,{className:"w-4 h-4"}),"Compare (",ae.size,")"]}),!De&&a.jsxs(Ie,{variant:"secondary",onClick:()=>le(!0),children:[a.jsx(us,{className:"w-4 h-4"}),"Select"]}),a.jsxs(Ie,{onClick:()=>$(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[a.jsx(Ca,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),a.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[a.jsx("button",{className:`p-2 ${B==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("grid"),title:t("archives.gridView"),children:a.jsx(jw,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${B==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("list"),title:t("archives.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${B==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("calendar"),title:t("archives.calendarView"),children:a.jsx(ype,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${B==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("log"),title:t("archives.logView"),children:a.jsx($pe,{className:"w-4 h-4"})})]}),B!=="log"&&a.jsx(Dt,{className:"mb-6",children:a.jsxs(Rt,{className:"py-4",children:[a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{ref:s,type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o,onChange:He=>l(He.target.value)})]}),a.jsxs("div",{className:"flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c||"",onChange:He=>d(He.target.value?Number(He.target.value):null),children:[a.jsx("option",{value:"",children:"All Printers"}),Me?.map(He=>a.jsx("option",{value:He.id,children:He.name},He.id))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(Na,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:u||"",onChange:He=>m(He.target.value||null),children:[a.jsx("option",{value:"",children:"All Materials"}),Ft.map(He=>a.jsx("option",{value:He,children:He},He))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(Jk,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:T,onChange:He=>C(He.target.value),children:[a.jsx("option",{value:"all",children:"All Files"}),a.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),a.jsx("option",{value:"source",children:"Source Only"})]})]}),a.jsxs("button",{onClick:()=>g(!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:[a.jsx(If,{className:`w-4 h-4 ${b?"fill-yellow-400":""}`}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),a.jsxs("button",{onClick:()=>k(!_),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${_?"bg-red-500/20 border-red-500 text-red-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(_?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[a.jsx(qa,{className:"w-4 h-4 "}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),a.jsxs("button",{onClick:()=>N(!P),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${P?"bg-purple-500/20 border-purple-500 text-purple-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("archives.hideDuplicates"),children:[a.jsx(Mo,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm hidden md:inline",children:t("archives.hideDuplicates")})]}),ht.length>0&&a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(Gu,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:M||"",onChange:He=>A(He.target.value||null),children:[a.jsx("option",{value:"",children:"All Tags"}),ht.map(He=>a.jsx("option",{value:He,children:He},He))]}),a.jsx("button",{onClick:()=>U(!0),className:"p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",title:t("archives.manageTags"),children:a.jsx(Ow,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(lO,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:D,onChange:He=>j(He.target.value),children:[a.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),a.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),a.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),a.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),a.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),a.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),Ze&&a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:Qe,className:"text-bambu-gray hover:text-white",children:[a.jsx(Bt,{className:"w-4 h-4"}),"Reset"]})]}),Nt.length>0&&a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&a.jsx("button",{onClick:()=>v(He=>He==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${y==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:y==="or"?"Match ANY selected color":"Match ALL selected colors",children:y.toUpperCase()}),a.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:Nt.map(He=>a.jsx("button",{onClick:()=>We(He),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(He)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:He},title:He},He))}),p.size>0&&a.jsxs("button",{onClick:Xe,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[a.jsx(Bt,{className:"w-3 h-3"}),"Clear"]})]})]})}),a.jsx($Ze,{}),Pe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):Mt?.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):B==="calendar"?a.jsx(Dt,{className:"p-6",children:a.jsx(pGe,{archives:Mt||[],onArchiveClick:He=>{l(""),Y("grid"),re(He.id)},highlightedArchiveId:R})}):B==="grid"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:pt?.map(He=>a.jsx(GZe,{archive:He,printerName:He.printer_id?Ke.get(He.printer_id)||"Unknown":He.sliced_for_model?`Sliced for ${He.sliced_for_model}`:"No Printer",isSelected:ae.has(He.id),onSelect:Le,selectionMode:De,projects:Ve,isHighlighted:He.id===R,timeFormat:Ht,preferredSlicer:Xt,currency:Kt,t,onNavigateToArchive:Ge},He.id))}),a.jsx(DY,{pageIndex:q,pageSize:O,totalRows:Qt,totalPages:dt,onPageChange:de,onPageSizeChange:He=>{G(He),de(0)},t})]}):B==="list"?a.jsxs(a.Fragment,{children:[a.jsx(Dt,{children:a.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[a.jsx("div",{className:"col-span-1"}),a.jsx("div",{className:"col-span-4",children:"Name"}),a.jsx("div",{className:"col-span-2",children:"Printer"}),a.jsx("div",{className:"col-span-2",children:"Date"}),a.jsx("div",{className:"col-span-1",children:"Size"}),a.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),pt?.map(He=>a.jsx(WZe,{archive:He,printerName:He.printer_id?Ke.get(He.printer_id)||"Unknown":He.sliced_for_model?`Sliced for ${He.sliced_for_model}`:"No Printer",isSelected:ae.has(He.id),onSelect:Le,selectionMode:De,projects:Ve,isHighlighted:He.id===R,preferredSlicer:Xt,t,onNavigateToArchive:Ge},He.id))]})}),a.jsx(DY,{pageIndex:q,pageSize:O,totalRows:Qt,totalPages:dt,onPageChange:de,onPageSizeChange:He=>{G(He),de(0)},t})]}):B==="log"?a.jsxs("div",{className:"space-y-4",children:[a.jsx(Dt,{children:a.jsx(Rt,{className:"py-3",children:a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:o,onChange:He=>{l(He.target.value),Re(0)}})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:c||"",onChange:He=>{d(He.target.value?Number(He.target.value):null),Re(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allPrinters")}),Me?.map(He=>a.jsx("option",{value:He.id,children:He.name},He.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:ye||"",onChange:He=>{Ae(He.target.value||null),Re(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allUsers")}),ut?.map(He=>a.jsx("option",{value:He.username,children:He.username},He.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:ve||"",onChange:He=>{Te(He.target.value||null),Re(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allStatuses")}),a.jsx("option",{value:"completed",children:t("archives.status.completed")}),a.jsx("option",{value:"failed",children:t("archives.status.failed")}),a.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),a.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),a.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),a.jsx("input",{type:"date",className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:Fe,onChange:He=>{Ee(He.target.value),Re(0)}})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),a.jsx("input",{type:"date",className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:Se,onChange:He=>{je(He.target.value),Re(0)}})]}),a.jsx("div",{className:"ml-auto",children:a.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>ce(!0),disabled:!r("archives:delete_all")||en.isPending,children:[a.jsx(un,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),a.jsx(Dt,{children:wt?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):xt?.items.length?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),a.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:xt.items.map(He=>a.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[a.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Bf(He.started_at||He.created_at,Ht)}),a.jsx("td",{className:"px-4 py-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[He.thumbnail_path&&a.jsx("img",{src:pe.getPrintLogThumbnail(He.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:St=>{St.target.style.display="none"}}),a.jsx("span",{className:"text-white truncate max-w-[200px]",children:He.print_name||"—"})]})}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:He.printer_name||"—"}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:He.created_by_username||"—"}),a.jsx("td",{className:"px-4 py-3",children:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${He.status==="completed"?"bg-green-500/20 text-green-400":He.status==="failed"?"bg-red-500/20 text-red-400":He.status==="stopped"?"bg-yellow-500/20 text-yellow-400":He.status==="cancelled"?"bg-orange-500/20 text-orange-400":He.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:He.status})}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:He.duration_seconds?ls(He.duration_seconds):"—"}),a.jsx("td",{className:"px-4 py-3",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[He.filament_color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:He.filament_color.startsWith("#")?He.filament_color:void 0}}),a.jsx("span",{className:"text-bambu-gray-light text-xs",children:He.filament_type||"—"})]})})]},He.id))})]})}),a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(qe+ze,xt.total),total:xt.total})}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),a.jsxs("select",{className:"px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",value:ze,onChange:He=>{Ne(Number(He.target.value)),Re(0)},children:[a.jsx("option",{value:10,children:"10"}),a.jsx("option",{value:25,children:"25"}),a.jsx("option",{value:50,children:"50"}),a.jsx("option",{value:100,children:"100"})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(qe/ze)+1," / ",Math.max(1,Math.ceil(xt.total/ze))]}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>Re(Math.max(0,qe-ze)),disabled:qe===0,children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>Re(qe+ze),disabled:qe+ze>=xt.total,children:a.jsx(Va,{className:"w-4 h-4"})})]})]})]}):a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,F&&a.jsx(iGe,{onClose:()=>{$(!1),X([])},initialFiles:I}),ue&&a.jsx(kn,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:ae.size}),confirmText:t("archives.modal.deleteCount",{count:ae.size}),variant:"danger",onConfirm:()=>{Ut.mutate(Array.from(ae)),K(!1)},onCancel:()=>K(!1)}),ne&&a.jsx(lGe,{selectedIds:Array.from(ae),existingTags:ht,onClose:()=>oe(!1)}),be&&a.jsx(cGe,{selectedIds:Array.from(ae),onClose:()=>_e(!1)}),he&&ae.size>=2&&ae.size<=5&&a.jsx(UZe,{archiveIds:Array.from(ae),onClose:()=>{fe(!1),ee(new Set),le(!1)}}),se&&a.jsx(VZe,{onClose:()=>U(!1)}),Ye&&a.jsx(kn,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{en.mutate(),ce(!1)},onCancel:()=>ce(!1)})]})}function DY({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o("archives.prints")}`:a.jsxs(a.Fragment,{children:[o("archives.pagination.showing")," ",t*c+1," ",o("archives.pagination.to")," ",Math.min((t+1)*c,n)," ",o("archives.pagination.of")," ",n," ",o("archives.prints")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("archives.pagination.show")}),a.jsxs("select",{value:e,onChange:d=>s(Number(d.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[25,50,100,200].map(d=>a.jsx("option",{value:d,children:d},d)),a.jsx("option",{value:-1,children:o("archives.pagination.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(dO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("archives.pagination.page")," ",t+1," ",o("archives.pagination.of")," ",r]}),a.jsx("button",{onClick:()=>i(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(uO,{className:"w-4 h-4"})})]})]})]})}function XZe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return w.useMemo(()=>r=>{e.forEach(i=>i(r))},e)}const XT=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function vy(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function Bz(t){return"nodeType"in t}function Ro(t){var e,n;return t?vy(t)?t:Bz(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Hz(t){const{Document:e}=Ro(t);return t instanceof e}function bS(t){return vy(t)?!1:t instanceof Ro(t).HTMLElement}function Foe(t){return t instanceof Ro(t).SVGElement}function wy(t){return t?vy(t)?t.document:Bz(t)?Hz(t)?t:bS(t)||Foe(t)?t.ownerDocument:document:document:document}const Dd=XT?w.useLayoutEffect:w.useEffect;function qz(t){const e=w.useRef(t);return Dd(()=>{e.current=t}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return e.current==null?void 0:e.current(...r)},[])}function QZe(){const t=w.useRef(null),e=w.useCallback((r,i)=>{t.current=setInterval(r,i)},[]),n=w.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function ww(t,e){e===void 0&&(e=[t]);const n=w.useRef(t);return Dd(()=>{n.current!==t&&(n.current=t)},e),n}function xS(t,e){const n=w.useRef();return w.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function mP(t){const e=qz(t),n=w.useRef(null),r=w.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function RL(t){const e=w.useRef();return w.useEffect(()=>{e.current=t},[t]),e.current}let t3={};function yS(t,e){return w.useMemo(()=>{if(e)return e;const n=t3[t]==null?0:t3[t]+1;return t3[t]=n,t+"-"+n},[t,e])}function Roe(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const l=Object.entries(o);for(const[c,d]of l){const u=s[c];u!=null&&(s[c]=u+t*d)}return s},{...e})}}const fx=Roe(1),Sw=Roe(-1);function ZZe(t){return"clientX"in t&&"clientY"in t}function $z(t){if(!t)return!1;const{KeyboardEvent:e}=Ro(t.target);return e&&t instanceof e}function JZe(t){if(!t)return!1;const{TouchEvent:e}=Ro(t.target);return e&&t instanceof e}function LL(t){if(JZe(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 ZZe(t)?{x:t.clientX,y:t.clientY}:null}const Kx=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[Kx.Translate.toString(t),Kx.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),FY="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function eJe(t){return t.matches(FY)?t:t.querySelector(FY)}const tJe={display:"none"};function nJe(t){let{id:e,value:n}=t;return Qr.createElement("div",{id:e,style:tJe},n)}function rJe(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Qr.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function aJe(){const[t,e]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const Loe=w.createContext(null);function iJe(t){const e=w.useContext(Loe);w.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function sJe(){const[t]=w.useState(()=>new Set),e=w.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[w.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const oJe={draggable:`
  8317. To pick up a draggable item, press the space bar.
  8318. While dragging, use the arrow keys to move the item.
  8319. Press space again to drop the item in its new position, or press escape to cancel.
  8320. `},lJe={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 cJe(t){let{announcements:e=lJe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=oJe}=t;const{announce:s,announcement:o}=aJe(),l=yS("DndLiveRegion"),[c,d]=w.useState(!1);if(w.useEffect(()=>{d(!0)},[]),iJe(w.useMemo(()=>({onDragStart(m){let{active:p}=m;s(e.onDragStart({active:p}))},onDragMove(m){let{active:p,over:f}=m;e.onDragMove&&s(e.onDragMove({active:p,over:f}))},onDragOver(m){let{active:p,over:f}=m;s(e.onDragOver({active:p,over:f}))},onDragEnd(m){let{active:p,over:f}=m;s(e.onDragEnd({active:p,over:f}))},onDragCancel(m){let{active:p,over:f}=m;s(e.onDragCancel({active:p,over:f}))}}),[s,e])),!c)return null;const u=Qr.createElement(Qr.Fragment,null,Qr.createElement(nJe,{id:r,value:i.draggable}),Qr.createElement(rJe,{id:l,announcement:o}));return n?Cu.createPortal(u,n):u}var gi;(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"})(gi||(gi={}));function hP(){}function pP(t,e){return w.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function Ooe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return w.useMemo(()=>[...e].filter(r=>r!=null),[...e])}const Oc=Object.freeze({x:0,y:0});function Ioe(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function zoe(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function dJe(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function RY(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Uoe(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function LY(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 Boe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=LY(e,e.left,e.top),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const d=Ioe(LY(c),i);s.push({id:l,data:{droppableContainer:o,value:d}})}}return s.sort(zoe)},uJe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=RY(e),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const d=RY(c),u=i.reduce((p,f,y)=>p+Ioe(d[y],f),0),m=Number((u/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:m}})}}return s.sort(zoe)};function mJe(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r<i&&n<s){const c=e.width*e.height,d=t.width*t.height,u=o*l,m=u/(c+d-u);return Number(m.toFixed(4))}return 0}const hJe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const c=mJe(l,e);c>0&&i.push({id:o,data:{droppableContainer:s,value:c}})}}return i.sort(dJe)};function pJe(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Hoe(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Oc}function fJe(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];return i.reduce((o,l)=>({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const gJe=fJe(1);function bJe(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 xJe(t,e,n){const r=bJe(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,c=t.left-o-(1-i)*parseFloat(n),d=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),u=i?t.width/i:t.width,m=s?t.height/s:t.height;return{width:u,height:m,top:d,right:c+u,bottom:d+m,left:c}}const yJe={ignoreTransform:!1};function Sy(t,e){e===void 0&&(e=yJe);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:d,transformOrigin:u}=Ro(t).getComputedStyle(t);d&&(n=xJe(n,d,u))}const{top:r,left:i,width:s,height:o,bottom:l,right:c}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:c}}function OY(t){return Sy(t,{ignoreTransform:!0})}function vJe(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function wJe(t,e){return e===void 0&&(e=Ro(t).getComputedStyle(t)),e.position==="fixed"}function SJe(t,e){e===void 0&&(e=Ro(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 QT(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Hz(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!bS(i)||Foe(i)||n.includes(i))return n;const s=Ro(t).getComputedStyle(i);return i!==t&&SJe(i,s)&&n.push(i),wJe(i,s)?n:r(i.parentNode)}return t?r(t):n}function qoe(t){const[e]=QT(t,1);return e??null}function n3(t){return!XT||!t?null:vy(t)?t:Bz(t)?Hz(t)||t===wy(t).scrollingElement?window:bS(t)?t:null:null}function $oe(t){return vy(t)?t.scrollX:t.scrollLeft}function Voe(t){return vy(t)?t.scrollY:t.scrollTop}function OL(t){return{x:$oe(t),y:Voe(t)}}var Fi;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(Fi||(Fi={}));function Goe(t){return!XT||!t?!1:t===document.scrollingElement}function Woe(t){const e={x:0,y:0},n=Goe(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const _Je={x:.2,y:.2};function kJe(t,e,n,r,i){let{top:s,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=_Je);const{isTop:d,isBottom:u,isLeft:m,isRight:p}=Woe(t),f={x:0,y:0},y={x:0,y:0},v={height:e.height*i.y,width:e.width*i.x};return!d&&s<=e.top+v.height?(f.y=Fi.Backward,y.y=r*Math.abs((e.top+v.height-s)/v.height)):!u&&c>=e.bottom-v.height&&(f.y=Fi.Forward,y.y=r*Math.abs((e.bottom-v.height-c)/v.height)),!p&&l>=e.right-v.width?(f.x=Fi.Forward,y.x=r*Math.abs((e.right-v.width-l)/v.width)):!m&&o<=e.left+v.width&&(f.x=Fi.Backward,y.x=r*Math.abs((e.left+v.width-o)/v.width)),{direction:f,speed:y}}function NJe(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function Koe(t){return t.reduce((e,n)=>fx(e,OL(n)),Oc)}function CJe(t){return t.reduce((e,n)=>e+$oe(n),0)}function PJe(t){return t.reduce((e,n)=>e+Voe(n),0)}function TJe(t,e){if(e===void 0&&(e=Sy),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);qoe(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const AJe=[["x",["left","right"],CJe],["y",["top","bottom"],PJe]];class Vz{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=QT(n),i=Koe(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of AJe)for(const c of o)Object.defineProperty(this,c,{get:()=>{const d=l(r),u=i[s]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class C0{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function MJe(t){const{EventTarget:e}=Ro(t);return t instanceof e?t:wy(t)}function r3(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var Fl;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Fl||(Fl={}));function IY(t){t.preventDefault()}function jJe(t){t.stopPropagation()}var xr;(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"})(xr||(xr={}));const Yoe={start:[xr.Space,xr.Enter],cancel:[xr.Esc],end:[xr.Space,xr.Enter,xr.Tab]},EJe=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case xr.Right:return{...n,x:n.x+25};case xr.Left:return{...n,x:n.x-25};case xr.Down:return{...n,y:n.y+25};case xr.Up:return{...n,y:n.y-25}}};class ZT{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 C0(wy(n)),this.windowListeners=new C0(Ro(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Fl.Resize,this.handleCancel),this.windowListeners.add(Fl.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Fl.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&TJe(r),n(Oc)}handleKeyDown(e){if($z(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=Yoe,coordinateGetter:o=EJe,scrollBehavior:l="smooth"}=i,{code:c}=e;if(s.end.includes(c)){this.handleEnd(e);return}if(s.cancel.includes(c)){this.handleCancel(e);return}const{collisionRect:d}=r.current,u=d?{x:d.left,y:d.top}:Oc;this.referenceCoordinates||(this.referenceCoordinates=u);const m=o(e,{active:n,context:r.current,currentCoordinates:u});if(m){const p=Sw(m,u),f={x:0,y:0},{scrollableAncestors:y}=r.current;for(const v of y){const b=e.code,{isTop:g,isRight:_,isLeft:k,isBottom:P,maxScroll:N,minScroll:M}=Woe(v),A=NJe(v),T={x:Math.min(b===xr.Right?A.right-A.width/2:A.right,Math.max(b===xr.Right?A.left:A.left+A.width/2,m.x)),y:Math.min(b===xr.Down?A.bottom-A.height/2:A.bottom,Math.max(b===xr.Down?A.top:A.top+A.height/2,m.y))},C=b===xr.Right&&!_||b===xr.Left&&!k,F=b===xr.Down&&!P||b===xr.Up&&!g;if(C&&T.x!==m.x){const $=v.scrollLeft+p.x,I=b===xr.Right&&$<=N.x||b===xr.Left&&$>=M.x;if(I&&!p.y){v.scrollTo({left:$,behavior:l});return}I?f.x=v.scrollLeft-$:f.x=b===xr.Right?v.scrollLeft-N.x:v.scrollLeft-M.x,f.x&&v.scrollBy({left:-f.x,behavior:l});break}else if(F&&T.y!==m.y){const $=v.scrollTop+p.y,I=b===xr.Down&&$<=N.y||b===xr.Up&&$>=M.y;if(I&&!p.x){v.scrollTo({top:$,behavior:l});return}I?f.y=v.scrollTop-$:f.y=b===xr.Down?v.scrollTop-N.y:v.scrollTop-M.y,f.y&&v.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(e,fx(Sw(m,this.referenceCoordinates),f))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}ZT.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=Yoe,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i?.({event:t.nativeEvent}),!0)}return!1}}];function zY(t){return!!(t&&"distance"in t)}function UY(t){return!!(t&&"delay"in t)}class Gz{constructor(e,n,r){var i;r===void 0&&(r=MJe(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=wy(o),this.documentListeners=new C0(this.document),this.listeners=new C0(r),this.windowListeners=new C0(Ro(o)),this.initialCoordinates=(i=LL(s))!=null?i:Oc,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Fl.Resize,this.handleCancel),this.windowListeners.add(Fl.DragStart,IY),this.windowListeners.add(Fl.VisibilityChange,this.handleCancel),this.windowListeners.add(Fl.ContextMenu,IY),this.documentListeners.add(Fl.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(UY(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(zY(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Fl.Click,jJe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Fl.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const c=(n=LL(e))!=null?n:Oc,d=Sw(i,c);if(!r&&l){if(zY(l)){if(l.tolerance!=null&&r3(d,l.tolerance))return this.handleCancel();if(r3(d,l.distance))return this.handleStart()}if(UY(l)&&r3(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===xr.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const DJe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class JT extends Gz{constructor(e){const{event:n}=e,r=wy(n.target);super(e,DJe,r)}}JT.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const FJe={move:{name:"mousemove"},end:{name:"mouseup"}};var IL;(function(t){t[t.RightClick=2]="RightClick"})(IL||(IL={}));class RJe extends Gz{constructor(e){super(e,FJe,wy(e.event.target))}}RJe.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===IL.RightClick?!1:(r?.({event:n}),!0)}}];const a3={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class LJe extends Gz{constructor(e){super(e,a3)}static setup(){return window.addEventListener(a3.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(a3.move.name,e)};function e(){}}}LJe.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var P0;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(P0||(P0={}));var fP;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(fP||(fP={}));function OJe(t){let{acceleration:e,activator:n=P0.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=fP.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:m,threshold:p}=t;const f=zJe({delta:m,disabled:!s}),[y,v]=QZe(),b=w.useRef({x:0,y:0}),g=w.useRef({x:0,y:0}),_=w.useMemo(()=>{switch(n){case P0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case P0.DraggableRect:return i}},[n,i,c]),k=w.useRef(null),P=w.useCallback(()=>{const M=k.current;if(!M)return;const A=b.current.x*g.current.x,T=b.current.y*g.current.y;M.scrollBy(A,T)},[]),N=w.useMemo(()=>l===fP.TreeOrder?[...d].reverse():d,[l,d]);w.useEffect(()=>{if(!s||!d.length||!_){v();return}for(const M of N){if(r?.(M)===!1)continue;const A=d.indexOf(M),T=u[A];if(!T)continue;const{direction:C,speed:F}=kJe(M,T,_,e,p);for(const $ of["x","y"])f[$][C[$]]||(F[$]=0,C[$]=0);if(F.x>0||F.y>0){v(),k.current=M,y(P,o),b.current=F,g.current=C;return}}b.current={x:0,y:0},g.current={x:0,y:0},v()},[e,P,r,v,s,o,JSON.stringify(_),JSON.stringify(f),y,d,N,u,JSON.stringify(p)])}const IJe={x:{[Fi.Backward]:!1,[Fi.Forward]:!1},y:{[Fi.Backward]:!1,[Fi.Forward]:!1}};function zJe(t){let{delta:e,disabled:n}=t;const r=RL(e);return xS(i=>{if(n||!r||!i)return IJe;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[Fi.Backward]:i.x[Fi.Backward]||s.x===-1,[Fi.Forward]:i.x[Fi.Forward]||s.x===1},y:{[Fi.Backward]:i.y[Fi.Backward]||s.y===-1,[Fi.Forward]:i.y[Fi.Forward]||s.y===1}}},[n,e,r])}function UJe(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return xS(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function BJe(t,e){return w.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var _w;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(_w||(_w={}));var zL;(function(t){t.Optimized="optimized"})(zL||(zL={}));const BY=new Map;function HJe(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=w.useState(null),{frequency:l,measure:c,strategy:d}=i,u=w.useRef(t),m=b(),p=ww(m),f=w.useCallback(function(g){g===void 0&&(g=[]),!p.current&&o(_=>_===null?g:_.concat(g.filter(k=>!_.includes(k))))},[p]),y=w.useRef(null),v=xS(g=>{if(m&&!n)return BY;if(!g||g===BY||u.current!==t||s!=null){const _=new Map;for(let k of t){if(!k)continue;if(s&&s.length>0&&!s.includes(k.id)&&k.rect.current){_.set(k.id,k.rect.current);continue}const P=k.node.current,N=P?new Vz(c(P),P):null;k.rect.current=N,N&&_.set(k.id,N)}return _}return g},[t,s,n,m,c]);return w.useEffect(()=>{u.current=t},[t]),w.useEffect(()=>{m||f()},[n,m]),w.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),w.useEffect(()=>{m||typeof l!="number"||y.current!==null||(y.current=setTimeout(()=>{f(),y.current=null},l))},[l,m,f,...r]),{droppableRects:v,measureDroppableContainers:f,measuringScheduled:s!=null};function b(){switch(d){case _w.Always:return!1;case _w.BeforeDragging:return n;default:return!n}}}function Xoe(t,e){return xS(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function qJe(t,e){return Xoe(t,e)}function $Je(t){let{callback:e,disabled:n}=t;const r=qz(e),i=w.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return w.useEffect(()=>()=>i?.disconnect(),[i]),i}function eA(t){let{callback:e,disabled:n}=t;const r=qz(e),i=w.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return w.useEffect(()=>()=>i?.disconnect(),[i]),i}function VJe(t){return new Vz(Sy(t),t)}function HY(t,e,n){e===void 0&&(e=VJe);const[r,i]=w.useState(null);function s(){i(c=>{if(!t)return null;if(t.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=e(t);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const o=$Je({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=eA({callback:s});return Dd(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),r}function GJe(t){const e=Xoe(t);return Hoe(t,e)}const qY=[];function WJe(t){const e=w.useRef(t),n=xS(r=>t?r&&r!==qY&&t&&e.current&&t.parentNode===e.current.parentNode?r:QT(t):qY,[t]);return w.useEffect(()=>{e.current=t},[t]),n}function KJe(t){const[e,n]=w.useState(null),r=w.useRef(t),i=w.useCallback(s=>{const o=n3(s.target);o&&n(l=>l?(l.set(o,OL(o)),new Map(l)):null)},[]);return w.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(c=>{const d=n3(c);return d?(d.addEventListener("scroll",i,{passive:!0}),[d,OL(d)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(c=>{const d=n3(c);d?.removeEventListener("scroll",i)})}},[i,t]),w.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>fx(s,o),Oc):Koe(t):Oc,[t,e])}function $Y(t,e){e===void 0&&(e=[]);const n=w.useRef(null);return w.useEffect(()=>{n.current=null},e),w.useEffect(()=>{const r=t!==Oc;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?Sw(t,n.current):Oc}function YJe(t){w.useEffect(()=>{if(!XT)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function XJe(t,e){return w.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function Qoe(t){return w.useMemo(()=>t?vJe(t):null,[t])}const VY=[];function QJe(t,e){e===void 0&&(e=Sy);const[n]=t,r=Qoe(n?Ro(n):null),[i,s]=w.useState(VY);function o(){s(()=>t.length?t.map(c=>Goe(c)?r:new Vz(e(c),c)):VY)}const l=eA({callback:o});return Dd(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),i}function ZJe(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return bS(e)?e:t}function JJe(t){let{measure:e}=t;const[n,r]=w.useState(null),i=w.useCallback(d=>{for(const{target:u}of d)if(bS(u)){r(m=>{const p=e(u);return m?{...m,width:p.width,height:p.height}:p});break}},[e]),s=eA({callback:i}),o=w.useCallback(d=>{const u=ZJe(d);s?.disconnect(),u&&s?.observe(u),r(u?e(u):null)},[e,s]),[l,c]=mP(o);return w.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const eet=[{sensor:JT,options:{}},{sensor:ZT,options:{}}],tet={current:{}},qk={draggable:{measure:OY},droppable:{measure:OY,strategy:_w.WhileDragging,frequency:zL.Optimized},dragOverlay:{measure:Sy}};class T0 extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const net={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new T0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:hP},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:qk,measureDroppableContainers:hP,windowRect:null,measuringScheduled:!1},ret={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:hP,draggableNodes:new Map,over:null,measureDroppableContainers:hP},tA=w.createContext(ret),Zoe=w.createContext(net);function aet(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new T0}}}function iet(t,e){switch(e.type){case gi.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case gi.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 gi.DragEnd:case gi.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case gi.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new T0(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case gi.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new T0(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case gi.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new T0(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function set(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=w.useContext(tA),s=RL(r),o=RL(n?.id);return w.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!$z(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:c,node:d}=l;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const m=eJe(u);if(m){m.focus();break}}})}},[r,e,i,o,s]),null}function oet(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function cet(t){return w.useMemo(()=>({draggable:{...qk.draggable,...t?.draggable},droppable:{...qk.droppable,...t?.droppable},dragOverlay:{...qk.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function det(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=w.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;Dd(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const d=e?.node.current;if(!d||d.isConnected===!1)return;const u=n(d),m=Hoe(u,r);if(o||(m.x=0),l||(m.y=0),s.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const p=qoe(d);p&&p.scrollBy({top:m.y,left:m.x})}},[e,o,l,r,n])}const Joe=w.createContext({...Oc,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 ele=w.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:c=!0,children:d,sensors:u=eet,collisionDetection:m=hJe,measuring:p,modifiers:f,...y}=e;const v=w.useReducer(iet,void 0,aet),[b,g]=v,[_,k]=sJe(),[P,N]=w.useState(dh.Uninitialized),M=P===dh.Initialized,{draggable:{active:A,nodes:T,translate:C},droppable:{containers:F}}=b,$=A!=null?T.get(A):null,I=w.useRef({initial:null,translated:null}),X=w.useMemo(()=>{var Ge;return A!=null?{id:A,data:(Ge=$?.data)!=null?Ge:tet,rect:I}:null},[A,$]),L=w.useRef(null),[te,ae]=w.useState(null),[ee,me]=w.useState(null),le=ww(y,Object.values(y)),ue=yS("DndDescribedBy",o),K=w.useMemo(()=>F.getEnabled(),[F]),ne=cet(p),{droppableRects:oe,measureDroppableContainers:be,measuringScheduled:_e}=HJe(K,{dragging:M,dependencies:[C.x,C.y],config:ne.droppable}),B=UJe(T,A),Y=w.useMemo(()=>ee?LL(ee):null,[ee]),D=Ne(),j=qJe(B,ne.draggable.measure);det({activeNode:A!=null?T.get(A):null,config:D.layoutShiftCompensation,initialRect:j,measure:ne.draggable.measure});const z=HY(B,ne.draggable.measure,j),W=HY(B?B.parentElement:null),q=w.useRef({activatorEvent:null,active:null,activeNode:B,collisionRect:null,collisions:null,droppableRects:oe,draggableNodes:T,draggingNode:null,draggingNodeRect:null,droppableContainers:F,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),de=F.getNodeFor((n=q.current.over)==null?void 0:n.id),O=JJe({measure:ne.dragOverlay.measure}),G=(r=O.nodeRef.current)!=null?r:B,Q=M?(i=O.rect)!=null?i:z:null,V=!!(O.nodeRef.current&&O.rect),J=GJe(V?null:z),ie=Qoe(G?Ro(G):null),he=WJe(M?de??B:null),fe=QJe(he),se=oet(f,{transform:{x:C.x-J.x,y:C.y-J.y,scaleX:1,scaleY:1},activatorEvent:ee,active:X,activeNodeRect:z,containerNodeRect:W,draggingNodeRect:Q,over:q.current.over,overlayNodeRect:O.rect,scrollableAncestors:he,scrollableAncestorRects:fe,windowRect:ie}),U=Y?fx(Y,C):null,R=KJe(he),re=$Y(R),xe=$Y(R,[z]),we=fx(se,re),ye=Q?gJe(Q,se):null,Ae=X&&ye?m({active:X,collisionRect:ye,droppableRects:oe,droppableContainers:K,pointerCoordinates:U}):null,ve=Uoe(Ae,"id"),[Te,Fe]=w.useState(null),Ee=V?se:fx(se,xe),Se=pJe(Ee,(s=Te?.rect)!=null?s:null,z),je=w.useRef(null),qe=w.useCallback((Ge,$e)=>{let{sensor:Pe,options:Me}=$e;if(L.current==null)return;const Ve=T.get(L.current);if(!Ve)return;const tt=Ge.nativeEvent,ut=new Pe({active:L.current,activeNode:Ve,event:tt,options:Me,context:q,onAbort(wt){if(!T.get(wt))return;const{onDragAbort:Xt}=le.current,Kt={id:wt};Xt?.(Kt),_({type:"onDragAbort",event:Kt})},onPending(wt,Ht,Xt,Kt){if(!T.get(wt))return;const{onDragPending:en}=le.current,Ke={id:wt,constraint:Ht,initialCoordinates:Xt,offset:Kt};en?.(Ke),_({type:"onDragPending",event:Ke})},onStart(wt){const Ht=L.current;if(Ht==null)return;const Xt=T.get(Ht);if(!Xt)return;const{onDragStart:Kt}=le.current,Ut={activatorEvent:tt,active:{id:Ht,data:Xt.data,rect:I}};Cu.unstable_batchedUpdates(()=>{Kt?.(Ut),N(dh.Initializing),g({type:gi.DragStart,initialCoordinates:wt,active:Ht}),_({type:"onDragStart",event:Ut}),ae(je.current),me(tt)})},onMove(wt){g({type:gi.DragMove,coordinates:wt})},onEnd:xt(gi.DragEnd),onCancel:xt(gi.DragCancel)});je.current=ut;function xt(wt){return async function(){const{active:Xt,collisions:Kt,over:Ut,scrollAdjustedTranslate:en}=q.current;let Ke=null;if(Xt&&en){const{cancelDrop:Ft}=le.current;Ke={activatorEvent:tt,active:Xt,collisions:Kt,delta:en,over:Ut},wt===gi.DragEnd&&typeof Ft=="function"&&await Promise.resolve(Ft(Ke))&&(wt=gi.DragCancel)}L.current=null,Cu.unstable_batchedUpdates(()=>{g({type:wt}),N(dh.Uninitialized),Fe(null),ae(null),me(null),je.current=null;const Ft=wt===gi.DragEnd?"onDragEnd":"onDragCancel";if(Ke){const Nt=le.current[Ft];Nt?.(Ke),_({type:Ft,event:Ke})}})}}},[T]),Re=w.useCallback((Ge,$e)=>(Pe,Me)=>{const Ve=Pe.nativeEvent,tt=T.get(Me);if(L.current!==null||!tt||Ve.dndKit||Ve.defaultPrevented)return;const ut={active:tt};Ge(Pe,$e.options,ut)===!0&&(Ve.dndKit={capturedBy:$e.sensor},L.current=Me,qe(Pe,$e))},[T,qe]),Ye=BJe(u,Re);YJe(u),Dd(()=>{z&&P===dh.Initializing&&N(dh.Initialized)},[z,P]),w.useEffect(()=>{const{onDragMove:Ge}=le.current,{active:$e,activatorEvent:Pe,collisions:Me,over:Ve}=q.current;if(!$e||!Pe)return;const tt={active:$e,activatorEvent:Pe,collisions:Me,delta:{x:we.x,y:we.y},over:Ve};Cu.unstable_batchedUpdates(()=>{Ge?.(tt),_({type:"onDragMove",event:tt})})},[we.x,we.y]),w.useEffect(()=>{const{active:Ge,activatorEvent:$e,collisions:Pe,droppableContainers:Me,scrollAdjustedTranslate:Ve}=q.current;if(!Ge||L.current==null||!$e||!Ve)return;const{onDragOver:tt}=le.current,ut=Me.get(ve),xt=ut&&ut.rect.current?{id:ut.id,rect:ut.rect.current,data:ut.data,disabled:ut.disabled}:null,wt={active:Ge,activatorEvent:$e,collisions:Pe,delta:{x:Ve.x,y:Ve.y},over:xt};Cu.unstable_batchedUpdates(()=>{Fe(xt),tt?.(wt),_({type:"onDragOver",event:wt})})},[ve]),Dd(()=>{q.current={activatorEvent:ee,active:X,activeNode:B,collisionRect:ye,collisions:Ae,droppableRects:oe,draggableNodes:T,draggingNode:G,draggingNodeRect:Q,droppableContainers:F,over:Te,scrollableAncestors:he,scrollAdjustedTranslate:we},I.current={initial:Q,translated:ye}},[X,B,Ae,ye,T,G,Q,oe,F,Te,he,we]),OJe({...D,delta:C,draggingRect:ye,pointerCoordinates:U,scrollableAncestors:he,scrollableAncestorRects:fe});const ce=w.useMemo(()=>({active:X,activeNode:B,activeNodeRect:z,activatorEvent:ee,collisions:Ae,containerNodeRect:W,dragOverlay:O,draggableNodes:T,droppableContainers:F,droppableRects:oe,over:Te,measureDroppableContainers:be,scrollableAncestors:he,scrollableAncestorRects:fe,measuringConfiguration:ne,measuringScheduled:_e,windowRect:ie}),[X,B,z,ee,Ae,W,O,T,F,oe,Te,be,he,fe,ne,_e,ie]),ze=w.useMemo(()=>({activatorEvent:ee,activators:Ye,active:X,activeNodeRect:z,ariaDescribedById:{draggable:ue},dispatch:g,draggableNodes:T,over:Te,measureDroppableContainers:be}),[ee,Ye,X,z,g,ue,T,Te,be]);return Qr.createElement(Loe.Provider,{value:k},Qr.createElement(tA.Provider,{value:ze},Qr.createElement(Zoe.Provider,{value:ce},Qr.createElement(Joe.Provider,{value:Se},d)),Qr.createElement(set,{disabled:l?.restoreFocus===!1})),Qr.createElement(cJe,{...l,hiddenTextDescribedById:ue}));function Ne(){const Ge=te?.autoScrollEnabled===!1,$e=typeof c=="object"?c.enabled===!1:c===!1,Pe=M&&!Ge&&!$e;return typeof c=="object"?{...c,enabled:Pe}:{enabled:Pe}}}),uet=w.createContext(null),GY="button",met="Draggable";function het(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=yS(met),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:m,over:p}=w.useContext(tA),{role:f=GY,roleDescription:y="draggable",tabIndex:v=0}=i??{},b=c?.id===e,g=w.useContext(b?Joe:uet),[_,k]=mP(),[P,N]=mP(),M=XJe(o,e),A=ww(n);Dd(()=>(m.set(e,{id:e,key:s,node:_,activatorNode:P,data:A}),()=>{const C=m.get(e);C&&C.key===s&&m.delete(e)}),[m,e]);const T=w.useMemo(()=>({role:f,tabIndex:v,"aria-disabled":r,"aria-pressed":b&&f===GY?!0:void 0,"aria-roledescription":y,"aria-describedby":u.draggable}),[r,f,v,b,y,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:T,isDragging:b,listeners:r?void 0:M,node:_,over:p,setNodeRef:k,setActivatorNodeRef:N,transform:g}}function pet(){return w.useContext(Zoe)}const fet="Droppable",get={timeout:25};function bet(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=yS(fet),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=w.useContext(tA),u=w.useRef({disabled:n}),m=w.useRef(!1),p=w.useRef(null),f=w.useRef(null),{disabled:y,updateMeasurementsFor:v,timeout:b}={...get,...i},g=ww(v??r),_=w.useCallback(()=>{if(!m.current){m.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(g.current)?g.current:[g.current]),f.current=null},b)},[b]),k=eA({callback:_,disabled:y||!o}),P=w.useCallback((T,C)=>{k&&(C&&(k.unobserve(C),m.current=!1),T&&k.observe(T))},[k]),[N,M]=mP(P),A=ww(e);return w.useEffect(()=>{!k||!N.current||(k.disconnect(),m.current=!1,k.observe(N.current))},[N,k]),w.useEffect(()=>(l({type:gi.RegisterDroppable,element:{id:r,key:s,disabled:n,node:N,rect:p,data:A}}),()=>l({type:gi.UnregisterDroppable,key:s,id:r})),[r]),w.useEffect(()=>{n!==u.current.disabled&&(l({type:gi.SetDroppableDisabled,id:r,key:s,disabled:n}),u.current.disabled=n)},[r,s,n,l]),{active:o,rect:p,isOver:c?.id===r,node:N,over:c,setNodeRef:M}}function nA(t,e,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function xet(t,e){return t.reduce((n,r,i)=>{const s=e.get(r);return s&&(n[i]=s),n},Array(t.length))}function dk(t){return t!==null&&t>=0}function yet(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 vet(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const Wz=t=>{let{rects:e,activeIndex:n,overIndex:r,index:i}=t;const s=nA(e,r,n),o=e[i],l=s[i];return!l||!o?null:{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}},uk={scaleX:1,scaleY:1},wet=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:r;if(!l)return null;if(i===n){const d=s[o];return d?{x:0,y:n<o?d.top+d.height-(l.top+l.height):d.top-l.top,...uk}:null}const c=_et(s,i,n);return i>n&&i<=o?{x:0,y:-l.height-c,...uk}:i<n&&i>=o?{x:0,y:l.height+c,...uk}:{x:0,y:0,...uk}};function _et(t,e,n){const r=t[e],i=t[e-1],s=t[e+1];return r?n<e?i?r.top-(i.top+i.height):s?s.top-(r.top+r.height):0:s?s.top-(r.top+r.height):i?r.top-(i.top+i.height):0:0}const tle="Sortable",nle=Qr.createContext({activeIndex:-1,containerId:tle,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Wz,disabled:{draggable:!1,droppable:!1}});function rle(t){let{children:e,id:n,items:r,strategy:i=Wz,disabled:s=!1}=t;const{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=pet(),m=yS(tle,n),p=l.rect!==null,f=w.useMemo(()=>r.map(M=>typeof M=="object"&&"id"in M?M.id:M),[r]),y=o!=null,v=o?f.indexOf(o.id):-1,b=d?f.indexOf(d.id):-1,g=w.useRef(f),_=!yet(f,g.current),k=b!==-1&&v===-1||_,P=vet(s);Dd(()=>{_&&y&&u(f)},[_,f,y,u]),w.useEffect(()=>{g.current=f},[f]);const N=w.useMemo(()=>({activeIndex:v,containerId:m,disabled:P,disableTransforms:k,items:f,overIndex:b,useDragOverlay:p,sortedRects:xet(f,c),strategy:i}),[v,m,P.draggable,P.droppable,k,f,b,c,p,i]);return Qr.createElement(nle.Provider,{value:N},e)}const ket=t=>{let{id:e,items:n,activeIndex:r,overIndex:i}=t;return nA(n,r,i).indexOf(e)},Net=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=t;return!d||!r||l!==s&&i===o?!1:n?!0:o!==i&&e===c},Cet={duration:200,easing:"ease"},ale="transform",Pet=Kx.Transition.toString({property:ale,duration:0,easing:"linear"}),Tet={roleDescription:"sortable"};function Aet(t){let{disabled:e,index:n,node:r,rect:i}=t;const[s,o]=w.useState(null),l=w.useRef(n);return Dd(()=>{if(!e&&n!==l.current&&r.current){const c=i.current;if(c){const d=Sy(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&o(u)}}n!==l.current&&(l.current=n)},[e,n,r,i]),w.useEffect(()=>{s&&o(null)},[s]),s}function ile(t){let{animateLayoutChanges:e=Net,attributes:n,disabled:r,data:i,getNewIndex:s=ket,id:o,strategy:l,resizeObserverConfig:c,transition:d=Cet}=t;const{items:u,containerId:m,activeIndex:p,disabled:f,disableTransforms:y,sortedRects:v,overIndex:b,useDragOverlay:g,strategy:_}=w.useContext(nle),k=Met(r,f),P=u.indexOf(o),N=w.useMemo(()=>({sortable:{containerId:m,index:P,items:u},...i}),[m,i,P,u]),M=w.useMemo(()=>u.slice(u.indexOf(o)),[u,o]),{rect:A,node:T,isOver:C,setNodeRef:F}=bet({id:o,data:N,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...c}}),{active:$,activatorEvent:I,activeNodeRect:X,attributes:L,setNodeRef:te,listeners:ae,isDragging:ee,over:me,setActivatorNodeRef:le,transform:ue}=het({id:o,data:N,attributes:{...Tet,...n},disabled:k.draggable}),K=XZe(F,te),ne=!!$,oe=ne&&!y&&dk(p)&&dk(b),be=!g&&ee,_e=be&&oe?ue:null,Y=oe?_e??(l??_)({rects:v,activeNodeRect:X,activeIndex:p,overIndex:b,index:P}):null,D=dk(p)&&dk(b)?s({id:o,items:u,activeIndex:p,overIndex:b}):P,j=$?.id,z=w.useRef({activeId:j,items:u,newIndex:D,containerId:m}),W=u!==z.current.items,q=e({active:$,containerId:m,isDragging:ee,isSorting:ne,id:o,index:P,items:u,newIndex:z.current.newIndex,previousItems:z.current.items,previousContainerId:z.current.containerId,transition:d,wasDragging:z.current.activeId!=null}),de=Aet({disabled:!q,index:P,node:T,rect:A});return w.useEffect(()=>{ne&&z.current.newIndex!==D&&(z.current.newIndex=D),m!==z.current.containerId&&(z.current.containerId=m),u!==z.current.items&&(z.current.items=u)},[ne,D,m,u]),w.useEffect(()=>{if(j===z.current.activeId)return;if(j!=null&&z.current.activeId==null){z.current.activeId=j;return}const G=setTimeout(()=>{z.current.activeId=j},50);return()=>clearTimeout(G)},[j]),{active:$,activeIndex:p,attributes:L,data:N,rect:A,index:P,newIndex:D,items:u,isOver:C,isSorting:ne,isDragging:ee,listeners:ae,node:T,overIndex:b,over:me,setNodeRef:K,setActivatorNodeRef:le,setDroppableNodeRef:F,setDraggableNodeRef:te,transform:de??Y,transition:O()};function O(){if(de||W&&z.current.newIndex===P)return Pet;if(!(be&&!$z(I)||!d)&&(ne||q))return Kx.Transition.toString({...d,property:ale})}}function Met(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function gP(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 jet=[xr.Down,xr.Right,xr.Up,xr.Left],sle=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(jet.includes(t.code)){if(t.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const p=i.get(m.id);if(p)switch(t.code){case xr.Down:r.top<p.top&&c.push(m);break;case xr.Up:r.top>p.top&&c.push(m);break;case xr.Left:r.left>p.left&&c.push(m);break;case xr.Right:r.left<p.left&&c.push(m);break}});const d=uJe({collisionRect:r,droppableRects:i,droppableContainers:c});let u=Uoe(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,y=p?.node.current;if(y&&f&&m&&p){const b=QT(y).some((M,A)=>l[A]!==M),g=ole(m,p),_=Eet(m,p),k=b||!g?{x:0,y:0}:{x:_?r.width-f.width:0,y:_?r.height-f.height:0},P={x:f.left,y:f.top};return k.x&&k.y?P:Sw(P,k)}}}};function ole(t,e){return!gP(t)||!gP(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function Eet(t,e){return!gP(t)||!gP(e)||!ole(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}function Det(t){return t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function Fet({activeCount:t,pendingCount:e,totalTime:n,totalWeight:r,historyCount:i,t:s}){const o=[{icon:Ds,value:t,label:s("queue.summary.printing"),color:"text-blue-400"},{icon:rr,value:e,label:s("queue.summary.queued"),color:"text-yellow-400"},{icon:Pc,value:ls(n),label:s("queue.summary.totalTime"),color:"text-bambu-green"},{icon:CQ,value:Det(r),label:s("queue.summary.totalWeight"),color:"text-purple-400"},{icon:fr,value:i,label:s("queue.summary.history"),color:"text-bambu-gray"}];return a.jsx("div",{className:"flex items-center gap-3 sm:gap-5 flex-wrap px-4 py-3 bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary mb-6",children:o.map((l,c)=>a.jsxs("div",{className:"flex items-center gap-3",children:[c>0&&a.jsx("span",{className:"hidden sm:block text-bambu-dark-tertiary",children:"|"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(l.icon,{className:`w-4 h-4 ${l.color}`}),a.jsx("span",{className:"text-sm font-semibold text-white",children:l.value}),a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:l.label})]})]},c))})}const WY={completed:{icon:fr,color:"text-emerald-400",border:"border-l-emerald-500"},failed:{icon:$a,color:"text-red-400",border:"border-l-red-500"},skipped:{icon:CP,color:"text-orange-400",border:"border-l-gray-500"},cancelled:{icon:Bt,color:"text-gray-400",border:"border-l-gray-500"}};function Ret({item:t,onRequeue:e,onRemove:n,timeFormat:r="system",hasPermission:i,canModify:s,t:o}){const l=WY[t.status]||WY.cancelled,c=l.icon,d=t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,u=t.archive_thumbnail?pe.getArchiveThumbnail(t.archive_id):t.library_file_thumbnail?pe.getLibraryFileThumbnailUrl(t.library_file_id):null,m=t.completed_at||t.created_at;return a.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 px-3 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary border-l-[3px] ${l.border}`,children:[a.jsx(c,{className:`w-4 h-4 shrink-0 ${l.color}`}),a.jsx("div",{className:"w-8 h-8 shrink-0 bg-bambu-dark rounded overflow-hidden",children:u?a.jsx("img",{src:u,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ea,{className:"w-4 h-4"})})}),a.jsx("span",{className:"text-sm text-white font-medium truncate min-w-0 flex-1",children:d}),t.printer_name&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[a.jsx(Pr,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate max-w-[100px]",children:t.printer_name})]}),t.print_time_seconds&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[a.jsx(Pc,{className:"w-3 h-3"}),ls(t.print_time_seconds)]}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:Sx(m,r,o)}),a.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:e,disabled:!i("queue:create"),title:i("queue:create")?o("queue.actions.requeue"):o("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5",children:a.jsx(vr,{className:"w-3.5 h-3.5"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,disabled:!s("queue","delete",t.created_by_id),title:s("queue","delete",t.created_by_id)?o("common.remove"):o("queue.permissions.noRemove"),className:"p-1.5",children:a.jsx(un,{className:"w-3.5 h-3.5"})})]})]})}function Hv(t){const e=new Date(t);return e.setHours(0,0,0,0),e}function Let(t){return t.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}function Oet(t){return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function Iet(t,e){if(t<=0)return e("queue.timeline.time.anyMoment");const n=Math.round(t/6e4);if(n<60)return e("queue.timeline.time.minutesLeft",{minutes:n});const r=Math.floor(n/60),i=n%60;return i===0?e("queue.timeline.time.hoursLeft",{hours:r}):e("queue.timeline.time.hoursMinutesLeft",{hours:r,minutes:i})}function zet(t){const e=new Date;return e.setHours(t,0,0,0),e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function Uet({event:t,now:e,onItemClick:n,t:r}){const i=t.item,s=i.archive_name||i.library_file_name||r("common.unknown"),o=i.printer_name||(i.target_model?`${r("queue.filter.any")} ${i.target_model}`:r("queue.timeline.unassigned")),l=t.type==="printing",c=t.estimatedEnd.getTime()-e.getTime(),d=i.archive_thumbnail?pe.getArchiveThumbnail(i.archive_id):i.library_file_thumbnail?pe.getLibraryFileThumbnailUrl(i.library_file_id):null;return a.jsxs("div",{className:`flex items-center gap-3 px-3 sm:px-4 py-3 bg-bambu-dark-secondary rounded-xl border cursor-pointer transition-all hover:border-bambu-green/40
  8321. ${l?"border-blue-500/30":"border-bambu-dark-tertiary"}`,onClick:()=>n(i),children:[a.jsx("div",{className:`w-1 self-stretch rounded-full shrink-0 ${l?"bg-blue-500":"bg-bambu-green/40"}`}),a.jsx("div",{className:"w-10 h-10 shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:d?a.jsx("img",{src:d,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ea,{className:"w-5 h-5"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:s}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[a.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",children:[a.jsx(Pr,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:o})]}),i.print_time_seconds&&a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray",children:ls(i.print_time_seconds)})]}),l&&t.progress!=null&&a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all",style:{width:`${t.progress}%`}})}),a.jsxs("span",{className:"text-xs text-blue-400 shrink-0",children:[Math.round(t.progress),"%"]})]})]}),a.jsxs("div",{className:"text-right shrink-0",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:Oet(t.estimatedEnd)}),a.jsx("p",{className:`text-xs mt-0.5 ${l?"text-blue-400":"text-bambu-gray"}`,children:Iet(c,r)})]})]})}function Bet({queueItems:t,printerStatuses:e,onItemClick:n,t:r}){const[i,s]=w.useState(()=>Hv(new Date)),[o,l]=w.useState(()=>new Date),[c,d]=w.useState("all");w.useEffect(()=>{const T=setInterval(()=>l(new Date),6e4);return()=>clearInterval(T)},[]);const u=o.getTime(),m=Hv(new Date).getTime()===Hv(i).getTime(),p=w.useMemo(()=>{const T=[],C=new Map;for(const F of t)if(F.status==="printing"){const $=F.printer_id!=null?e[F.printer_id]:void 0,I=Qn(F.started_at)||new Date;let X;if($?.remaining_time!=null&&$.remaining_time>0)X=new Date(u+$.remaining_time*60*1e3);else if(F.print_time_seconds){const L=$?.progress||0,te=Math.max(0,1-L/100);X=new Date(u+F.print_time_seconds*te*1e3)}else X=new Date(u+36e5);T.push({item:F,estimatedStart:I,estimatedEnd:X,progress:$?.progress??void 0,type:"printing"})}else if(F.status==="pending"){const $=F.printer_id;C.has($)||C.set($,[]),C.get($).push(F)}for(const[F,$]of C){$.sort((X,L)=>X.position-L.position);let I=u;for(const X of T)X.item.printer_id===F&&X.type==="printing"&&(I=Math.max(I,X.estimatedEnd.getTime()));for(const X of $){const L=Qn(X.scheduled_time);if(L){const me=Date.now()+15552e6;L.getTime()<=me&&(I=Math.max(I,L.getTime()))}const te=(X.print_time_seconds||3600)*1e3,ae=new Date(I),ee=new Date(I+te);T.push({item:X,estimatedStart:ae,estimatedEnd:ee,type:"queued"}),I=ee.getTime()}}return T.sort((F,$)=>F.estimatedEnd.getTime()-$.estimatedEnd.getTime()),T},[t,e,u]),f=Hv(i).getTime(),y=f+1440*60*1e3-1,v=w.useMemo(()=>p.filter(T=>{const C=T.estimatedEnd.getTime();return C<f||C>y?!1:c==="printing"?T.type==="printing":c==="queued"?T.type==="queued":!0}),[p,f,y,c]),b=w.useMemo(()=>{const T=new Map;for(const C of v){const F=C.estimatedEnd.getHours();T.has(F)||T.set(F,[]),T.get(F).push(C)}return Array.from(T.entries()).sort(([C],[F])=>C-F)},[v]),g=p.filter(T=>T.type==="printing"&&T.estimatedEnd.getTime()>=f&&T.estimatedEnd.getTime()<=y).length,_=p.filter(T=>T.type==="queued"&&T.estimatedEnd.getTime()>=f&&T.estimatedEnd.getTime()<=y).length,k=w.useMemo(()=>{let T=0;for(const C of p)T=Math.max(T,C.estimatedEnd.getTime());return T>0?new Date(T):null},[p]),P=()=>s(Hv(new Date)),N=()=>{const T=new Date(i);T.setDate(T.getDate()-1),s(T)},M=()=>{const T=new Date(i);T.setDate(T.getDate()+1),s(T)},A=[{key:"all",label:r("queue.timeline.filterAll"),count:g+_},{key:"printing",label:r("queue.timeline.filterPrinting"),count:g},{key:"queued",label:r("queue.timeline.filterQueued"),count:_}];return a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:N,className:"p-1.5",children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-sm font-medium text-white min-w-[140px] text-center",children:Let(i)}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:M,className:"p-1.5",children:a.jsx(Va,{className:"w-4 h-4"})}),!m&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:P,className:"text-xs text-bambu-green",children:r("queue.timeline.day.today")})]}),k&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),r("queue.timeline.allDoneBy",{time:k.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]})]}),a.jsx("div",{className:"flex gap-2 mb-5",children:A.map(T=>a.jsxs("button",{onClick:()=>d(T.key),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${c===T.key?"bg-bambu-green text-white":"bg-bambu-dark-secondary border border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[T.label,T.count>0&&a.jsx("span",{className:`ml-1.5 text-xs ${c===T.key?"text-white/70":"text-bambu-gray"}`,children:T.count})]},T.key))}),b.length>0?a.jsx("div",{className:"space-y-6",children:b.map(([T,C])=>a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[a.jsx("span",{className:"text-xs font-medium text-bambu-gray w-14 shrink-0",children:zet(T)}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a.jsx("div",{className:"space-y-2 sm:ml-[68px]",children:C.map(F=>a.jsx(Uet,{event:F,now:o,onItemClick:n,t:r},F.item.id))})]},T))}):a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[a.jsx(ea,{className:"w-12 h-12 mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:r("queue.timeline.noData")})]})]})}function Het(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function qet({status:t,waitingReason:e,printerState:n,t:r}){if(t==="pending"&&e)return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-400 bg-purple-400/10 border-purple-400/20",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),r("queue.status.waiting")]});if(t==="printing"&&n==="PAUSE")return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-400 bg-yellow-400/10 border-yellow-400/20",children:[a.jsx(Fw,{className:"w-3.5 h-3.5"}),r("queue.status.paused")]});const i={pending:{icon:rr,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:r("queue.status.pending")},printing:{icon:Ds,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:r("queue.status.printing")},completed:{icon:fr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:r("queue.status.completed")},failed:{icon:$a,color:"text-status-error bg-status-error/10 border-status-error/20",label:r("queue.status.failed")},skipped:{icon:CP,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:r("queue.status.skipped")},cancelled:{icon:Bt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:r("queue.status.cancelled")}},{icon:s,color:o,label:l}=i[t];return a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[a.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function $et({selectedCount:t,printers:e,onSave:n,onClose:r,isSaving:i,canControlPrinter:s,t:o}){const[l,c]=w.useState("unchanged"),[d,u]=w.useState("unchanged"),[m,p]=w.useState("unchanged"),[f,y]=w.useState("unchanged"),[v,b]=w.useState("unchanged"),[g,_]=w.useState("unchanged"),[k,P]=w.useState("unchanged"),[N,M]=w.useState("unchanged"),[A,T]=w.useState("unchanged"),[C,F]=w.useState("unchanged"),$=()=>{const X={};l!=="unchanged"&&(X.printer_id=l),d!=="unchanged"&&(X.manual_start=d),m!=="unchanged"&&(X.auto_off_after=m),f!=="unchanged"&&(X.require_previous_success=f),v!=="unchanged"&&(X.bed_levelling=v),g!=="unchanged"&&(X.flow_cali=g),k!=="unchanged"&&(X.vibration_cali=k),N!=="unchanged"&&(X.layer_inspect=N),A!=="unchanged"&&(X.timelapse=A),C!=="unchanged"&&(X.use_ams=C),n(X)},I=l!=="unchanged"||d!=="unchanged"||m!=="unchanged"||f!=="unchanged"||v!=="unchanged"||g!=="unchanged"||k!=="unchanged"||N!=="unchanged"||A!=="unchanged"||C!=="unchanged";return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("queue.bulkEdit.title",{count:t})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:o("queue.bulkEdit.description")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printer")}),a.jsxs("select",{value:l===null?"null":l==="unchanged"?"unchanged":String(l),onChange:X=>{const L=X.target.value;c(L==="unchanged"?"unchanged":L==="null"?null:Number(L))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"unchanged",children:o("queue.bulkEdit.noChange")}),a.jsx("option",{value:"null",children:o("queue.filter.unassigned")}),e.map(X=>a.jsx("option",{value:X.id,children:X.name},X.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.queueOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(gu,{label:o("queue.bulkEdit.staged"),value:d,onChange:u,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.autoPowerOff"),value:m,onChange:p,disabled:!s,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.requirePrevious"),value:f,onChange:y,t:o})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(gu,{label:o("queue.bulkEdit.bedLevelling"),value:v,onChange:b,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.flowCalibration"),value:g,onChange:_,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.vibrationCalibration"),value:k,onChange:P,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.layerInspection"),value:N,onChange:M,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.timelapse"),value:A,onChange:T,t:o}),a.jsx(gu,{label:o("queue.bulkEdit.useAms"),value:C,onChange:F,t:o})]})]})]}),a.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ie,{variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ie,{onClick:$,disabled:!I||i,children:o(i?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function gu({label:t,value:e,onChange:n,disabled:r,t:i}){return a.jsxs("div",{className:`flex items-center justify-between py-1 ${r?"opacity-50":""}`,children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[a.jsx("button",{onClick:()=>n("unchanged"),disabled:r,className:`px-2 py-1 text-xs rounded ${e==="unchanged"?"bg-bambu-dark-tertiary text-white":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:"—"}),a.jsx("button",{onClick:()=>n(!1),disabled:r,className:`px-2 py-1 text-xs rounded ${e===!1?"bg-red-500/20 text-red-400":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:i("common.off")}),a.jsx("button",{onClick:()=>n(!0),disabled:r,className:`px-2 py-1 text-xs rounded ${e===!0?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:i("common.on")})]})]})}function KY({item:t,position:e,onEdit:n,onCancel:r,onRemove:i,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:d=!1,onToggleSelect:u,hasPermission:m,canModify:p,printerState:f,t:y}){const{data:v}=et({queryKey:["printerStatus",t.printer_id],queryFn:()=>pe.getPrinterStatus(t.printer_id),refetchInterval:3e4,enabled:t.printer_id!=null&&f==="printing"}),b=!!t.library_file_id&&!t.archive_id,{data:g}=et({queryKey:["archive-plates",t.archive_id],queryFn:()=>pe.getArchivePlates(t.archive_id),enabled:!!t.archive_id&&!b}),{data:_}=et({queryKey:["library-file-plates",t.library_file_id],queryFn:()=>pe.getLibraryFilePlates(t.library_file_id),enabled:b&&!!t.library_file_id}),k=b?_:g,P=k?.plates??[],N=m("queue:reorder"),{attributes:M,listeners:A,setNodeRef:T,transform:C,transition:F,isDragging:$}=ile({id:t.id,disabled:t.status!=="pending"||!N}),I={transform:Kx.Transform.toString(C),transition:F},X=t.status==="printing",L=t.status==="pending",te=["completed","failed","skipped","cancelled"].includes(t.status),ae=L&&u;return a.jsxs("div",{ref:T,style:I,className:`
  8322. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  8323. border-l-[3px] ${X?"border-l-blue-500":L?"border-l-yellow-500":t.status==="completed"?"border-l-emerald-500":t.status==="failed"?"border-l-red-500":"border-l-gray-500"}
  8324. ${$?"opacity-50 scale-[1.02] shadow-xl z-50":""}
  8325. ${X?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""}
  8326. ${d&&ae?"sm:border-bambu-dark-tertiary border-bambu-green/40":""}
  8327. ${!d&&!X?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""}
  8328. ${ae?"sm:cursor-default":""}
  8329. `,onClick:ae?()=>{window.innerWidth<640&&u()}:void 0,children:[ae&&d&&a.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),a.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[L&&u&&a.jsx("button",{onClick:ee=>{ee.stopPropagation(),u()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${d?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:d&&a.jsx(Kr,{className:"w-4 h-4"})}),L?a.jsx("div",{...M,...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:a.jsx(Eh,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0",children:["#",e]}):a.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),a.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?pe.getArchivePlateThumbnail(t.archive_id,t.plate_id):pe.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?pe.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):pe.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ea,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("p",{className:"text-sm sm:text-base text-white font-medium truncate",children:[t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,(k?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(ee=>ee.index===t.plate_id)?.name||y("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(vo,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewArchive"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(vo,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewInFileManager"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&a.jsx("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30",children:t.batch_name})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1 sm:gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model&&!t.printer_id?"text-blue-400":""}`,children:[a.jsx(Pr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${y("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?y("queue.filter.unassigned"):t.printer_name||`${y("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(Pc,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ls(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(CQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Het(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:y("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(Wu,{className:"w-3.5 h-3.5"}),t.created_by_username]}),L&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Qn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?y?.("queue.time.overdue")??"Overdue":Sx(t.scheduled_time,c,y):y?.("queue.time.asap")??"ASAP"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(gQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:y("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(im,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.autoPowerOff")]}),t.gcode_injection&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1",children:[a.jsx(ey,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.gcodeInjection")]})]}),X&&v&&a.jsxs("div",{className:"mt-2 sm:mt-3",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray",children:[v.remaining_time!=null&&v.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:y("printers.estimatedCompletion"),children:["ETA ",vO(v.remaining_time,c,y)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ea,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[a.jsx(qa,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),t.error_message]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:ee=>ee.stopPropagation(),children:[a.jsx(qet,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:y}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[X&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.stopPrint"):y("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Upe,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.startPrint"):y("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(Ds,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?y("common.edit"):y("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.cancel"):y("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),te&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?y("queue.actions.requeue"):y("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(vr,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.remove"):y("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})]})]})}function Vet(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=_r(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(null),[_,k]=w.useState(null),[P,N]=w.useState([]),[M,A]=w.useState(!1),[T,C]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[F,$]=w.useState(()=>{const Ae=localStorage.getItem("queue.historySortAsc");return Ae!==null?Ae==="true":!1}),[I,X]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,te]=w.useState(()=>{const Ae=localStorage.getItem("queue.pendingSortAsc");return Ae!==null?Ae==="true":!0}),[ae,ee]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[me,le]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",T)},[T]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(F))},[F]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",I)},[I]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ae))},[ae]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",me)},[me]);const ue=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),{data:K}=et({queryKey:["settings"],queryFn:pe.getSettings}),ne=K?.time_format||"system",{data:oe,isLoading:be}=et({queryKey:["queue",o,c],queryFn:()=>pe.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:_e}=et({queryKey:["printers"],queryFn:()=>pe.getPrinters()}),B=lt({mutationFn:Ae=>pe.updateSettings({queue_shortest_first:Ae}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Y=lt({mutationFn:Ae=>pe.cancelQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),D=lt({mutationFn:Ae=>pe.removeFromQueue(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=lt({mutationFn:Ae=>pe.stopQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),z=lt({mutationFn:Ae=>pe.startQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),W=lt({mutationFn:Ae=>pe.reorderQueue(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),q=lt({mutationFn:async()=>{const Ae=oe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];for(const ve of Ae)await pe.removeFromQueue(ve.id);return Ae.length},onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Ae}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),de=lt({mutationFn:Ae=>pe.bulkUpdateQueue(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),N([]),A(!1),n(Ae.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),O=lt({mutationFn:async Ae=>{for(const ve of Ae)await pe.cancelQueueItem(ve);return Ae.length},onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:Ae}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=Ae=>{N(ve=>ve.includes(Ae)?ve.filter(Te=>Te!==Ae):[...ve,Ae])},Q=w.useMemo(()=>{const Ae=new Set;return _e?.forEach(ve=>{ve.location&&Ae.add(ve.location)}),oe?.forEach(ve=>{ve.target_location&&Ae.add(ve.target_location)}),Array.from(Ae).sort()},[_e,oe]),V=w.useCallback(Ae=>u?Ae.target_location?Ae.target_location===u:Ae.printer_id?_e?.find(Te=>Te.id===Ae.printer_id)?.location===u:!1:!0,[u,_e]),J=w.useMemo(()=>{let Ae=oe?.filter(Te=>Te.status==="pending")||[];u&&(Ae=Ae.filter(V));const ve=Te=>{if(!Te.scheduled_time)return 0;const Fe=Qn(Te.scheduled_time)?.getTime()??0,Ee=Date.now()+4320*60*60*1e3;return Fe>Ee?0:Fe};return K?.queue_shortest_first?[...Ae].sort((Te,Fe)=>{const Ee=Te.printer_id??-(Te.target_model?.charCodeAt(0)??0),Se=Fe.printer_id??-(Fe.target_model?.charCodeAt(0)??0);if(Ee!==Se)return Ee-Se;const je=Te.been_jumped?1:0,qe=Fe.been_jumped?1:0;if(je!==qe)return qe-je;const Re=Te.print_time_seconds??1/0,Ye=Fe.print_time_seconds??1/0;return Re!==Ye?Re-Ye:Te.position-Fe.position}):[...Ae].sort((Te,Fe)=>{let Ee;if(I==="name"){const Se=Te.archive_name||Te.library_file_name||"",je=Fe.archive_name||Fe.library_file_name||"";Ee=Se.localeCompare(je)}else I==="printer"?Ee=(Te.printer_name||"").localeCompare(Fe.printer_name||""):I==="time"?Ee=ve(Te)-ve(Fe):Ee=Te.position-Fe.position;return L?Ee:-Ee})},[oe,I,L,V,u,K?.queue_shortest_first]),ie=()=>{const Ae=J.map(ve=>ve.id);P.length===Ae.length?N([]):N(Ae)},he=w.useMemo(()=>{let Ae=oe?.filter(ve=>ve.status==="printing")||[];return u&&(Ae=Ae.filter(V)),Ae},[oe,u,V]),fe=w.useMemo(()=>{const Ae=new Set;return he.forEach(ve=>{ve.printer_id&&Ae.add(ve.printer_id)}),Array.from(Ae)},[he]),se=ep({queries:fe.map(Ae=>({queryKey:["printerStatus",Ae],queryFn:()=>pe.getPrinterStatus(Ae),refetchInterval:5e3}))}),U=w.useMemo(()=>{const Ae={};return fe.forEach((ve,Te)=>{const Fe=se[Te];Fe?.data?.state&&(Ae[ve]=Fe.data.state)}),Ae},[fe,se]),R=w.useMemo(()=>{const Ae={};return fe.forEach((ve,Te)=>{const Fe=se[Te];Fe?.data&&(Ae[ve]={progress:Fe.data.progress??void 0,remaining_time:Fe.data.remaining_time??void 0,state:Fe.data.state??void 0})}),Ae},[fe,se]),re=w.useMemo(()=>{let Ae=oe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];return u&&(Ae=Ae.filter(V)),[...Ae].sort((ve,Te)=>{let Fe;if(T==="name"){const Ee=ve.archive_name||ve.library_file_name||"",Se=Te.archive_name||Te.library_file_name||"";Fe=Ee.localeCompare(Se)}else T==="printer"?Fe=(ve.printer_name||"").localeCompare(Te.printer_name||""):Fe=(Qn(Te.completed_at||Te.created_at)?.getTime()??0)-(Qn(ve.completed_at||ve.created_at)?.getTime()??0);return F?-Fe:Fe})},[oe,T,F,V,u]),xe=w.useMemo(()=>J.reduce((Ae,ve)=>Ae+(ve.print_time_seconds||0),0),[J]),we=w.useMemo(()=>J.reduce((Ae,ve)=>Ae+(ve.filament_used_grams||0),0),[J]),ye=Ae=>{const{active:ve,over:Te}=Ae;if(!Te||ve.id===Te.id)return;const Fe=J.findIndex(Se=>Se.id===ve.id),Ee=J.findIndex(Se=>Se.id===Te.id);if(Fe!==-1&&Ee!==-1){const je=nA(J,Fe,Ee).map((qe,Re)=>({id:qe.id,position:Re+1}));W.mutate(je)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(nN,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsx(Fet,{activeCount:he.length,pendingCount:J.length,totalTime:xe,totalWeight:we,historyCount:re.length,t}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:o===-1?"unassigned":o||"",onChange:Ae=>{const ve=Ae.target.value;l(ve==="unassigned"?-1:ve===""?null:Number(ve))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),_e?.map(Ae=>a.jsx("option",{value:Ae.id,children:Ae.name},Ae.id))]}),a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:c,onChange:Ae=>d(Ae.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Q.length>0&&a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:u,onChange:Ae=>m(Ae.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Q.map(Ae=>a.jsx("option",{value:Ae,children:Ae},Ae))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),re.length>0&&a.jsxs(Ie,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(un,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsxs("div",{className:"hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{className:`p-2 transition-colors ${me==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("list"),title:t("queue.timeline.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${me==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx(Npe,{className:"w-4 h-4"})})]}),a.jsxs("button",{onClick:()=>{const Ae=!(K?.queue_shortest_first??!1);B.mutate(Ae)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${K?.queue_shortest_first?"bg-bambu-green/20 border-bambu-green text-bambu-green":"bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,title:t("queue.sjf.tooltip","Shortest Job First — scheduler prioritizes shorter prints"),children:[a.jsx(Pc,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]})]}),be?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):oe?.length===0?a.jsxs(Dt,{className:"p-12 text-center border-dashed",children:[a.jsx(Wr,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):me==="timeline"?a.jsx(Bet,{queueItems:oe||[],printerStatuses:R,onItemClick:Ae=>{["completed","failed","skipped","cancelled"].includes(Ae.status)?g(Ae):Ae.status==="pending"?v(Ae):Ae.status==="printing"&&k({type:"stop",item:Ae})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[he.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-2 sm:space-y-3",children:he.map(Ae=>a.jsx(KY,{item:Ae,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>k({type:"stop",item:Ae}),onRequeue:()=>{},onStart:()=>{},timeFormat:ne,hasPermission:r,canModify:s,printerState:Ae.printer_id?U[Ae.printer_id]:null,t},Ae.id))})]}),J.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:J.length}),")"]}),a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:I,onChange:Ae=>X(Ae.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>te(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:ie,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===J.length&&J.length>0?a.jsx(us,{className:"w-4 h-4 text-bambu-green"}):a.jsx(eo,{className:"w-4 h-4"}),P.length===J.length&&J.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:P.length})}),a.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Ie,{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:[a.jsx(Za,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>O.mutate(P),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:O.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[a.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),a.jsx(ele,{sensors:ue,collisionDetection:Boe,onDragEnd:ye,children:a.jsx(rle,{items:J.map(Ae=>Ae.id),strategy:wet,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:J.map((Ae,ve)=>a.jsx(KY,{item:Ae,position:ve+1,onEdit:()=>v(Ae),onCancel:()=>k({type:"cancel",item:Ae}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>z.mutate(Ae.id),timeFormat:ne,isSelected:P.includes(Ae.id),onToggleSelect:()=>G(Ae.id),hasPermission:r,canModify:s,t},Ae.id))})})})]}),re.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("button",{onClick:()=>ee(!ae),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ae?a.jsx(Va,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(Fn,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:re.length}),")"]})]}),!ae&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:T,onChange:Ae=>C(Ae.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>$(!F),title:t(F?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:F?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),!ae&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:re.slice(0,50).map(Ae=>a.jsx(Ret,{item:Ae,onRemove:()=>k({type:"remove",item:Ae}),onRequeue:()=>g(Ae),timeFormat:ne,hasPermission:r,canModify:s,t},Ae.id))})]})]}),y&&a.jsx(kd,{mode:"edit-queue-item",archiveId:y.archive_id??void 0,libraryFileId:y.library_file_id??void 0,archiveName:y.archive_name||y.library_file_name||`File #${y.archive_id||y.library_file_id}`,queueItem:y,onClose:()=>v(null)}),b&&a.jsx(kd,{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:()=>g(null)}),_&&a.jsx(kn,{title:_.type==="cancel"?t("queue.confirm.cancelTitle"):_.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:_.type==="cancel"?t("queue.confirm.cancelMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):_.type==="stop"?t("queue.confirm.stopMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:_.type==="cancel"?t("queue.confirm.cancelButton"):_.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{_.type==="cancel"?Y.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):D.mutate(_.item.id),k(null)},onCancel:()=>k(null)}),p&&a.jsx(kn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:re.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{q.mutate(),f(!1)},onCancel:()=>f(!1)}),M&&a.jsx($et,{selectedCount:P.length,printers:_e?.map(Ae=>({id:Ae.id,name:Ae.name}))||[],onSave:Ae=>{Object.keys(Ae).length>0&&de.mutate({item_ids:P,...Ae})},onClose:()=>A(!1),isSaving:de.isPending,canControlPrinter:r("printers:control"),t})]})}function Get({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const k=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return k.observe(_),()=>k.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach($=>{const I=$.split("T")[0];_[I]=(_[I]||0)+1});const k=new Date,P=new Date(k);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],M=[];let A=[],T=-1;const C=new Date(P);let F=0;for(;C<=k;)C.getDay()===0&&A.length>0&&(N.push(A),A=[],F++),C.getMonth()!==T&&(M.push({month:C.toLocaleDateString("en-US",{month:"short"}),weekIndex:F}),T=C.getMonth()),A.push(new Date(C)),C.setDate(C.getDate()+1);return A.length>0&&N.push(A),{weeks:N,monthLabels:M,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const k=_/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,y=r-p-16,v=m>0?Math.floor((y-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,v)),g=b<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:_,weekIndex:k},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:g,marginLeft:P===0?0:`${(k-(o[P-1]?.weekIndex||0))*(b+f)-24}px`},children:_},P))}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((_,k)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:g,visibility:k%2===1?"visible":"hidden"},children:_},_))}),s.map((_,k)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(C=>C.getDay()===P);if(!N)return a.jsx("div",{style:{width:b,height:b}},P);const M=N.toISOString().split("T")[0],A=l[M]||0,T=M===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(A)} ${T?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${N.toLocaleDateString()}: ${A} print${A!==1?"s":""}`},P)})},k))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:g},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),a.jsx("span",{children:"More"})]})]})})}const YY=["weight","prints","time"];function bP({value:t,onChange:e,exclude:n}){const{t:r}=Lt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?YY.filter(o=>!n.includes(o)):YY;return a.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>a.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function 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 mk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Wet=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],XY=["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 Ket({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Lt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{const F=Qn(C.completed_at||C.created_at)||new Date,$=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`,I=T.get($)||{date:$,filament:0,cost:0,prints:0};I.filament+=C.filament_used_grams||0,I.cost+=C.cost||0,I.prints+=C.quantity||1,T.set($,I)}),Array.from(T.values()).sort((C,F)=>C.date.localeCompare(F.date)).map(C=>({...C,dateLabel:new Date(C.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=w.useMemo(()=>{if(n&&r)return Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1;if(n)return Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1;if(t.length<2)return 0;const T=t.map(C=>new Date(C.completed_at||C.created_at).getTime());return(Math.max(...T)-Math.min(...T))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const T=new Map,C=u>1;return t.forEach(F=>{const $=Qn(F.completed_at||F.created_at)||new Date,I=$.getHours(),X=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,L=T.get(X)||{date:X,filament:0,cost:0,prints:0};L.filament+=F.filament_used_grams||0,L.cost+=F.cost||0,L.prints+=F.quantity||1,T.set(X,L)}),Array.from(T.values()).sort((F,$)=>F.date.localeCompare($.date)).map(F=>{const[$,I]=F.date.split("T"),X=new Date($),L=parseInt(I,10),te=C?`${Wet[X.getDay()]} ${XY[L]}`:XY[L];return{...F,dateLabel:te}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const T=new Map;return d.forEach(C=>{const F=new Date(C.date),$=new Date(F);$.setDate(F.getDate()-F.getDay());const I=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}`,X=T.get(I)||{week:I,filament:0,cost:0,prints:0};X.filament+=C.filament,X.cost+=C.cost,X.prints+=C.prints,T.set(I,X)}),Array.from(T.values()).sort((C,F)=>C.week.localeCompare(F.week)).map(C=>({date:C.week,dateLabel:`Week of ${new Date(C.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...C}))},[d]),f=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", ");$.forEach(I=>{const X=(C.filament_used_grams||0)/$.length;T.set(I,(T.get(I)||0)+X)})}),Array.from(T.entries()).map(([C,F])=>({name:C,value:Math.round(F)})).sort((C,F)=>F.value-C.value)},[t]),y=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{(C.filament_type||"Unknown").split(", ").forEach(I=>{T.set(I,(T.get(I)||0)+1)})}),Array.from(T.entries()).map(([C,F])=>({name:C,value:F})).sort((C,F)=>F.value-C.value)},[t]),v=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", "),I=(C.actual_time_seconds||C.print_time_seconds||0)/$.length;$.forEach(X=>{T.set(X,(T.get(X)||0)+I)})}),Array.from(T.entries()).map(([C,F])=>({name:C,value:Math.round(F/3600*10)/10})).sort((C,F)=>F.value-C.value)},[t]),b=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{if(C.status!=="completed"&&C.status!=="failed")return;(C.filament_type||"Unknown").split(", ").forEach($=>{const I=T.get($)||{completed:0,failed:0};C.status==="completed"?I.completed++:I.failed++,T.set($,I)})}),Array.from(T.entries()).filter(([,C])=>C.completed+C.failed>=2).map(([C,F])=>{const $=F.completed+F.failed,I=Math.round(F.completed/$*100);return{name:C,rate:I,total:$}}).sort((C,F)=>F.rate-C.rate)},[t]),g=w.useMemo(()=>{const T=new Map;return t.forEach(C=>{if(!C.filament_color)return;const F=C.filament_color.split(",").map(I=>I.trim()),$=(C.filament_used_grams||0)/F.length;F.forEach(I=>{const X=T.get(I)||{count:0,weight:0};X.count++,X.weight+=$,T.set(I,X)})}),Array.from(T.entries()).map(([C,F])=>({hex:C,value:l==="prints"?F.count:Math.round(F.weight)})).sort((C,F)=>F.value-C.value)},[t,l]),_=s==="weight"?f:s==="prints"?y:v,k=u<=7&&m.length>0?m:p,P=t.reduce((T,C)=>T+(C.filament_used_grams||0),0),N=t.reduce((T,C)=>T+(C.cost||0),0),M=t.reduce((T,C)=>T+(C.quantity||1),0),A=new Set(t.map(T=>T.printer_id).filter(Boolean)).size;return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),a.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:bh(P)})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[A," ",i("nav.printers").toLowerCase()]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,N.toFixed(2)]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[M," ",i("common.prints")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[M>0?(P/M).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,M>0?(N/M).toFixed(2):"0.00"," avg"]})]})]}),k.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),a.jsx(_h,{width:"100%",height:250,children:a.jsxs(bVe,{data:k,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:T=>`${T}g`}),a.jsx(kh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:T=>[`${Number(T??0).toFixed(0)}g`,"Filament"]}),a.jsx(Jre,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),a.jsx(bP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(_h,{width:160,height:160,children:a.jsxs(PW,{children:[a.jsx(qR,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((T,C)=>a.jsx(zx,{fill:mk[C%mk.length]},`cell-${C}`))}),a.jsx(kh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:T=>[s==="weight"?bh(Number(T??0)):s==="time"?`${Number(T??0)}h`:`${T??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((T,C)=>{const F=_.reduce((I,X)=>I+X.value,0),$=F>0?(T.value/F*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:mk[C%mk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:T.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?bh(T.value):s==="time"?`${T.value}h`:T.value," · ",$,"%"]})]},T.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?a.jsx("div",{className:"space-y-1.5",children:b.map(T=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:T.name}),a.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:a.jsx("div",{className:`h-full rounded-full transition-all ${T.rate>=90?"bg-status-ok":T.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${T.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${T.rate>=90?"text-status-ok":T.rate>=70?"text-status-warning":"text-status-error"}`,children:[T.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",T.total,")"]})]},T.name))}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),a.jsx(bP,{value:l,onChange:c,exclude:["time"]})]}),g.length>0?(()=>{const T=g.reduce((C,F)=>C+F.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(_h,{width:"100%",height:"100%",children:a.jsxs(PW,{children:[a.jsx(qR,{data:g,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:g.map((C,F)=>a.jsx(zx,{fill:C.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${F}`))}),a.jsx(kh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:C=>[l==="weight"?bh(Number(C??0)):`${C??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?bh(T):T}),a.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[g.length," ",g.length===1?"color":"colors"]})]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:g.slice(0,8).map(C=>{const F=T>0?(C.value/T*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[a.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:C.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[F,"%"]})]},C.hex)})}),g.length>8&&a.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",g.length-8," more"]})]})})():a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function Yet({id:t,title:e,component:n,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=ile({id:t}),y={transform:Kx.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...y,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(Eh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(hO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(NP,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(Tw,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function Xet({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const T={};return t.forEach(C=>{T[C.id]=C.defaultSize||4}),T},[c,d]=w.useState(()=>{const T=localStorage.getItem(e);if(T)try{const C=JSON.parse(T);if(!C.sizes)C.sizes=l();else{const F=l();for(const $ in F)$ in C.sizes||(C.sizes[$]=F[$])}return C}catch{}return{order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const T=window.matchMedia(`(max-width: ${r}px)`),C=$=>{f($.matches)};C(T);const F=$=>C($);return T.addEventListener?T.addEventListener("change",F):T.addListener(F),()=>{T.removeEventListener?T.removeEventListener("change",F):T.removeListener(F)}},[r]);const y=r&&p?1:n;w.useEffect(()=>{const T=()=>m(C=>!C);return window.addEventListener("toggle-hidden-panel",T),()=>window.removeEventListener("toggle-hidden-panel",T)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const C=t.map(F=>F.id).filter(F=>!c.order.includes(F));C.length>0&&d(F=>({...F,order:[...F.order,...C]}))},[t,c.order]);const v=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),b=T=>{const{active:C,over:F}=T;F&&C.id!==F.id&&d($=>{const I=$.order.indexOf(C.id),X=$.order.indexOf(F.id);return{...$,order:nA($.order,I,X)}})},g=T=>{d(C=>({...C,hidden:C.hidden.includes(T)?C.hidden.filter(F=>F!==T):[...C.hidden,T]}))},_=T=>{d(C=>{const F=C.sizes[T]||4,$=F===1?2:F===2?4:1;return{...C,sizes:{...C.sizes,[T]:$}}})},k=()=>{const T={order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()};d(T),s?.()},P=c.order.map(T=>t.find(C=>C.id===T)).filter(Boolean),N=P.filter(T=>!c.hidden.includes(T.id)),M=P.filter(T=>c.hidden.includes(T.id)),A=o?.({hiddenCount:M.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:k});return a.jsxs("div",{className:"space-y-4",children:[A,!i&&!o&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:k,children:[a.jsx(jo,{className:"w-4 h-4"}),"Reset Layout"]}),M.length>0&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(Dc,{className:"w-4 h-4"}),M.length," Hidden"]})]}),u&&M.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(T=>a.jsxs("button",{onClick:()=>g(T.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(Dc,{className:"w-3 h-3"}),T.title]},T.id))})]}),a.jsx(ele,{sensors:v,collisionDetection:Boe,onDragEnd:b,children:a.jsx(rle,{items:N.map(T=>T.id),strategy:Wz,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:N.map(T=>{const C=c.sizes[T.id]||2,F=Math.min(C,y);return a.jsx(Yet,{id:T.id,title:T.title,component:T.component,isHidden:c.hidden.includes(T.id),size:C,columnSpan:F,onToggleVisibility:()=>g(T.id),onToggleSize:()=>_(T.id)},T.id)})})})}),N.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Ie,{className:"mt-4",onClick:k,children:"Reset Layout"})]})]})}function Qet(t){const e=new Date,n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(n,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(n,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(n,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(n,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(n,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(n,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const Zet=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],Jet=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],UL=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],i3=[{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}],hk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function ett({stats:t,currency:e}){const{t:n}=Lt(),r=[{icon:Na,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:rr,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Na,color:"text-orange-400",label:n("stats.filamentUsed"),value:bh(t?.total_filament_grams||0)},{icon:Zk,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:Xl,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`},{icon:Zk,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:r.map(i=>a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${i.color}`,children:a.jsx(i.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsx("p",{className:"text-xl font-bold text-white",children:i.value})]})]},i.label))})}function ttt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round(t.successful_prints/i*100):0,o=n===1?112:n===2?128:144,l=o/2-8,c=l*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($a,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([d,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function ntt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),d=i-100,u=n===1?112:n===2?128:144,m=u/2-8,p=m*2*Math.PI,f=n===1?3:n===2?6:999,y=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(_Q,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),y.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:y.map(([v,b])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},v))})]})]})}function rtt({printDates:t,dateFrom:e,dateTo:n}){const{days:r,hourlyCounts:i,maxCount:s}=w.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(n+"T00:00:00"),p=[],f=g=>`${g.getFullYear()}-${String(g.getMonth()+1).padStart(2,"0")}-${String(g.getDate()).padStart(2,"0")}`,y=new Date(u);for(;y<=m;)p.push({key:f(y),label:y.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),y.setDate(y.getDate()+1);const v={};let b=0;return t.forEach(g=>{const _=Qn(g);if(!_)return;const P=`${`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}-${_.getHours()}`;v[P]=(v[P]||0)+1,v[P]>b&&(b=v[P])}),{days:p,hourlyCounts:v,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 a.jsxs("div",{className:"w-full overflow-x-auto",children:[a.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[a.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:UL.map((u,m)=>a.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>a.jsxs("div",{className:"flex items-center",style:{gap:c},children:[a.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return a.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${UL[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:c},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),a.jsx("span",{children:"More"})]})]})}function att({printDates:t,size:e=2,dateFrom:n,dateTo:r}){const i=w.useMemo(()=>n&&r?Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1:n?Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1:1/0,[n,r]);if(i<=7&&n&&r)return a.jsx(rtt,{printDates:t,dateFrom:n,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return a.jsx(Get,{printDates:t,months:o})}function itt({stats:t,archives:e,printerMap:n}){const{t:r}=Lt(),[i,s]=w.useState("weight"),[o,l]=w.useState("weight"),c=w.useMemo(()=>{const g=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([_,k])=>{const P=g.get(_)||{prints:0,weight:0,time:0};P.prints=k,g.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const k=String(_.printer_id),P=g.get(k)||{prints:0,weight:0,time:0};P.weight+=_.filament_used_grams||0,P.time+=_.actual_time_seconds||_.print_time_seconds||0,t?.prints_by_printer||P.prints++,g.set(k,P)}),Array.from(g.entries()).map(([_,k])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?k.prints:i==="weight"?Math.round(k.weight):Math.round(k.time/3600*10)/10})).sort((_,k)=>k.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const g=Array.from({length:24},(_,k)=>({hour:k,label:UL[k],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const k=Qn(_.started_at);if(!k)return;const P=k.getHours();g[P].total++,_.status==="failed"&&g[P].failures++}),g},[e]),u=w.useMemo(()=>{const g=i3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const k=_.actual_time_seconds||_.print_time_seconds;if(!(!k||k<=0)){for(let P=0;P<i3.length;P++)if(k<=i3[P].max){g[P].count++;break}}}),g},[e]),m=w.useMemo(()=>{const g=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=Qn(P.created_at)||new Date(P.created_at);let M=N.getDay()-1;M<0&&(M=6),o==="prints"?g[M]++:o==="weight"?g[M]+=P.filament_used_grams||0:g[M]+=(P.actual_time_seconds||P.print_time_seconds||0)/3600;const A=new Date(N);A.setDate(N.getDate()-(N.getDay()+6)%7),_.add(`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`)});const k=Math.max(_.size,1);return Jet.map((P,N)=>({name:P,avg:Math.round(g[N]/k*10)/10}))},[e,o]),p=g=>({unit:g==="weight"?"g":g==="time"?"h":"",color:g==="weight"?"#00ae42":g==="time"?"#3b82f6":"#f59e0b"}),f=p(i),y=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),v=p(o),b=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),a.jsx(bP,{value:i,onChange:s})]}),c.length>0?a.jsx(_h,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(W1,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(hf,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(kh,{contentStyle:hk,formatter:g=>[i==="weight"?bh(Number(g??0)):`${g??0}${f.unit}`,y]}),a.jsx(Hb,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?a.jsx(_h,{width:"100%",height:160,children:a.jsxs(W1,{data:u,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(kh,{contentStyle:hk}),a.jsx(Hb,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),a.jsx(bP,{value:o,onChange:l})]}),e.length>0?a.jsx(_h,{width:"100%",height:160,children:a.jsxs(W1,{data:m,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(kh,{contentStyle:hk,formatter:g=>[`${g??0}${v.unit}`,b]}),a.jsx(Hb,{dataKey:"avg",fill:v.color,radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?a.jsx(_h,{width:"100%",height:160,children:a.jsxs(W1,{data:d,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(kh,{contentStyle:hk}),a.jsx(Hb,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(Hb,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function stt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Lt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ket,{archives:t,currency:e,dateFrom:n,dateTo:r})}function ott({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Lt(),s=!!(e||n),{data:o,isLoading:l}=et({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>pe.getFailureAnalysis({...s?{dateFrom:e,dateTo:n}:{days:30},createdById:r})});if(l)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ln,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(fO,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate<o.trend[o.trend.length-2].failure_rate?"text-status-ok":"text-status-error"}`}),a.jsx("span",{className:"text-bambu-gray",children:i("stats.lastWeekRate",{rate:o.trend[o.trend.length-1].failure_rate.toFixed(1)})})]})})]}),u.length>0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function ltt({archives:t,currency:e}){const{t:n}=Lt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=y=>{let v=null,b=0;return t.forEach(g=>{const _=y(g);_&&_>b&&(b=_,v=g)}),{archive:v,value:b}},o=s(y=>y.actual_time_seconds);o.archive&&i.push({icon:rr,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ls(o.value),detail:o.archive.print_name||null});const l=s(y=>y.filament_used_grams);l.archive&&i.push({icon:Na,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:bh(l.value),detail:l.archive.print_name||null});const c=s(y=>y.cost);c.archive&&i.push({icon:Zk,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(y=>{const v=Qn(y.created_at)||new Date(y.created_at),b=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((y,v)=>{y>m&&(m=y,u=v)}),m>1&&i.push({icon:Wr,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[y,v,b]=u.split("-").map(Number);return new Date(y,v-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(y=>y.status==="completed"||y.status==="failed").sort((y,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(y.completed_at||y.created_at).getTime());let f=0;for(const y of p)if(y.status==="completed")f++;else break;return f>0&&i.push({icon:Xl,iconColor:"text-yellow-400",label:n("stats.successStreak"),value:`${f}`,detail:f===1?n("stats.streakPrint"):n("stats.streakPrints",{count:f})}),i},[t,e,n]);return r.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noArchiveData")}):a.jsx("div",{className:"space-y-3",children:r.map((i,s)=>a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:a.jsx(i.icon,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function ctt(){const{t}=Lt(),{showToast:e}=xn(),{hasPermission:n,authEnabled:r}=_r(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(0),[u,m]=w.useState(0),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(!1),_=r&&n("stats:filter_by_user"),[k,P]=w.useState(()=>{try{const Y=localStorage.getItem("bambusy-stats-timeframe");if(Y){const D=JSON.parse(Y);if(D.preset)return D}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,M]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(k))},[k]);const A=w.useMemo(()=>k.preset==="custom"?{dateFrom:k.dateFrom,dateTo:k.dateTo}:Qet(k.preset),[k]);w.useEffect(()=>{const Y=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const z=JSON.parse(j);m(z.hidden?.length||0)}}catch{m(0)}};Y(),window.addEventListener("storage",Y);const D=setInterval(Y,2e3);return()=>{window.removeEventListener("storage",Y),clearInterval(D)}},[c]);const T=y!==null?y:void 0,{data:C,isLoading:F,isFetching:$,refetch:I}=et({queryKey:["archiveStats",A.dateFrom,A.dateTo,T??"all"],queryFn:()=>pe.getArchiveStats({dateFrom:A.dateFrom,dateTo:A.dateTo,createdById:T})}),{data:X}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:L,isFetching:te,refetch:ae}=et({queryKey:["archivesSlim",A.dateFrom,A.dateTo,T??"all"],queryFn:()=>pe.getArchivesSlim(A.dateFrom,A.dateTo,T)}),{data:ee}=et({queryKey:["settings"],queryFn:pe.getSettings}),{data:me}=et({queryKey:["users"],queryFn:pe.getUsers,enabled:_}),le=w.useMemo(()=>y===null?t("stats.allUsers","All Users"):y===-1?t("stats.noUser","No User (System)"):me?.find(Y=>Y.id===y)?.username??"?",[y,me,t]),ue=async Y=>{l(!1),s(!0);try{const{blob:D,filename:j}=await pe.exportStats({format:Y,days:90,createdById:T}),z=URL.createObjectURL(D),W=document.createElement("a");W.href=z,W.download=j,W.click(),URL.revokeObjectURL(z),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},K=async()=>{f(!0);try{const Y=await pe.recalculateCosts();await Promise.all([I(),ae()]),e(t("stats.recalculatedCosts",{count:Y.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},ne=($||te)&&!F,oe=yo(ee?.currency||"USD"),be=new Map(X?.map(Y=>[String(Y.id),Y.name])||[]),_e=w.useMemo(()=>L?.map(Y=>Y.created_at)||[],[L]);if(F)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const B=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(ett,{stats:C,currency:oe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Y=>a.jsx(ttt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Y=>a.jsx(ntt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Y=>a.jsx(ott,{size:Y,dateFrom:A.dateFrom,dateTo:A.dateTo,createdById:T}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Y=>a.jsx(att,{printDates:_e,size:Y,dateFrom:A.dateFrom,dateTo:A.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(ltt,{archives:L||[],currency:oe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(itt,{stats:C,archives:L||[],printerMap:be}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(stt,{archives:L||[],currency:oe,dateFrom:A.dateFrom,dateTo:A.dateTo}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),ne&&a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Ie,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(Dc,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Y=>Y+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(jo,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Ie,{variant:"secondary",onClick:K,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(bpe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>ue("csv"),children:[a.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>ue("xlsx"),children:[a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&me&&me.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!b),children:[a.jsx(_u,{className:"w-4 h-4"}),le,a.jsx(Fn,{className:"w-3 h-3"})]}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2 max-h-64 overflow-y-auto",children:[a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(null),g(!1)},children:t("stats.allUsers","All Users")}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(-1),g(!1)},children:t("stats.noUser","No User (System)")}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),me.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===Y.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Y.id),g(!1)},children:Y.username},Y.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>M(!N),children:[a.jsx(Wr,{className:"w-4 h-4"}),t(`stats.timeframe.${k.preset}`),a.jsx(Fn,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>M(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[Zet.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset===Y?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Y,dateFrom:void 0,dateTo:void 0}),M(!1)},children:t(`stats.timeframe.${Y}`)},Y)),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Y=>({...Y,preset:"custom"})),children:t("stats.timeframe.custom")}),k.preset==="custom"&&a.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),a.jsx("input",{type:"date",value:k.dateFrom||"",max:k.dateTo||new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateFrom:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),a.jsx("input",{type:"date",value:k.dateTo||"",min:k.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateTo:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsx(Ie,{variant:"primary",onClick:()=>M(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Xet,{widgets:B,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function lle({summary:t,children:e,defaultOpen:n=!1,className:r="",summaryClassName:i=""}){const[s,o]=w.useState(n);return a.jsxs("div",{className:r,children:[a.jsxs("button",{type:"button",onClick:()=>o(l=>!l),className:`w-full flex items-center justify-between gap-2 text-left ${i}`,"aria-expanded":s,children:[a.jsx("div",{className:"flex-1 min-w-0",children:t}),a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsx("div",{className:"mt-3",children:e})]})}function dtt({plug:t,onEdit:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:y}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>pe.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=et({queryKey:["printers"],queryFn:pe.getPrinters}),b=v?.find(F=>F.id===t.printer_id),g=lt({mutationFn:F=>pe.controlSmartPlug(t.id,F),onMutate:async F=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const $=r.getQueryData(["smart-plug-status",t.id]),I=F==="on"?"ON":F==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],X=>({...X,state:I})),{previousStatus:$}},onError:(F,$,I)=>{I?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(n("smartPlugs.failedToTurn",{action:$,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=lt({mutationFn:F=>pe.updateSmartPlug(t.id,F),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),k=lt({mutationFn:()=>pe.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),P=f?.state==="ON",N=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,M=(f?.reachable??!1)||N,A=g.isPending,C=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const F=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${F}/`:`http://${F}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?M?"bg-teal-500/20":"bg-red-500/20":M?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(pO,{className:`w-5 h-5 ${M?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Mw,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(yd,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(ql,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[y?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),M&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):t.plug_type==="rest"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):M?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(vf,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:P?"text-status-ok":"text-bambu-gray",children:f?.state||n("smartPlugs.unknown")})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Ku,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),C&&a.jsxs("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(sa,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("smartPlugs.linkedTo")," "]}),a.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(Dc,{className:"w-3 h-3"}),n("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(Ah,{className:"w-3 h-3"}),n("smartPlugs.alerts")]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(Wr,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?n("smartPlugs.scheduleOn",{time:t.schedule_on_time}):n("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Ie,{size:"sm",variant:P?"primary":"secondary",disabled:!M||A,onClick:()=>c(!0),className:"flex-1",children:[A?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(im,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(Ie,{size:"sm",variant:P?"secondary":"primary",disabled:!M||A,onClick:()=>u(!0),className:"flex-1",children:[A?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Rw,{className:"w-4 h-4"}),n("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.kwhToday")})]})]}),a.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?n("smartPlugs.settings"):n("smartPlugs.automationSettings")]}),a.jsx("span",{children:m?"-":"+"})]}),m&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:F=>_.mutate({show_in_switchbar:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.enableAutomation")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:F=>_.mutate({enabled:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOn")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOnDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:F=>_.mutate({auto_on:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOff")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:F=>_.mutate({auto_off:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffPersistent")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffPersistentDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:F=>_.mutate({auto_off_persistent:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:n("smartPlugs.turnOffDelayMode")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(rr,{className:"w-4 h-4"}),n("smartPlugs.time")]}),a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(PP,{className:"w-4 h-4"}),n("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayMinutes")}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:F=>_.mutate({off_delay_minutes:parseInt(F.target.value)||5}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.tempThreshold")}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:F=>_.mutate({off_temp_threshold:parseInt(F.target.value)||70}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.tempThresholdDescription")})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(xh,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(kn,{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&&a.jsx(kn,{title:n("smartPlugs.turnOnSmartPlug"),message:n("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{g.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&a.jsx(kn,{title:n("smartPlugs.turnOffSmartPlug"),message:n("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{g.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function utt({plug:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[d,u]=w.useState(t?.ip_address||""),[m,p]=w.useState(t?.username||""),[f,y]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[g,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[k,P]=w.useState(t?.mqtt_power_path||""),[N,M]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[A,T]=w.useState(t?.mqtt_energy_topic||""),[C,F]=w.useState(t?.mqtt_energy_path||""),[$,I]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[X,L]=w.useState(t?.mqtt_state_topic||""),[te,ae]=w.useState(t?.mqtt_state_path||""),[ee,me]=w.useState(t?.mqtt_state_on_value||""),[le,ue]=w.useState(t?.rest_on_url||""),[K,ne]=w.useState(t?.rest_on_body||""),[oe,be]=w.useState(t?.rest_off_url||""),[_e,B]=w.useState(t?.rest_off_body||""),[Y,D]=w.useState(t?.rest_method||"POST"),[j,z]=w.useState(t?.rest_headers||""),[W,q]=w.useState(t?.rest_status_url||""),[de,O]=w.useState(t?.rest_status_path||""),[G,Q]=w.useState(t?.rest_status_on_value||""),[V,J]=w.useState(t?.rest_power_url||""),[ie,he]=w.useState(t?.rest_power_path||""),[fe,se]=w.useState((t?.rest_power_multiplier??1).toString()),[U,R]=w.useState(t?.rest_energy_url||""),[re,xe]=w.useState(t?.rest_energy_path||""),[we,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[Ae,ve]=w.useState(t?.ha_power_entity||""),[Te,Fe]=w.useState(t?.ha_energy_today_entity||""),[Ee,Se]=w.useState(t?.ha_energy_total_entity||""),[je,qe]=w.useState(""),[Re,Ye]=w.useState(""),[ce,ze]=w.useState(!1),Ne=w.useRef(null),[Ge,$e]=w.useState(""),[Pe,Me]=w.useState(!1),Ve=w.useRef(null),[tt,ut]=w.useState(""),[xt,wt]=w.useState(!1),Ht=w.useRef(null),[Xt,Kt]=w.useState(""),[Ut,en]=w.useState(!1),Ke=w.useRef(null),[Ft,Nt]=w.useState(t?.printer_id||null),[ht,Mt]=w.useState(null),[Qt,Wt]=w.useState(null),[Ue,dt]=w.useState(t?.power_alert_enabled||!1),[pt,De]=w.useState(t?.power_alert_high?.toString()||""),[Le,at]=w.useState(t?.power_alert_low?.toString()||""),[Ce,We]=w.useState(t?.schedule_enabled||!1),[Xe,Qe]=w.useState(t?.schedule_on_time||""),[Ze,rt]=w.useState(t?.schedule_off_time||""),[bt,Pt]=w.useState(t?.show_in_switchbar||!1),[vt,He]=w.useState(t?.show_on_printer_card??!0),[St,Ct]=w.useState(!1),[Zt,Jt]=w.useState({scanned:0,total:0}),[Nn,vn]=w.useState([]),yn=w.useRef(null),{data:an}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:rn}=et({queryKey:["smart-plugs"],queryFn:pe.getSmartPlugs}),{data:bn}=et({queryKey:["settings"],queryFn:pe.getSettings}),Gn=!!(bn?.ha_enabled&&bn?.ha_url&&bn?.ha_token);w.useEffect(()=>{const jt=setTimeout(()=>{Ye(je)},300);return()=>clearTimeout(jt)},[je]),w.useEffect(()=>{const jt=Wn=>{Ne.current&&!Ne.current.contains(Wn.target)&&ze(!1),Ve.current&&!Ve.current.contains(Wn.target)&&Me(!1),Ht.current&&!Ht.current.contains(Wn.target)&&wt(!1),Ke.current&&!Ke.current.contains(Wn.target)&&en(!1)};return document.addEventListener("mousedown",jt),()=>document.removeEventListener("mousedown",jt)},[]);const{data:ar,isLoading:On,error:mi}=et({queryKey:["ha-entities",Re],queryFn:()=>pe.getHAEntities(Re||void 0),enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0}),{data:Rn}=et({queryKey:["ha-sensor-entities"],queryFn:pe.getHASensorEntities,enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0});w.useEffect(()=>{const jt=Wn=>{Wn.key==="Escape"&&e()};return window.addEventListener("keydown",jt),()=>{window.removeEventListener("keydown",jt),yn.current&&clearInterval(yn.current)}},[e]);const na=async()=>{Ct(!0),vn([]),Jt({scanned:0,total:0}),Wt(null);try{await pe.startTasmotaScan();const jt=async()=>{try{const Wn=await pe.getTasmotaScanStatus();Jt({scanned:Wn.scanned,total:Wn.total});const En=await pe.getDiscoveredTasmotaDevices();vn(En),Wn.running||(Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null))}catch(Wn){console.error("Polling error:",Wn)}};await jt(),yn.current=setInterval(jt,500)}catch(jt){Ct(!1);const Wn=jt instanceof Error?jt.message:typeof jt=="string"?jt:JSON.stringify(jt);Wt(Wn||n("smartPlugs.failedToStartScan"))}},ra=async()=>{try{await pe.stopTasmotaScan()}catch{}Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null)},jr=jt=>{u(jt.ip_address),c(jt.name),Mt(null)},In=lt({mutationFn:()=>pe.testSmartPlugConnection(d,m||null,f||null),onSuccess:jt=>{Mt(jt),Wt(null),!l&&jt.device_name&&c(jt.device_name)},onError:jt=>{Mt(null),Wt(jt.message)}}),Bi=lt({mutationFn:jt=>pe.createSmartPlug(jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Hi=lt({mutationFn:jt=>pe.updateSmartPlug(t.id,jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Ci=an?.filter(jt=>s==="tasmota"?!rn?.some(En=>En.printer_id===jt.id&&En.id!==t?.id&&En.plug_type==="tasmota"):!0),Hc=jt=>{if(jt.preventDefault(),Wt(null),!l.trim()){Wt(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Wt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Wt(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const En=g.trim(),Vt=A.trim(),sc=X.trim();if(!En&&!Vt&&!sc){Wt(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!le.trim()&&!oe.trim()){Wt(n("smartPlugs.restUrlRequired"));return}const Wn={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&Ae||null,ha_energy_today_entity:s==="homeassistant"&&Te||null,ha_energy_total_entity:s==="homeassistant"&&Ee||null,mqtt_power_topic:s==="mqtt"&&g.trim()||null,mqtt_power_path:s==="mqtt"&&k.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&A.trim()||null,mqtt_energy_path:s==="mqtt"&&C.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat($)||1,mqtt_state_topic:s==="mqtt"&&X.trim()||null,mqtt_state_path:s==="mqtt"&&te.trim()||null,mqtt_state_on_value:s==="mqtt"&&ee.trim()||null,rest_on_url:s==="rest"&&le.trim()||null,rest_on_body:s==="rest"&&K.trim()||null,rest_off_url:s==="rest"&&oe.trim()||null,rest_off_body:s==="rest"&&_e.trim()||null,rest_method:s==="rest"?Y:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&de.trim()||null,rest_status_on_value:s==="rest"&&G.trim()||null,rest_power_url:s==="rest"&&V.trim()||null,rest_power_path:s==="rest"&&ie.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(fe)||1,rest_energy_url:s==="rest"&&U.trim()||null,rest_energy_path:s==="rest"&&re.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(we)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Ft,power_alert_enabled:Ue,power_alert_high:pt?parseFloat(pt):null,power_alert_low:Le?parseFloat(Le):null,schedule_enabled:Ce,schedule_on_time:Xe||null,schedule_off_time:Ze||null,show_in_switchbar:bt,show_on_printer_card:vt};i?Hi.mutate(Wn):Bi.mutate(Wn)},pa=Bi.isPending||Hi.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:jt=>jt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Hc,className:"p-6 space-y-4 overflow-y-auto",children:[Qt&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Qt}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(ql,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(Mw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(pO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(yd,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[St?a.jsxs(Ie,{type:"button",variant:"secondary",onClick:ra,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(Ie,{type:"button",variant:"primary",onClick:na,className:"w-full",children:[a.jsx(Sr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),St&&Zt.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Zt.scanned," / ",Zt.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Zt.scanned/Zt.total*100}%`}})})]}),Nn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:Nn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Nn.map(jt=>a.jsxs("button",{type:"button",onClick:()=>jr(jt),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ql,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:jt.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:jt.ip_address})]})]}),jt.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${jt.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(im,{className:"w-3 h-3"}),jt.state]})]},jt.ip_address))})]}),!St&&Nn.length===0&&Zt.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:n("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Gn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.haNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.haSettingsPath")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:n("smartPlugs.selectEntity")}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Gn&&a.jsxs(a.Fragment,{children:[On&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),mi&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:n("smartPlugs.failedToLoadEntities",{error:mi.message})}),(()=>{const jt=rn?.filter(Vt=>Vt.ha_entity_id&&Vt.id!==t?.id).map(Vt=>Vt.ha_entity_id)||[],Wn=(ar||[]).filter(Vt=>!jt.includes(Vt.entity_id)),En=ar?.find(Vt=>Vt.entity_id===v);return a.jsxs("div",{ref:Ne,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.selectEntity")}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:ce?je:En?`${En.friendly_name} (${En.entity_id})`:"",onChange:Vt=>{qe(Vt.target.value),ce||ze(!0)},onFocus:()=>{ze(!0),qe("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!ce&&a.jsx("button",{type:"button",onClick:()=>{b(""),qe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),On&&a.jsx(ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),ce&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[On&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!On&&Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Re?n("smartPlugs.noEntitiesMatching",{search:Re}):n("smartPlugs.noEntitiesAvailable")}),!On&&Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{b(Vt.entity_id),ze(!1),qe(""),l||c(Vt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Vt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:Vt.entity_id}),a.jsx("span",{className:Vt.state==="on"?"text-bambu-green":"",children:Vt.state})]})]},Vt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re?n("smartPlugs.searchingEntities",{count:Wn.length}):n("smartPlugs.showingEntities",{count:Wn.length})})]})})(),v&&Rn&&Rn.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:n("smartPlugs.energyMonitoringOptional")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:n("smartPlugs.energyMonitoringHint")})]}),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="W"||Vt.unit_of_measurement==="kW"||Vt.unit_of_measurement==="mW"),Wn=Ge?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Ge.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Ge.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===Ae);return a.jsxs("div",{ref:Ve,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.powerSensorW")}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Pe?Ge:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{$e(Vt.target.value),Pe||Me(!0)},onFocus:()=>{Me(!0),$e("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Ae&&!Pe&&a.jsx("button",{type:"button",onClick:()=>{ve(""),$e("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Pe&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ve(""),Me(!1),$e("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{ve(Vt.entity_id),Me(!1),$e("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=tt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(tt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(tt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===Te);return a.jsxs("div",{ref:Ht,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.energyTodayKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:xt?tt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{ut(Vt.target.value),xt||wt(!0)},onFocus:()=>{wt(!0),ut("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Te&&!xt&&a.jsx("button",{type:"button",onClick:()=>{Fe(""),ut("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),xt&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Fe(""),wt(!1),ut("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{Fe(Vt.entity_id),wt(!1),ut("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===Te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=Xt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Xt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Xt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===Ee);return a.jsxs("div",{ref:Ke,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.totalEnergyKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Ut?Xt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{Kt(Vt.target.value),Ut||en(!0)},onFocus:()=>{en(!0),Kt("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Ee&&!Ut&&a.jsx("button",{type:"button",onClick:()=>{Se(""),Kt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ut&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Se(""),en(!1),Kt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{Se(Vt.entity_id),en(!1),Kt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===Ee?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!bn?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.mqttNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.mqttSettingsPath")})," ",n("smartPlugs.mqttNotConfiguredSuffix")]}),bn?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:n("smartPlugs.monitorOnly")}),a.jsx("p",{className:"text-xs opacity-80",children:n("smartPlugs.mqttMonitorOnlyDescription")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.powerMonitoring")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:g,onChange:jt=>_(jt.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:k,onChange:jt=>P(jt.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:N,onChange:jt=>M(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttPowerHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:A,onChange:jt=>T(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:C,onChange:jt=>F(jt.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:$,onChange:jt=>I(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttEnergyHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:X,onChange:jt=>L(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:te,onChange:jt=>ae(jt.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.onValue")}),a.jsx("input",{type:"text",value:ee,onChange:jt=>me(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.restControl")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restMethod")}),a.jsxs("select",{value:Y,onChange:jt=>D(jt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"GET",children:"GET"}),a.jsx("option",{value:"POST",children:"POST"}),a.jsx("option",{value:"PUT",children:"PUT"}),a.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOnUrl")}),a.jsx("input",{type:"text",value:le,onChange:jt=>{ue(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOnBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:K,onChange:jt=>ne(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOffUrl")}),a.jsx("input",{type:"text",value:oe,onChange:jt=>{be(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOffBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:_e,onChange:jt=>B(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.restHeaders")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("div",{children:a.jsx("textarea",{value:j,onChange:jt=>z(jt.target.value),placeholder:n("smartPlugs.restHeadersHint"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none font-mono text-sm"})})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusUrl")}),a.jsx("input",{type:"text",value:W,onChange:jt=>q(jt.target.value),placeholder:n("smartPlugs.restStatusHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusPath")}),a.jsx("input",{type:"text",value:de,onChange:jt=>O(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusOnValue")}),a.jsx("input",{type:"text",value:G,onChange:jt=>Q(jt.target.value),placeholder:"ON",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restPowerUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:V,onChange:jt=>J(jt.target.value),placeholder:n("smartPlugs.restPowerUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerPath")}),a.jsx("input",{type:"text",value:ie,onChange:jt=>he(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerMultiplier")}),a.jsx("input",{type:"text",value:fe,onChange:jt=>se(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restEnergyUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:U,onChange:jt=>R(jt.target.value),placeholder:n("smartPlugs.restEnergyUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyPath")}),a.jsx("input",{type:"text",value:re,onChange:jt=>xe(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyMultiplier")}),a.jsx("input",{type:"text",value:we,onChange:jt=>ye(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.restEnergyHint")})]}),(le.trim()||oe.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:async()=>{Mt(null);try{const jt=le.trim()||oe.trim(),Wn=await pe.testRESTConnection(jt,Y,j.trim()||null);Mt({success:Wn.success}),Wn.success||Wt(Wn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{Mt({success:!1}),Wt(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),ht&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${ht.success?"text-green-400":"text-red-400"}`,children:[ht.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx(Ku,{className:"w-4 h-4"}),ht.success?n("smartPlugs.connectionSuccess"):n("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.ipAddress")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:jt=>{u(jt.target.value),Mt(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>In.mutate(),disabled:!d.trim()||In.isPending,children:[In.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&ht&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ht.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:ht.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:n("smartPlugs.connectedResult")}),a.jsxs("p",{className:"text-sm opacity-80",children:[ht.device_name&&n("smartPlugs.deviceLabel",{name:ht.device_name}),n("smartPlugs.stateLabel",{state:ht.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ku,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.nameLabel")}),a.jsx("input",{type:"text",value:l,onChange:jt=>c(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.username")}),a.jsx("input",{type:"text",value:m,onChange:jt=>p(jt.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.password")}),a.jsx("input",{type:"password",value:f,onChange:jt=>y(jt.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:n("smartPlugs.authHint")})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.linkToPrinter")}),a.jsxs("select",{value:Ft??"",onChange:jt=>Nt(jt.target.value?Number(jt.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:n("smartPlugs.noPrinter")}),Ci?.map(jt=>a.jsx("option",{value:jt.id,children:jt.name},jt.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.linkingDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ah,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.powerAlerts")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ue,onChange:jt=>dt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Ue&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertAbove")}),a.jsx("input",{type:"number",value:pt,onChange:jt=>De(jt.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertBelow")}),a.jsx("input",{type:"number",value:Le,onChange:jt=>at(jt.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.dailySchedule")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ce,onChange:jt=>We(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Ce&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOnAt")}),a.jsx("input",{type:"time",value:Xe,onChange:jt=>Qe(jt.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOffAt")}),a.jsx("input",{type:"time",value:Ze,onChange:jt=>rt(jt.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.scheduleDescription")})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:bt,onChange:jt=>Pt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showOnPrinterCard")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.displayOnPrinterCard")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:vt,onChange:jt=>He(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(Ie,{type:"submit",disabled:pa,className:"flex-1",children:[pa?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function Vn({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}function mtt({provider:t,onEdit:e}){const{t:n}=Lt(),r=mn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:pe.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>pe.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>pe.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),y=lt({mutationFn:()=>pe.testNotificationProvider(t.id),onSuccess:b=>{d(b),r.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),v=b=>b||"";return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-3",children:[a.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Ah,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:n("notifications.lastSuccess",{date:Uf(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Qn(t.last_error_at)?.getTime()||0)>(Qn(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&a.jsxs(a.Fragment,{children:[m&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("notifications.printer")," "]}),a.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.allPrinters")})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:n("notifications.start")}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:n("notifications.plateCheck")}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:n("notifications.complete")}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:n("notifications.failed")}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:n("notifications.stopped")}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:n("notifications.progress")}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:n("notifications.offline")}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:n("notifications.error")}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:n("notifications.lowFilament")}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:n("notifications.maintenance")}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:n("notifications.amsHumidity")}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:n("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:n("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:n("notifications.amsHtTemp")}),t.on_bed_cooled&&a.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:n("notifications.bedCooled")}),t.on_first_layer_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:n("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:n("notifications.missingSpoolAssignmentLabel")}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(aN,{className:"w-3 h-3"}),n("notifications.quiet")]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(Wr,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Ie,{size:"sm",variant:"secondary",disabled:y.isPending,onClick:()=>{d(null),y.mutate()},className:"w-full",children:[y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.sendTestNotification")]})}),c&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx($a,{className:"w-4 h-4"}),a.jsx("span",{children:c.message})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"})]}),o&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.sendFromProvider")})]}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printEvents")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStarted")}),a.jsx(Vn,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.plateNotEmpty")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.plateNotEmptyDescription")})]}),a.jsx(Vn,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printCompleted")}),a.jsx(Vn,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.bedCooledLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.bedCooledDescription")})]}),a.jsx(Vn,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.missingSpoolAssignmentLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.missingSpoolAssignmentDescription")})]}),a.jsx(Vn,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printFailed")}),a.jsx(Vn,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStopped")}),a.jsx(Vn,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.progressMilestones")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.progressMilestonesDescription")})]}),a.jsx(Vn,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerOffline")}),a.jsx(Vn,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerError")}),a.jsx(Vn,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.lowFilamentLabel")}),a.jsx(Vn,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.maintenanceDue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.maintenanceDueDescription")})]}),a.jsx(Vn,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsHtAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printQueue")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAdded")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAddedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAssigned")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAssignedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobStarted")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobStartedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobWaiting")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobWaitingDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobSkipped")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobSkippedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobFailed")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobFailedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.queueComplete")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.queueCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(aN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(Vn,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.noNotificationsDuring")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[v(t.quiet_hours_start)||"22:00"," - ",v(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeQuietHours")})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(Vn,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:n("notifications.sendAt",{time:v(t.daily_digest_time)||"08:00"})})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeDigestTime")})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(xh,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(kn,{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 htt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function ptt({provider:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.provider_type||"email"),[d,u]=w.useState(t?.printer_id||null),[m,p]=w.useState(t?.quiet_hours_enabled||!1),[f,y]=w.useState(t?.quiet_hours_start||"22:00"),[v,b]=w.useState(t?.quiet_hours_end||"07:00"),[g,_]=w.useState(t?.daily_digest_enabled||!1),[k,P]=w.useState(t?.daily_digest_time||"08:00"),[N,M]=w.useState(t?.on_print_start??!1),[A,T]=w.useState(t?.on_print_complete??!0),[C,F]=w.useState(t?.on_print_failed??!0),[$,I]=w.useState(t?.on_print_stopped??!0),[X,L]=w.useState(t?.on_print_progress??!1),[te,ae]=w.useState(t?.on_printer_offline??!1),[ee,me]=w.useState(t?.on_printer_error??!1),[le,ue]=w.useState(t?.on_filament_low??!1),[K,ne]=w.useState(t?.on_maintenance_due??!1),[oe,be]=w.useState(t?.on_bed_cooled??!1),[_e,B]=w.useState(t?.on_first_layer_complete??!1),[Y,D]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([se,U])=>[se,String(U)])):{}),[j,z]=w.useState(null),[W,q]=w.useState(null),{data:de}=et({queryKey:["printers"],queryFn:pe.getPrinters});w.useEffect(()=>{const se=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const O=lt({mutationFn:()=>pe.testNotificationConfig({provider_type:l,config:Y}),onSuccess:se=>{z(se),q(null)},onError:se=>{z({success:!1,message:se.message})}}),G=lt({mutationFn:se=>pe.createNotificationProvider(se),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:se=>{q(se.message)}}),Q=lt({mutationFn:se=>pe.updateNotificationProvider(t.id,se),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:se=>{q(se.message)}}),V=se=>{if(se.preventDefault(),q(null),!s.trim()){q(n("notifications.nameRequired"));return}const U=he(l);for(const re of U)if(!Y[re.key]?.trim()){q(n("notifications.fieldRequired",{field:re.label}));return}const R={name:s.trim(),provider_type:l,config:Y,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?v:null,daily_digest_enabled:g,daily_digest_time:g?k:null,on_print_start:N,on_print_complete:A,on_print_failed:C,on_print_stopped:$,on_print_progress:X,on_printer_offline:te,on_printer_error:ee,on_filament_low:le,on_maintenance_due:K,on_bed_cooled:oe,on_first_layer_complete:_e};i?Q.mutate(R):G.mutate(R)},J=G.isPending||Q.isPending,ie=se=>{switch(se){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},he=se=>ie(se).filter(U=>U.required),fe=ie(l);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:se=>se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"notifications.editTitle":"notifications.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:V,className:"p-6 space-y-4",children:[W&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:W}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.nameLabel")}),a.jsx("input",{type:"text",value:s,onChange:se=>o(se.target.value),placeholder:n("notifications.namePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.providerTypeLabel")}),a.jsx("select",{value:l,onChange:se=>{c(se.target.value),D({}),z(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:htt.map(se=>a.jsx("option",{value:se,children:n(`notifications.providerTypes.${se}`,se)},se))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n(`notifications.providerDescriptions.${l}`,"")})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.configuration")}),fe.filter(se=>!("showIf"in se)||se.showIf?.(Y)!==!1).map(se=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[se.label," ",se.required&&"*"]}),se.type==="select"&&"options"in se&&se.options?a.jsx("select",{value:Y[se.key]||se.options[0]?.value||"",onChange:U=>{D({...Y,[se.key]:U.target.value}),z(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:se.options.map(U=>a.jsx("option",{value:U.value,children:U.label},U.value))}):a.jsx("input",{type:se.type,value:Y[se.key]||"",onChange:U=>{D({...Y,[se.key]:U.target.value}),z(null)},placeholder:se.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"})]},se.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>{z(null),O.mutate()},disabled:O.isPending||he(l).length>0&&!Y[he(l)[0]?.key],className:"flex-1",children:[O.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.testConfiguration")]})}),j&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${j.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:j.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx($a,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.printerFilter")}),a.jsxs("select",{value:d??"",onChange:se=>u(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:n("notifications.allPrinters")}),de?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.onlyFromPrinter")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.quietHoursDnd")}),a.jsx(Vn,{checked:m,onChange:p})]}),m&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietStart")}),a.jsx("input",{type:"time",value:f,onChange:se=>y(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietEnd")}),a.jsx("input",{type:"time",value:v,onChange:se=>b(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.dailyDigestLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")})]}),a.jsx(Vn,{checked:g,onChange:_})]}),g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.sendDigestAt")}),a.jsx("input",{type:"time",value:k,onChange:se=>P(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.digestCollected")})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.notificationEvents")}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printEvents")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.start")}),a.jsx(Vn,{checked:N,onChange:M})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(Vn,{checked:A,onChange:T})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(Vn,{checked:C,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(Vn,{checked:$,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.progress")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.progressPercent")})]}),a.jsx(Vn,{checked:X,onChange:L})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.bedCooled")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.bedCooledAfterPrint")})]}),a.jsx(Vn,{checked:oe,onChange:be})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:_e,onChange:B})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.offline")}),a.jsx(Vn,{checked:te,onChange:ae})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.error")}),a.jsx(Vn,{checked:ee,onChange:me})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(Vn,{checked:le,onChange:ue})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(Vn,{checked:K,onChange:ne})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(Ie,{type:"submit",disabled:J,className:"flex-1",children:[J?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function ftt({template:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=w.useRef(null),[s,o]=w.useState(t.title_template),[l,c]=w.useState(t.body_template),[d,u]=w.useState(null),[m,p]=w.useState(!0),{data:f}=et({queryKey:["template-variables"],queryFn:pe.getTemplateVariables}),y=f?.find(M=>M.event_type===t.event_type),{data:v,isLoading:b}=et({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>pe.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const M=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e]);const g=lt({mutationFn:M=>pe.updateNotificationTemplate(t.id,M),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:M=>{u(M.message)}}),_=lt({mutationFn:()=>pe.resetNotificationTemplate(t.id),onSuccess:M=>{o(M.title_template),c(M.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:M=>{u(M.message)}}),k=M=>{if(M.preventDefault(),u(null),!s.trim()){u(n("notifications.titleRequired"));return}if(!l.trim()){u(n("notifications.bodyRequired"));return}g.mutate({title_template:s,body_template:l})},P=M=>{const A=i.current;if(!A)return;const T=A.selectionStart,C=A.selectionEnd,F=l,$=F.substring(0,T),I=F.substring(C),X=$+`{${M}}`+I;c(X),setTimeout(()=>{A.focus();const L=T+M.length+2;A.setSelectionRange(L,L)},0)},N=s!==t.title_template||l!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("notifications.editTemplate",{name:t.name})}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:k,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.titleLabel")}),a.jsx("input",{type:"text",value:s,onChange:M=>o(M.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:n("notifications.titlePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.bodyLabel")}),a.jsx("textarea",{ref:i,value:l,onChange:M=>c(M.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")})]}),y&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:n("notifications.availableVariables")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:y.variables.map(M=>a.jsxs("button",{type:"button",onClick:()=>P(M),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(ur,{className:"w-3 h-3"}),M]},M))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:n("notifications.clickToInsert")})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4"}),n("notifications.livePreview")]}),a.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:n(m?"notifications.hide":"notifications.show")})]}),m&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("notifications.loadingPreview")]}):v?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.titlePreview")}),a.jsx("div",{className:"text-white font-medium",children:v.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.bodyPreview")}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:v.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:n("notifications.enterTemplateContent")})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Ie,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(jo,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(Ie,{onClick:k,disabled:g.isPending||!N,children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(cs,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const gtt={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 btt({onClose:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=et({queryKey:["settings"],queryFn:pe.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:y,isRefetching:v}=et({queryKey:["notification-logs",i,c],queryFn:()=>pe.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=et({queryKey:["notification-log-stats",i],queryFn:()=>pe.getNotificationLogStats(i)}),g=lt({mutationFn:()=>pe.clearNotificationLogs(30),onSuccess:k=>{r(k.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:k=>{r(`Failed to clear logs: ${k.message}`,"error")}}),_=k=>{const P=Qn(k);if(!P)return"";const M=new Date().getTime()-P.getTime();return M<6e4?e("notifications.justNow"):M<36e5?`${Math.floor(M/6e4)}m ago`:M<864e5?`${Math.floor(M/36e5)}h ago`:P.toLocaleDateString()+" "+DQ(P,m)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(L0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",a.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(fr,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx($a,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:i,onChange: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:[a.jsx("option",{value:1,children:e("notifications.last24Hours")}),a.jsx("option",{value:7,children:e("notifications.last7Days")}),a.jsx("option",{value:30,children:e("notifications.last30Days")}),a.jsx("option",{value:90,children:e("notifications.last90Days")})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:k=>d(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>y(),disabled:v,children:[v?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(k=>a.jsx(xtt,{log:k,isExpanded:o===k.id,onToggle:()=>l(o===k.id?null:k.id),formatDate:_,formatFullDate:P=>Bf(P,m)},k.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(L0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function xtt({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Lt();return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(fr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx($a,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${gtt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(Yl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),a.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}function ytt({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Lt();w.useEffect(()=>{const d=u=>{u.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const c=d=>{e({...t,group_ids:t.group_ids.includes(d)?t.group_ids.filter(u=>u!==d):[...t.group_ids,d]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:d=>e({...t,username:d.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:d=>e({...t,email:d.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(d=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(d.id),onChange:()=>c(d.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:d.name}),d.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},d.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Ie,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function vtt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[d,u]=w.useState(!1),[m,p]=w.useState(!0),[f,y]=w.useState("all"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),{data:N,isLoading:M}=et({queryKey:["spoolman-settings"],queryFn:pe.getSpoolmanSettings}),{data:A,isLoading:T,refetch:C}=et({queryKey:["spoolman-status"],queryFn:pe.getSpoolmanStatus,refetchInterval:3e4}),{data:F}=et({queryKey:["printers"],queryFn:pe.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),u(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),b(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==d||N.spoolman_report_partial_usage!=="false"!==m){const ne=setTimeout(()=>{$.mutate()},500);return()=>clearTimeout(ne)}},[r,s,l,d,m,v]);const $=lt({mutationFn:()=>pe.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),n(t("settings.toast.settingsSaved"))}}),I=lt({mutationFn:pe.connectSpoolman,onSuccess:()=>{C()}}),X=lt({mutationFn:pe.disconnectSpoolman,onSuccess:()=>{C()}}),L=lt({mutationFn:pe.syncAllPrintersAms,onSuccess:K=>{K.success}}),te=lt({mutationFn:K=>pe.syncPrinterAms(K),onSuccess:K=>{K.success}}),ae=()=>{f==="all"?L.mutate():te.mutate(f)},ee=lt({mutationFn:pe.syncWeightsFromAms,onSuccess:K=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:K.synced,skipped:K.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),me=L.isPending||te.isPending,le=f==="all"?L.data:te.data,ue=f==="all"?L.isSuccess:te.isSuccess;return M?a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),$.isPending&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(Na,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(sa,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:ee.isPending,children:[ee.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(vr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:K=>c(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:K=>u(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),d&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:m,onChange:K=>p(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),T?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):A?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Kr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Bt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:A?.connected?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[X.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Sge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Ie,{size:"sm",onClick:()=>I.mutate(),disabled:I.isPending||!s,children:[I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lu,{className:"w-4 h-4"}),t("settings.connect")]})})]}),I.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:I.error.message}),A?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:f,onChange:K=>y(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),F?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(Fn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ae,disabled:me,children:[me?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),ue&&le&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${le.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:le.success?`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} successfully`:`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} with ${le.errors.length} error${le.errors.length!==1?"s":""}`}),le.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[le.skipped_count," spool",le.skipped_count!==1?"s":""," skipped"]})]}),le.skipped_count>5&&a.jsx("button",{onClick:()=>_(!g),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:g?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(g?le.skipped:le.skipped.slice(0,5)).map((K,ne)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},ne)),!g&&le.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",le.skipped_count-5," more"]})]})]}),le.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:le.errors.map((K,ne)=>a.jsx("li",{children:K},ne))})]})]})]})]})]}),k&&a.jsx(kn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:ee.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>ee.mutate(),onCancel:()=>P(!1)})]})}function wtt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(!1),[k,P]=w.useState(new Set),[N,M]=w.useState(!1),[A,T]=w.useState(null),[C,F]=w.useState(!1),$=w.useCallback(async()=>{try{const be=await pe.getSpoolCatalog();r(be)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{$()},[$]);const I=n.filter(be=>be.name.toLowerCase().includes(o.toLowerCase())),X=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const be=await pe.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(_e=>[..._e,be].sort((B,Y)=>B.name.localeCompare(Y.name))),u(!1),y(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=be=>{p(be.id),y(be.name),b(be.weight.toString())},te=()=>{p(null),y(""),b("")},ae=async be=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const _e=await pe.updateCatalogEntry(be,{name:f.trim(),weight:parseInt(v)});r(B=>B.map(Y=>Y.id===be?_e:Y).sort((Y,D)=>Y.name.localeCompare(D.name))),p(null),y(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},ee=async()=>{if(A)try{await pe.deleteCatalogEntry(A.id),r(be=>be.filter(_e=>_e.id!==A.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{T(null)}},me=async()=>{F(!1),s(!0);try{await pe.resetSpoolCatalog(),await $(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},le=be=>{P(_e=>{const B=new Set(_e);return B.has(be)?B.delete(be):B.add(be),B})},ue=()=>{k.size===I.length?P(new Set):P(new Set(I.map(be=>be.id)))},K=async()=>{if(M(!1),k.size!==0)try{const be=await pe.bulkDeleteCatalogEntries([...k]);r(_e=>_e.filter(B=>!k.has(B.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:be.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},ne=()=>{const be=n.map(({name:D,weight:j})=>({name:D,weight:j})),_e=new Blob([JSON.stringify(be,null,2)],{type:"application/json"}),B=URL.createObjectURL(_e),Y=document.createElement("a");Y.href=B,Y.download="spool-catalog.json",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL(B),e(t("settings.catalog.exported",{count:n.length}),"success")},oe=async be=>{const _e=be.target.files?.[0];if(_e){try{const B=await _e.text(),Y=JSON.parse(B);if(!Array.isArray(Y))throw new Error("Invalid format");let D=0,j=0;for(const z of Y){if(!z.name||typeof z.weight!="number"){j++;continue}if(n.some(q=>q.name.toLowerCase()===z.name.toLowerCase())){j++;continue}try{const q=await pe.addCatalogEntry({name:z.name,weight:z.weight});r(de=>[...de,q].sort((O,G)=>O.name.localeCompare(G.name))),D++}catch{j++}}e(t("settings.catalog.imported",{added:D,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(Dt,{children:[a.jsxs(Dn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:ne,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[a.jsx(va,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[a.jsx(Ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:oe}),a.jsxs("button",{onClick:()=>F(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[a.jsx(jo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(ur,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),k.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:k.size})}),a.jsxs("button",{onClick:()=>M(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(un,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),a.jsx("button",{onClick:()=>P(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:be=>l(be.target.value)})]}),d&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:f,onChange:be=>y(be.target.value)})}),a.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:be=>b(be.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:X,disabled:g,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:[g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),y(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:I.length>0&&k.size===I.length,onChange:ue,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:I.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(be=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.has(be.id)?"bg-bambu-dark":""}`,children:m===be.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:f,onChange:_e=>y(_e.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:_e=>b(_e.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>ae(be.id),disabled:g,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:te,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2 text-white",children:be.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[be.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:be.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(be),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>T(be),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(un,{className:"w-4 h-4"})})]})})]})},be.id))})]})})]}),A&&a.jsx(kn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:A.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:ee,onCancel:()=>T(null)}),N&&a.jsx(kn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:K,onCancel:()=>M(!1)}),C&&a.jsx(kn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:me,onCancel:()=>F(!1)})]})}function Stt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,d]=w.useState("Bambu Lab"),u=w.useRef(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),[v,b]=w.useState(""),[g,_]=w.useState(""),[k,P]=w.useState("#FFFFFF"),[N,M]=w.useState(""),[A,T]=w.useState(!1),[C,F]=w.useState(new Set),[$,I]=w.useState(!1),[X,L]=w.useState(!1),[te,ae]=w.useState(null),[ee,me]=w.useState(null),[le,ue]=w.useState(!1),K=w.useCallback(async()=>{try{const V=await pe.getColorCatalog();r(V)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{K()},[K]);const ne=[...new Set(n.map(V=>V.manufacturer))].sort(),oe=n.filter(V=>{const J=o===""||V.manufacturer.toLowerCase().includes(o.toLowerCase())||V.color_name.toLowerCase().includes(o.toLowerCase())||(V.material?.toLowerCase().includes(o.toLowerCase())??!1),ie=c===""||V.manufacturer===c;return J&&ie}),be=()=>{b(""),_(""),P("#FFFFFF"),M("")},_e=async()=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}T(!0);try{const V=await pe.addColorEntry({manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(J=>[...J,V].sort((ie,he)=>ie.manufacturer.localeCompare(he.manufacturer)||(ie.material||"").localeCompare(he.material||"")||ie.color_name.localeCompare(he.color_name))),p(!1),be(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{T(!1)}},B=V=>{y(V.id),b(V.manufacturer),_(V.color_name),P(V.hex_color),M(V.material||"")},Y=()=>{y(null),be()},D=async V=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}T(!0);try{const J=await pe.updateColorEntry(V,{manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(ie=>ie.map(he=>he.id===V?J:he).sort((he,fe)=>he.manufacturer.localeCompare(fe.manufacturer)||(he.material||"").localeCompare(fe.material||"")||he.color_name.localeCompare(fe.color_name))),y(null),be(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{T(!1)}},j=async()=>{if(ee)try{await pe.deleteColorEntry(ee.id),r(V=>V.filter(J=>J.id!==ee.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{me(null)}},z=async()=>{ue(!1),s(!0);try{await pe.resetColorCatalog(),await K(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},W=async()=>{L(!0),ae(null);try{const V={},J=Yu();J&&(V.Authorization=`Bearer ${J}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:V});if(!ie.ok)throw new Error("Failed to start sync");const he=ie.body?.getReader();if(!he)throw new Error("No response body");const fe=new TextDecoder;let se="";for(;;){const{done:U,value:R}=await he.read();if(U)break;se+=fe.decode(R,{stream:!0});const re=se.split(`
  8330. `);se=re.pop()||"";for(const xe of re)if(xe.startsWith("data: "))try{const we=JSON.parse(xe.slice(6));we.type==="progress"?ae({fetched:we.total_fetched,total:we.total_available}):we.type==="complete"?we.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:we.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:we.added,skipped:we.skipped}),"success"):we.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${we.error}`,"error")}catch{}}await K()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{L(!1),ae(null)}},q=V=>{F(J=>{const ie=new Set(J);return ie.has(V)?ie.delete(V):ie.add(V),ie})},de=()=>{C.size===oe.length?F(new Set):F(new Set(oe.map(V=>V.id)))},O=async()=>{if(I(!1),C.size!==0)try{const V=await pe.bulkDeleteColorEntries([...C]);r(J=>J.filter(ie=>!C.has(ie.id))),F(new Set),e(t("settings.colorCatalog.bulkDeleted",{count:V.deleted}),"success")}catch{e(t("settings.colorCatalog.bulkDeleteFailed"),"error")}},G=()=>{const V=n.map(({manufacturer:fe,color_name:se,hex_color:U,material:R})=>({manufacturer:fe,color_name:se,hex_color:U,material:R})),J=new Blob([JSON.stringify(V,null,2)],{type:"application/json"}),ie=URL.createObjectURL(J),he=document.createElement("a");he.href=ie,he.download="color-catalog.json",document.body.appendChild(he),he.click(),document.body.removeChild(he),URL.revokeObjectURL(ie),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},Q=async V=>{const J=V.target.files?.[0];if(J){try{const ie=await J.text(),he=JSON.parse(ie);if(!Array.isArray(he))throw new Error("Invalid format");let fe=0,se=0;for(const U of he){if(!U.manufacturer||!U.color_name||!U.hex_color){se++;continue}if(n.some(re=>re.manufacturer.toLowerCase()===U.manufacturer.toLowerCase()&&re.color_name.toLowerCase()===U.color_name.toLowerCase()&&(re.material||"").toLowerCase()===(U.material||"").toLowerCase())){se++;continue}try{const re=await pe.addColorEntry({manufacturer:U.manufacturer,color_name:U.color_name,hex_color:U.hex_color,material:U.material||null});r(xe=>[...xe,re].sort((we,ye)=>we.manufacturer.localeCompare(ye.manufacturer)||(we.material||"").localeCompare(ye.material||"")||we.color_name.localeCompare(ye.color_name))),fe++}catch{se++}}e(t("settings.colorCatalog.imported",{added:fe,skipped:se}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return a.jsxs(Dt,{children:[a.jsxs(Dn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Dw,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:G,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(va,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>u.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(Ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:u,type:"file",accept:".json",className:"hidden",onChange:Q}),a.jsxs("button",{onClick:W,disabled:X,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.colorCatalog.syncTooltip"),children:[X?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Jx,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:X?te?`${Math.min(te.fetched,te.total)} / ${te.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),a.jsxs("button",{onClick:()=>ue(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(jo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>p(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(ur,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),C.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.colorCatalog.selectedCount",{count:C.size})}),a.jsxs("button",{onClick:()=>I(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(un,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),a.jsx("button",{onClick:()=>F(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),a.jsxs("div",{className:"flex gap-2 flex-wrap",children:[a.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.searchColors"),value:o,onChange:V=>l(V.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:V=>d(V.target.value),children:[a.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),ne.map(V=>a.jsx("option",{value:V,children:V},V))]})]}),m&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.manufacturer"),value:v,onChange:V=>b(V.target.value)}),a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.colorName"),value:g,onChange:V=>_(V.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:V=>P(V.target.value)}),a.jsx("input",{type:"text",className:"w-32 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:"#FFFFFF",value:k,onChange:V=>P(V.target.value)})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"text",className:"flex-1 max-w-lg min-w-[200px] px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.materialOptional"),value:N,onChange:V=>M(V.target.value)}),a.jsxs("button",{onClick:_e,disabled:A,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:[A?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{p(!1),be()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]})]}),(o||c)&&a.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:oe.length,total:n.length})}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:oe.length>0&&C.size===oe.length,onChange:de,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),a.jsx("th",{className:"px-3 py-2 w-16"})]})}),a.jsx("tbody",{children:oe.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):oe.map(V=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${C.has(V.id)?"bg-bambu-dark":""}`,children:f===V.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(V.id),onChange:()=>q(V.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:v,onChange:J=>b(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:N,onChange:J=>M(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:g,onChange:J=>_(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:k,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>D(V.id),disabled:A,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:A?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:Y,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(V.id),onChange:()=>q(V.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:V.hex_color},title:V.hex_color})}),a.jsx("td",{className:"px-3 py-2 text-white",children:V.manufacturer}),a.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:V.material||"-"}),a.jsx("td",{className:"px-3 py-2 text-white",children:V.color_name}),a.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:V.hex_color}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>B(V),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>me(V),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(un,{className:"w-4 h-4"})})]})})]})},V.id))})]})})]}),ee&&a.jsx(kn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${ee.manufacturer} - ${ee.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:j,onCancel:()=>me(null)}),$&&a.jsx(kn,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:C.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:O,onCancel:()=>I(!1)}),le&&a.jsx(kn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:z,onCancel:()=>ue(!1)})]})}function _tt({link:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.url||""),[u,m]=w.useState(t?.icon||"link"),[p,f]=w.useState(t?.open_in_new_tab||!1),[y,v]=w.useState(!!t?.custom_icon),[b,g]=w.useState(t?.custom_icon?pe.getExternalLinkIconUrl(t.id):null),[_,k]=w.useState(null),[P,N]=w.useState(null);w.useEffect(()=>{const X=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[e]);const M=lt({mutationFn:async X=>{const L=await pe.createExternalLink(X);return _?await pe.uploadExternalLinkIcon(L.id,_):L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:X=>{N(X.message)}}),A=lt({mutationFn:async X=>{let L=await pe.updateExternalLink(t.id,X);return _?L=await pe.uploadExternalLinkIcon(t.id,_):!y&&t?.custom_icon&&(L=await pe.deleteExternalLinkIcon(t.id)),L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:X=>{N(X.message)}}),T=X=>{const L=X.target.files?.[0];if(L){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(L.type)){N("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(L.size>1024*1024){N("Image file must be less than 1MB");return}k(L),v(!0);const ae=new FileReader;ae.onload=ee=>{g(ee.target?.result)},ae.readAsDataURL(L)}},C=()=>{k(null),g(null),v(!1),s.current&&(s.current.value="")},F=X=>{if(X.preventDefault(),N(null),!o.trim()){N("Name is required");return}if(!c.trim()){N("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){N("URL must start with http:// or https://");return}const L={name:o.trim(),url:c.trim(),icon:u,open_in_new_tab:p};i?A.mutate(L):M.mutate(L)},$=M.isPending||A.isPending,I=TP(u);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:X=>X.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:y&&b?a.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):a.jsx(I,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:F,className:"p-6 space-y-4",children:[P&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:P}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:o,onChange:X=>l(X.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:c,onChange:X=>d(X.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),a.jsx("button",{type:"button",onClick:()=>f(!p),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:T}),y&&b?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:b,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:C,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(un,{className:"w-4 h-4"})})]}):a.jsxs(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[a.jsx(Ca,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!y&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(Oxe,{value:u,onChange:m})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ie,{type:"submit",disabled:$,className:"flex-1",children:[$?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function ktt(){const{t}=Lt(),e=mn(),[n,r]=w.useState(!1),[i,s]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),{data:u,isLoading:m}=et({queryKey:["external-links"],queryFn:pe.getExternalLinks}),p=lt({mutationFn:k=>pe.deleteExternalLink(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=lt({mutationFn:k=>pe.reorderExternalLinks(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),y=(k,P)=>{d(P),k.dataTransfer.effectAllowed="move"},v=k=>{k.preventDefault(),k.dataTransfer.dropEffect="move"},b=(k,P)=>{if(k.preventDefault(),c===null||c===P||!u)return;const N=u.map(C=>C.id),M=N.indexOf(c),A=N.indexOf(P);if(M===-1||A===-1)return;const T=[...N];T.splice(M,1),T.splice(A,0,c),f.mutate(T),d(null)},g=k=>{l(k)},_=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Lu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Ie,{size:"sm",onClick:()=>r(!0),children:[a.jsx(ur,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Rt,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),m?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"space-y-2",children:u.map(k=>{const P=TP(k.icon);return a.jsxs("div",{draggable:!0,onDragStart:N=>y(N,k.id),onDragOver:v,onDrop:N=>b(N,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:[a.jsx(Eh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(P,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white font-medium truncate",children:k.name}),a.jsx(sa,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:k.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.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:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>g(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:a.jsx(un,{className:"w-4 h-4"})})]})]},k.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Lu,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(_tt,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(kn,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:_,onCancel:()=>l(null)})]})}const s3={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function Ntt({printer:t,models:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[d,u]=w.useState(t.name),[m,p]=w.useState(""),[f,y]=w.useState(t.mode==="queue"?"review":t.mode),[v,b]=w.useState(t.target_printer_id),[g,_]=w.useState(t.bind_ip||""),[k,P]=w.useState(t.remote_interface_ip||""),[N,M]=w.useState(t.model||""),[A,T]=w.useState(t.auto_dispatch??!0),[C,F]=w.useState(!1),[$,I]=w.useState(null),[X,L]=w.useState(!1);w.useEffect(()=>{$||(c(t.enabled),y(t.mode==="queue"?"review":t.mode),u(t.name),b(t.target_printer_id),_(t.bind_ip||""),P(t.remote_interface_ip||""),M(t.model||""),T(t.auto_dispatch??!0))},[t,$]);const{data:te}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:ae}=et({queryKey:["network-interfaces"],queryFn:()=>pe.getNetworkInterfaces().then(j=>j.interfaces)}),ee=lt({mutationFn:j=>oN.update(t.id,j),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.updated")),I(null)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),y(t.mode==="queue"?"review":t.mode),b(t.target_printer_id),_(t.bind_ip||""),I(null)}}),me=lt({mutationFn:()=>oN.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.deleted")),L(!1)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToDelete"),"error"),L(!1)}}),le=j=>{j.stopPropagation();const z=!l;if(z){if(!g){i(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(f==="proxy"){if(!v){i(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!m&&!t.access_code_set){i(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(z),I("toggle"),ee.mutate({enabled:z})},ue=()=>{d.trim()&&(I("name"),ee.mutate({name:d.trim()}))},K=()=>{if(!m){i(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(m.length!==8){i(n("virtualPrinter.toast.accessCodeLength"),"error");return}I("accessCode"),ee.mutate({access_code:m}),p("")},ne=j=>{y(j),I("mode"),ee.mutate({mode:j})},oe=j=>{M(j),I("model"),ee.mutate({model:j})},be=j=>{b(j),I("targetPrinter"),ee.mutate({target_printer_id:j})},_e=j=>{P(j),I("remoteInterface"),ee.mutate({remote_interface_ip:j})},B=t.status?.running||!1,Y=n(`virtualPrinter.mode.${s3[f]||"archive"}`),D=te?.find(j=>j.id===v)?.name;return a.jsxs(a.Fragment,{children:[a.jsxs(Dt,{children:[a.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[a.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?a.jsx(Fn,{className:"w-4 h-4"}):a.jsx(Va,{className:"w-4 h-4"})}),a.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${B?"bg-green-400 animate-pulse":"bg-gray-500"}`}),a.jsx("span",{className:"text-white font-medium truncate",children:t.name}),a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:Y}),t.model_name&&a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),D&&a.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&a.jsx(L3,{className:"w-3 h-3 inline mr-1"}),D]}),g&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:g}),k&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:k}),a.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:j=>j.stopPropagation(),children:a.jsx("button",{onClick:le,disabled:$==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${$==="toggle"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${l?"translate-x-5":""}`})})})]}),s&&a.jsxs(Rt,{className:"pt-0 space-y-4",children:[a.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:j=>u(j.target.value),onBlur:ue,onKeyDown:j=>j.key==="Enter"&&ue(),className:"flex-1 text-sm text-white bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),a.jsx("button",{onClick:()=>L(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(j=>a.jsxs("button",{onClick:()=>ne(j),disabled:$==="mode",className:`p-2 rounded-lg border text-left transition-colors ${f===j?j==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[j==="proxy"&&a.jsx(L3,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${s3[j]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${s3[j]}Desc`)})]},j))})]}),f==="print_queue"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.autoDispatch.title")}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.autoDispatch.description")})]}),a.jsx("button",{onClick:()=>{const j=!A;T(j),I("autoDispatch"),ee.mutate({auto_dispatch:j})},disabled:$==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${A?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${$==="autoDispatch"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${A?"translate-x-5":""}`})})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:N,onChange:j=>oe(j.target.value),disabled:$==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:Object.entries(e).map(([j,z])=>a.jsxs("option",{value:j,children:[z," (",j,")"]},j))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),f==="proxy"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[a.jsx(Kr,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:C?"text":"password",value:m,onChange:j=>p(j.target.value),placeholder:t.access_code_set?n("virtualPrinter.accessCode.placeholderChange"):n("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm placeholder-bambu-gray pr-10 font-mono"}),a.jsx("button",{onClick:()=>F(!C),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:C?a.jsx(Tw,{className:"w-4 h-4"}):a.jsx(Dc,{className:"w-4 h-4"})})]}),a.jsx(Ie,{onClick:K,disabled:!m||$==="accessCode",variant:"primary",children:$==="accessCode"?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a.jsx("span",{className:m.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:m.length})})})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:v??"",onChange:j=>{const z=parseInt(j.target.value,10);isNaN(z)||be(z)},disabled:$==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),te?.map(j=>a.jsxs("option",{value:j.id,children:[j.name," (",j.ip_address,")"]},j.id))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:g,onChange:j=>{_(j.target.value),I("bindIp"),ee.mutate({bind_ip:j.target.value})},disabled:$==="bindIp",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),ae?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,")",j.is_alias?" [alias]":""," - ",j.subnet]},j.ip))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),k?a.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:a.jsx(Kr,{className:"w-3 h-3"})}):a.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:a.jsx(Ks,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k,onChange:j=>_e(j.target.value),disabled:$==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),ae?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,") - ",j.subnet]},j.ip))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),X&&a.jsx(kn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:me.isPending,onConfirm:()=>me.mutate(),onCancel:()=>L(!1)})]})}const QY={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function Ctt({onClose:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,d]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:pe.getPrinters}),m=lt({mutationFn:()=>oN.create({name:i.trim()||"Bambuddy",mode:o,target_printer_id:o==="proxy"?c??void 0:void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["virtual-printers"]}),r(e("virtualPrinter.toast.created")),t()},onError:p=>{r(p.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:a.jsxs(Rt,{className:"p-6 space-y-4",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),a.jsx("input",{type:"text",value:i,onChange:p=>s(p.target.value),placeholder:"Bambuddy",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm placeholder-bambu-gray",autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(p=>a.jsxs("button",{onClick:()=>l(p),className:`p-2 rounded-lg border text-left transition-colors ${o===p?p==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[p==="proxy"&&a.jsx(L3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${QY[p]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${QY[p]}Desc`)})]},p))})]}),o==="proxy"&&a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:c??"",onChange:p=>{const f=parseInt(p.target.value,10);d(isNaN(f)?null:f)},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm appearance-none cursor-pointer pr-10",children:[a.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),u?.map(p=>a.jsxs("option",{value:p.id,children:[p.name," (",p.ip_address,")"]},p.id))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),a.jsx(Ie,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function Ptt(){const{t}=Lt(),[e,n]=w.useState(!1),{data:r,isLoading:i}=et({queryKey:["virtual-printers"],queryFn:oN.list,refetchInterval:1e4});if(i)return a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[a.jsx(Dt,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Rt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs",children:[a.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),a.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 mt-2 px-3 py-1.5 bg-yellow-500/20 border border-yellow-500/50 rounded text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs",children:[a.jsx(sa,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(Dt,{className:"lg:col-span-3",children:a.jsx(Rt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),a.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Pr,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),a.jsxs(Ie,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-8 text-center",children:[a.jsx(Pr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),a.jsxs(Ie,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>a.jsx(Ntt,{printer:l,models:o},l.id))}),e&&a.jsx(Ctt,{onClose:()=>n(!1)})]})}function Ttt(t){if(!t)return"-";const e=Qn(t);return e?e.toLocaleString():"-"}function ZY({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:a.jsx(fr,{className:"w-3 h-3"}),failed:a.jsx($a,{className:"w-3 h-3"}),skipped:a.jsx(CP,{className:"w-3 h-3"}),running:a.jsx(ct,{className:"w-3 h-3 animate-spin"})};return a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function Att(){const t=mn(),{showToast:e}=xn(),{t:n}=Lt(),[r,i]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[d,u]=w.useState(!1),[m,p]=w.useState("daily"),[f,y]=w.useState(!0),[v,b]=w.useState(!0),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[A,T]=w.useState(!0),[C,F]=w.useState(!1),[$,I]=w.useState(!1),[X,L]=w.useState(""),[te,ae]=w.useState(!1),[ee,me]=w.useState(null),[le,ue]=w.useState(null),K=w.useRef(null);w.useEffect(()=>{if(C||$){const we=ye=>(ye.preventDefault(),ye.returnValue="A backup operation is in progress. Are you sure you want to leave?",ye.returnValue);return window.addEventListener("beforeunload",we),()=>window.removeEventListener("beforeunload",we)}},[C,$]);const[ne,oe]=w.useState(!1),[be,_e]=w.useState(null),B=w.useRef(null),Y=w.useRef(!1),{data:D,isLoading:j}=et({queryKey:["github-backup-config"],queryFn:pe.getGitHubBackupConfig}),{data:z}=et({queryKey:["github-backup-status"],queryFn:pe.getGitHubBackupStatus,refetchInterval:xe=>xe.state.data?.is_running?500:1e4}),{data:W}=et({queryKey:["github-backup-logs"],queryFn:()=>pe.getGitHubBackupLogs(20)}),{data:q}=et({queryKey:["cloud-status"],queryFn:pe.getCloudStatus}),{data:de}=et({queryKey:["printers"],queryFn:pe.getPrinters}),O=ep({queries:(de??[]).map(xe=>({queryKey:["printerStatus",xe.id],queryFn:()=>pe.getPrinterStatus(xe.id),staleTime:1e4,refetchInterval:3e4}))}),G=(de??[]).map((xe,we)=>({printer:xe,connected:O[we]?.data?.connected??!1})),Q=G.length,V=G.filter(xe=>xe.connected).length,J=Q>0&&V===0,ie=V>0&&V<Q;w.useEffect(()=>{D&&(i(D.repository_url),c(D.branch),u(D.schedule_enabled),p(D.schedule_type),y(D.backup_kprofiles),b(D.backup_cloud_profiles),_(D.backup_settings),P(D.backup_spools),M(D.backup_archives),T(D.enabled),o(""),setTimeout(()=>{Y.current=!0},100))},[D]);const he=w.useCallback(async(xe=!1)=>{if(D?.has_token)try{xe&&s?(await pe.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:A}),o(""),e(n("backup.tokenUpdated"))):(await pe.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:A}),e(n("backup.settingsSaved"))),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(we){e(n("backup.failedToSave",{message:we.message}),"error")}},[D?.has_token,r,s,l,d,m,f,v,g,k,N,A,t,e,n]);w.useEffect(()=>{if(!(!Y.current||!D?.has_token))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{he(!1)},500),()=>{B.current&&clearTimeout(B.current)}},[r,l,d,m,f,v,g,k,N,A,he,D?.has_token]),w.useEffect(()=>{if(!(!Y.current||!D?.has_token||!s))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{he(!0)},1e3),()=>{B.current&&clearTimeout(B.current)}},[s,he,D?.has_token]);const fe=lt({mutationFn:xe=>pe.saveGitHubBackupConfig(xe),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(n("backup.githubBackupEnabled")),o(""),Y.current=!0},onError:xe=>{e(n("backup.failedToSave",{message:xe.message}),"error")}}),se=lt({mutationFn:pe.triggerGitHubBackup,onSuccess:xe=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),xe.success?xe.files_changed>0?e(n("backup.backupCompleteFiles",{count:xe.files_changed})):e(n("backup.backupSkippedNoChanges")):e(n("backup.backupFailed2",{message:xe.message}),"error")},onError:xe=>{e(n("backup.backupFailed2",{message:xe.message}),"error")}}),U=lt({mutationFn:()=>pe.clearGitHubBackupLogs(0),onSuccess:xe=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(n("backup.clearedLogs",{count:xe.deleted}))},onError:xe=>{e(n("backup.failedToClearLogs",{message:xe.message}),"error")}}),R=async()=>{oe(!0),_e(null);try{let xe;if(s){if(!r){e(n("backup.enterRepoUrl"),"error"),oe(!1);return}xe=await pe.testGitHubConnection(r,s)}else if(D?.has_token)xe=await pe.testGitHubStoredConnection();else{e(n("backup.enterRepoAndToken"),"error"),oe(!1);return}_e({success:xe.success,message:xe.message})}catch(xe){_e({success:!1,message:xe.message})}finally{oe(!1)}},re=()=>{if(!r){e(n("backup.repoRequired"),"error");return}if(!s){e(n("backup.tokenRequired"),"error");return}fe.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:A})};return j?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(I3,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.githubBackup")})]}),D&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.enabled")}),a.jsx(Vn,{checked:A,onChange:T})]})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.githubDescription")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.repositoryUrl")}),a.jsx("input",{type:"text",value:r,onChange:xe=>{i(xe.target.value),_e(null)},placeholder:"https://github.com/username/bambuddy-backup",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("backup.personalAccessToken")," ",D?.has_token&&a.jsx("span",{className:"text-green-400",children:n("backup.tokenSaved")})]}),a.jsx("input",{type:"password",value:s,onChange:xe=>{o(xe.target.value),_e(null)},placeholder:D?.has_token?n("backup.enterNewToken"):"ghp_xxxxxxxxxxxx",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("backup.tokenHint")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.branch")}),a.jsx("input",{type:"text",value:l,onChange:xe=>c(xe.target.value),placeholder:"main",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.autoBackup")}),a.jsxs("select",{value:d?m:"disabled",onChange:xe=>{xe.target.value==="disabled"?u(!1):(u(!0),p(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",children:[a.jsx("option",{value:"disabled",children:n("backup.manualOnly")}),a.jsx("option",{value:"hourly",children:n("backup.hourly")}),a.jsx("option",{value:"daily",children:n("backup.daily")}),a.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:n("backup.includeInBackup")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${J?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:f,onChange:xe=>y(xe.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:J}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${J?"text-bambu-gray":"text-white"}`,children:n("backup.kProfiles")}),J&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.noPrintersConnected")]}),ie&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.printersConnected",{connected:V,total:Q})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.kProfilesDescription")})]})]}),a.jsxs("label",{className:`flex items-start gap-2 ${q?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:xe=>b(xe.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:!q?.is_authenticated}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${q?.is_authenticated?"text-white":"text-bambu-gray"}`,children:n("backup.cloudProfiles")}),!q?.is_authenticated&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.cloudLoginRequiredShort")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.cloudProfilesDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:g,onChange:xe=>_(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.appSettings")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.appSettingsDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k,onChange:xe=>P(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.spoolInventory")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.spoolInventoryDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:N,onChange:xe=>M(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.printArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.printArchivesDescription")})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[z?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:z.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[n("backup.lastBackupAt")," ",Sx(z.last_backup_at,"system",n)]}),a.jsx(ZY,{status:z.last_backup_status})]}):a.jsx("span",{children:n("backup.noBackupsYet")})}),z.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(rr,{className:"w-3 h-3 inline mr-1"}),n("backup.next")," ",Sx(z.next_scheduled_run,"system",n)]})]}),be&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${be.success?"text-green-400":"text-red-400"}`,children:[be.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx($a,{className:"w-4 h-4"}),be.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:z?.configured?a.jsx(a.Fragment,{children:se.isPending||z.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:z.progress||n("backup.startingBackup")})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>se.mutate(),disabled:!D?.enabled,children:[a.jsx(Ds,{className:"w-4 h-4"}),n("backup.backupNow")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:R,disabled:ne,children:[ne?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),n("backup.test")]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"primary",size:"sm",onClick:re,disabled:fe.isPending||!r||!s,children:[fe.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(fr,{className:"w-4 h-4"}),n("backup.enableBackup")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:R,disabled:ne||!r||!s,children:[ne?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),n("backup.testConnection")]})]})})]})]})]}),W&&W.length>0&&a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(L0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.history")})]}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[a.jsx(un,{className:"w-4 h-4"}),n("backup.clear")]})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.date")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.status")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.commit")})]})}),a.jsx("tbody",{children:W.slice(0,10).map(xe=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:Ttt(xe.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(ZY,{status:xe.status})}),a.jsx("td",{className:"py-2 px-2",children:xe.commit_sha?a.jsxs("a",{href:`${D?.repository_url}/commit/${xe.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[xe.commit_sha.substring(0,7),a.jsx(sa,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},xe.id))})]})})})]})]}),a.jsx("div",{className:"space-y-6",children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.localBackup")})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.localBackupDescription")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.downloadBackupLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.completeBackupZip")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",disabled:C||$,onClick:async()=>{F(!0),L(n("backup.preparingBackup"));try{L(n("backup.creatingArchive"));const{blob:xe,filename:we}=await pe.exportBackup();L(n("backup.downloadingFile"));const ye=URL.createObjectURL(xe),Ae=document.createElement("a");Ae.href=ye,Ae.download=we,Ae.click(),URL.revokeObjectURL(ye),e(n("backup.backupDownloaded"))}catch(xe){e(n("backup.failedToCreateBackup",{message:xe instanceof Error?xe.message:"Unknown error"}),"error")}finally{F(!1),L("")}},children:[a.jsx(va,{className:"w-4 h-4"}),n("backup.download")]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:K,type:"file",accept:".zip",className:"hidden",onChange:xe=>{const we=xe.target.files?.[0];we&&(me(we),ae(!0)),xe.target.value=""}}),a.jsxs(Ie,{variant:"secondary",size:"sm",disabled:$||C,onClick:()=>K.current?.click(),children:[a.jsx(Ca,{className:"w-4 h-4"}),n("backup.restore")]})]}),le&&a.jsx("div",{className:`p-3 rounded-lg ${le.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[le.success?a.jsx(fr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx($a,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:le.success?"text-green-200":"text-red-200",children:[le.message,le.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Ie,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(jo,{className:"w-3 h-3"}),n("backup.reloadNow")]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:n("backup.restoreReplacesAll")})," ",a.jsx("span",{className:"text-yellow-200/70",children:n("backup.restoreReplacesAllDetail")})]})]})})]})]})}),te&&ee&&a.jsx(kn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:ee.name}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{ae(!1),I(!0),ue(null);try{L(n("backup.uploadingFile"));const xe=await pe.importBackup(ee);ue(xe),xe.success?e(n("backup.backupRestoredRestart"),"success"):e(xe.message,"error")}catch(xe){const we=xe instanceof Error?xe.message:n("backup.failedToRestore");ue({success:!1,message:we}),e(we,"error")}finally{I(!1),L(""),me(null)}},onCancel:()=>{ae(!1),me(null)}}),(C||$)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:n(C?"backup.creatingBackup":"backup.restoringBackup")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:X||n(C?"backup.preparing":"backup.processing")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:n("backup.doNotClosePage")})]})})]})})]})}const Mtt={starttls:587,ssl:465,none:25},jtt={587:"starttls",465:"ssl",25:"none"};function Ett(){const{t}=Lt(),{showToast:e}=xn(),n=mn(),[r,i]=w.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=w.useState(""),{data:l,isLoading:c}=et({queryKey:["smtpSettings"],queryFn:()=>pe.getSMTPSettings()}),{authEnabled:d}=_r(),{data:u}=et({queryKey:["advancedAuthStatus"],queryFn:()=>pe.getAdvancedAuthStatus()});w.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=A=>{i({...r,smtp_security:A,smtp_port:Mtt[A]})},p=A=>{const T=jtt[A];i({...r,smtp_port:A,...T?{smtp_security:T}:{}})},f=A=>{i({...r,smtp_auth_enabled:A,...A?{}:{smtp_username:"",smtp_password:""}})},y=lt({mutationFn:A=>pe.saveSMTPSettings(A),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:A=>{e(A.message,"error")}}),v=lt({mutationFn:A=>pe.testSMTP(A),onSuccess:A=>{e(A.message,A.success?"success":"error")},onError:A=>{e(A.message,"error")}}),b=lt({mutationFn:A=>A?pe.enableAdvancedAuth():pe.disableAdvancedAuth(),onSuccess:A=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(A.message,"success")},onError:A=>{e(A.message,"error")}}),g=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}y.mutate(r)},_=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}v.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 a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});const P=u?.advanced_auth_enabled??!1,N="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",M="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(vx,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Ie,{onClick:k,disabled:b.isPending,variant:P?"danger":"primary",children:P?a.jsxs(a.Fragment,{children:[a.jsx(s0,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(ld,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"space-y-3",children:P?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(fr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Ln,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsx("div",{className:"lg:col-span-2",children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:A=>f(A.target.value==="true"),className:N,children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),a.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${r.smtp_auth_enabled?"":"opacity-40 pointer-events-none"}`,children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:A=>i({...r,smtp_username:A.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:M})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:A=>i({...r,smtp_password:A.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:M})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:A=>i({...r,smtp_host:A.target.value}),placeholder:"smtp.gmail.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:A=>p(parseInt(A.target.value)||587),placeholder:"587",className:N})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:A=>m(A.target.value),className:N,children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:A=>i({...r,smtp_from_email:A.target.value}),placeholder:"your@email.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:A=>i({...r,smtp_from_name:A.target.value}),placeholder:"BamBuddy",className:N})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Ie,{onClick:g,disabled:y.isPending,className:"flex-1",children:y.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),a.jsx("div",{children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:A=>o(A.target.value),placeholder:"test@example.com",className:N})]}),a.jsx(Ie,{onClick:_,disabled:v.isPending,variant:"secondary",children:v.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Lw,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const Dtt={starttls:"389",ldaps:"636"};function Ftt(){const{t}=Lt(),{showToast:e}=xn(),n=mn(),{authEnabled:r}=_r(),[i,s]=w.useState({ldap_server_url:"",ldap_bind_dn:"",ldap_bind_password:"",ldap_search_base:"",ldap_user_filter:"(sAMAccountName={username})",ldap_security:"starttls",ldap_group_mapping:"",ldap_auto_provision:!1,ldap_default_group:""}),{data:o,isLoading:l}=et({queryKey:["settings"],queryFn:()=>pe.getSettings()}),{data:c}=et({queryKey:["ldapStatus"],queryFn:()=>pe.getLDAPStatus()}),{data:d=[]}=et({queryKey:["groups"],queryFn:()=>pe.getGroups()});w.useEffect(()=>{o&&s({ldap_server_url:o.ldap_server_url||"",ldap_bind_dn:o.ldap_bind_dn||"",ldap_bind_password:"",ldap_search_base:o.ldap_search_base||"",ldap_user_filter:o.ldap_user_filter||"(sAMAccountName={username})",ldap_security:o.ldap_security||"starttls",ldap_group_mapping:o.ldap_group_mapping||"",ldap_auto_provision:o.ldap_auto_provision??!1,ldap_default_group:o.ldap_default_group||""})},[o]);const u=lt({mutationFn:g=>pe.updateSettings(g),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(t("settings.ldap.settingsSaved")||"LDAP settings saved","success")},onError:g=>{e(g.message,"error")}}),m=lt({mutationFn:g=>pe.updateSettings({ldap_enabled:g}),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:g=>{e(g.message,"error")}}),p=lt({mutationFn:()=>pe.testLDAP(),onSuccess:g=>{e(g.message,g.success?"success":"error")},onError:g=>{e(g.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 g={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&&(g.ldap_bind_password=i.ldap_bind_password),u.mutate(g)},y=()=>{if(!r){e(t("settings.ldap.errors.enableAuthFirst")||"Enable authentication first","error");return}if(!c?.ldap_enabled&&!c?.ldap_configured){e(t("settings.ldap.errors.configureLdapFirst")||"Save LDAP settings first","error");return}m.mutate(!c?.ldap_enabled)};if(l)return a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});const v=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 a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wb,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.title")||"LDAP Authentication"})]}),a.jsx(Ie,{onClick:y,disabled:m.isPending,variant:v?"danger":"primary",children:v?a.jsxs(a.Fragment,{children:[a.jsx(s0,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(ld,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),a.jsx(Rt,{children:v?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(fr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.enabledDesc")||"LDAP authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.ldap.feature1")||"Users can login with LDAP credentials"}),a.jsx("li",{children:t("settings.ldap.feature2")||"Local admin account remains as fallback"}),a.jsx("li",{children:t("settings.ldap.feature3")||"LDAP groups are mapped to BamBuddy groups on login"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Ln,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.disabledDesc")||"LDAP authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300 mt-1",children:t("settings.ldap.disabledHint")||"Configure and save LDAP settings below, then enable."})]})]})})})]}),a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[a.jsxs("div",{className:"md:col-span-2",children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.serverUrl")||"Server URL"}),a.jsx("input",{type:"text",className:b,placeholder:"ldaps://ldap.example.com:636",value:i.ldap_server_url,onChange:g=>s({...i,ldap_server_url:g.target.value})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.serverUrlHint")||"Use ldaps:// for SSL or ldap:// with StartTLS"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.security")||"Security"}),a.jsx("div",{className:"flex gap-2",children:["starttls","ldaps"].map(g=>a.jsx("button",{onClick:()=>s({...i,ldap_security:g}),className:`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${i.ldap_security===g?"bg-bambu-green text-black":"bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:g==="starttls"?"StartTLS":"LDAPS"},g))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.securityHint")||`Default port: ${Dtt[i.ldap_security]}`})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindDn")||"Bind DN (Service Account)"}),a.jsx("input",{type:"text",className:b,placeholder:"cn=service-account,ou=service,dc=example,dc=com",value:i.ldap_bind_dn,onChange:g=>s({...i,ldap_bind_dn:g.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindPassword")||"Bind Password"}),a.jsx("input",{type:"password",className:b,placeholder:o?.ldap_bind_dn?"••••••••":"",value:i.ldap_bind_password,onChange:g=>s({...i,ldap_bind_password:g.target.value})})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.searchBase")||"Search Base DN"}),a.jsx("input",{type:"text",className:b,placeholder:"ou=users,dc=example,dc=com",value:i.ldap_search_base,onChange:g=>s({...i,ldap_search_base:g.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.userFilter")||"User Search Filter"}),a.jsx("input",{type:"text",className:b,placeholder:"(sAMAccountName={username})",value:i.ldap_user_filter,onChange:g=>s({...i,ldap_user_filter:g.target.value})})]})]}),a.jsx(lle,{summary:a.jsx("span",{className:"text-sm font-medium text-bambu-gray",children:t("settings.ldap.advanced")||"Advanced"}),className:"border-t border-bambu-dark-tertiary pt-3",summaryClassName:"py-1",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white",children:t("settings.ldap.autoProvision")||"Auto-provision users"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:t("settings.ldap.autoProvisionHint")||"Automatically create a BamBuddy account on first LDAP login"})]}),a.jsx("button",{onClick:()=>s({...i,ldap_auto_provision:!i.ldap_auto_provision}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${i.ldap_auto_provision?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.ldap_auto_provision?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.defaultGroup")||"Default group"}),a.jsxs("select",{className:b,value:i.ldap_default_group,onChange:g=>s({...i,ldap_default_group:g.target.value}),children:[a.jsx("option",{value:"",children:t("settings.ldap.defaultGroupNone")||"— None (reject login) —"}),d.map(g=>a.jsx("option",{value:g.name,children:g.name},g.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.defaultGroupHint")||"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped group. Leave empty to leave unmapped users without permissions."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.groupMapping")||"Group Mapping (JSON)"}),a.jsx("textarea",{className:`${b} font-mono text-sm`,rows:4,placeholder:`{
  8331. "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",
  8332. "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"
  8333. }`,value:i.ldap_group_mapping,onChange:g=>s({...i,ldap_group_mapping:g.target.value})}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[t("settings.ldap.groupMappingHint")||"Map LDAP group DNs to BamBuddy groups. Available groups: ",d.map(g=>g.name).join(", ")]})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsxs(Ie,{onClick:f,disabled:u.isPending,children:[u.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(fr,{className:"w-4 h-4"}),t("common.save")||"Save"]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),t("settings.ldap.testConnection")||"Test Connection"]})]})]})})]})]})}const Rtt={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 Ltt(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function n0(t,e,n=0){if(n>5)return"...";if(e.$ref)return n0(t,Ltt(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const s=n0(t,i,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[n0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,s]of Object.entries(e.properties))r[i]=n0(t,s,n+1);return r}return{};default:return null}}function Ott({path:t,method:e,spec:n,schema:r,apiKey:i}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,y]=w.useState(!1),[v,b]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const T={};for(const C of n.parameters)C.schema?.default!==void 0&&(T[C.name]=String(C.schema.default));c(C=>({...T,...C}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!d){const T=n.requestBody.content["application/json"].schema,C=n0(r,T);u(JSON.stringify(C,null,2))}},[s,n.requestBody,r,d]);const _=(()=>{const T=[];for(const C of n.parameters||[])if(C.in==="path"||C.required){const F=l[C.name];(F===void 0||F==="")&&T.push(C.name)}return T})(),k=async()=>{if(_.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${_.join(", ")}`,duration:0});return}y(!0),p(null);try{let T=t;const C=new URLSearchParams;for(const ue of n.parameters||[]){const K=l[ue.name];K!==void 0&&K!==""&&(ue.in==="path"?T=T.replace(`{${ue.name}}`,encodeURIComponent(K)):ue.in==="query"&&C.append(ue.name,K))}const F=C.toString(),$=`${T}${F?`?${F}`:""}`,I={"Content-Type":"application/json"};i&&(I["X-API-Key"]=i);const X={method:e.toUpperCase(),headers:I};["post","put","patch"].includes(e)&&d&&(X.body=d);const L=performance.now(),te=await fetch($,X),ae=Math.round(performance.now()-L),ee={};te.headers.forEach((ue,K)=>{ee[K]=ue});let me;te.headers.get("content-type")?.includes("application/json")?me=await te.json():me=await te.text(),p({status:te.status,statusText:te.statusText,headers:ee,body:me,duration:ae})}catch(T){p({status:0,statusText:"Network Error",headers:{},body:T instanceof Error?T.message:"Unknown error",duration:0})}finally{y(!1)}},P=async()=>{if(m){const T=typeof m.body=="string"?m.body:JSON.stringify(m.body,null,2);try{await navigator.clipboard.writeText(T),b(!0),setTimeout(()=>b(!1),2e3)}catch{const C=document.createElement("textarea");C.value=T,C.style.position="fixed",C.style.left="-999999px",document.body.appendChild(C),C.select(),document.execCommand("copy"),document.body.removeChild(C),b(!0),setTimeout(()=>b(!1),2e3)}}},N=(n.parameters||[]).filter(T=>T.in==="path"),M=(n.parameters||[]).filter(T=>T.in==="query"),A=["post","put","patch"].includes(e)&&n.requestBody;return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):a.jsx(Va,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${Rtt[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),a.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&a.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),N.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),a.jsx("div",{className:"space-y-2",children:N.map(T=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[T.name,T.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),a.jsx("input",{type:"text",value:l[T.name]||"",onChange:C=>c(F=>({...F,[T.name]:C.target.value})),placeholder:T.description||T.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"})]},T.name))})]}),M.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),a.jsx("div",{className:"space-y-2",children:M.map(T=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[T.name,T.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),T.schema?.enum?a.jsxs("select",{value:l[T.name]||"",onChange:C=>c(F=>({...F,[T.name]:C.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"-- Select --"}),T.schema.enum.map(C=>a.jsx("option",{value:C,children:C},C))]}):a.jsx("input",{type:"text",value:l[T.name]||"",onChange:C=>c(F=>({...F,[T.name]:C.target.value})),placeholder:T.description||T.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"})]},T.name))})]}),A&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),a.jsx("textarea",{value:d,onChange:T=>u(T.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ie,{onClick:k,disabled:f,children:[f?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ds,{className:"w-4 h-4"}),"Execute"]}),_.length>0&&a.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),"Fill in: ",_.join(", ")]})]}),m&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",a.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${m.status>=200&&m.status<300?"bg-green-500/20 text-green-400":m.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[m.status," ",m.statusText]}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[m.duration,"ms"]})]}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:P,children:v?a.jsx(fr,{className:"w-3 h-3 text-green-400"}):a.jsx(Mo,{className:"w-3 h-3"})})]}),a.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof m.body=="string"?m.body:JSON.stringify(m.body,null,2)})]})]})]})}function Itt({apiKey:t=""}){const[e,n]=w.useState(null),[r,i]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[d,u]=w.useState("");if(w.useEffect(()=>{async function b(){try{const g=await fetch("/openapi.json");if(!g.ok)throw new Error("Failed to fetch OpenAPI schema");const _=await g.json();n(_)}catch(g){o(g instanceof Error?g.message:"Unknown error")}finally{i(!1)}}b()},[]),r)return a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-red-400",children:[a.jsx(qa,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{children:"Failed to load API schema"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const m={};for(const[b,g]of Object.entries(e.paths))for(const[_,k]of Object.entries(g)){if(_==="parameters")continue;const P=k.tags||["Other"];for(const N of P)m[N]||(m[N]=[]),m[N].push({path:b,method:_,spec:k})}const p=Object.entries(m).map(([b,g])=>{if(!d)return{tag:b,endpoints:g};const _=g.filter(({path:k,method:P,spec:N})=>{const M=d.toLowerCase();return k.toLowerCase().includes(M)||P.toLowerCase().includes(M)||(N.summary?.toLowerCase()||"").includes(M)||(N.description?.toLowerCase()||"").includes(M)});return{tag:b,endpoints:_}}).filter(({endpoints:b})=>b.length>0).sort((b,g)=>b.tag.localeCompare(g.tag)),f=b=>{c(g=>{const _=new Set(g);return _.has(b)?_.delete(b):_.add(b),_})},y=()=>{c(new Set(p.map(b=>b.tag)))},v=()=>{c(new Set)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("div",{className:"flex-1",children:a.jsx("input",{type:"text",value:d,onChange: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"})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:y,children:"Expand All"}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),a.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[a.jsx(sa,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((b,g)=>b+g.endpoints.length,0)," endpoints in ",p.length," categories"]}),a.jsx("div",{className:"space-y-3",children:p.map(({tag:b,endpoints:g})=>a.jsxs(Dt,{children:[a.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:a.jsxs("div",{className:"flex items-center gap-2",children:[l.has(b)?a.jsx(Fn,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(Va,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:b.replace(/-/g," ")}),a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:g.length})]})}),l.has(b)&&a.jsx(Rt,{className:"pt-0 space-y-2",children:g.map(({path:_,method:k,spec:P})=>a.jsx(Ott,{path:_,method:k,spec:P,schema:e,apiKey:t},`${k}-${_}`))})]},b))})]})}const ztt=["general","plugs","notifications","queue","filament","network","apikeys","virtual-printer","users","backup"],Utt={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"},JY=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],eX=(t,e)=>Utt[t]||JY[e%JY.length];function Btt(){const t=mn(),e=Eo(),[n,r]=eO(),{t:i,i18n:s}=Lt(),{showToast:o}=xn(),{authEnabled:l,user:c,refreshAuth:d,hasPermission:u}=_r(),{mode:m,darkStyle:p,darkBackground:f,darkAccent:y,lightStyle:v,lightBackground:b,lightAccent:g,setDarkStyle:_,setDarkBackground:k,setDarkAccent:P,setLightStyle:N,setLightBackground:M,setLightAccent:A}=cg(),[T,C]=w.useState(null),[F,$]=w.useState(!1),[I,X]=w.useState(null),[L,te]=w.useState(!1),[ae,ee]=w.useState(null),[me,le]=w.useState(null),[ue,K]=w.useState(""),[ne,oe]=w.useState(""),[be,_e]=w.useState(!1),[B,Y]=w.useState(FQ()),D=n.get("tab"),j=D==="email",z=j?"users":D&&ztt.includes(D)?D:"general",[W,q]=w.useState(z),[de,O]=w.useState(j?"email":"users"),G=ge=>{q(ge),ge==="users"&&O("users"),ge==="general"?n.delete("tab"):n.set("tab",ge),r(n,{replace:!0})},[Q,V]=w.useState(!1),[J,ie]=w.useState(""),[he,fe]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[se,U]=w.useState(null),[R,re]=w.useState(null),[xe,we]=w.useState(""),[ye,Ae]=w.useState(!1),[ve,Te]=w.useState(!1),[Fe,Ee]=w.useState(null),[Se,je]=w.useState(!1),[qe,Re]=w.useState(!1),[Ye,ce]=w.useState(!1),[ze,Ne]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[Ge,$e]=w.useState(!1),[Pe,Me]=w.useState(!1),[Ve,tt]=w.useState(!1),[ut,xt]=w.useState(!1),[wt,Ht]=w.useState(null),[Xt,Kt]=w.useState(null),[Ut,en]=w.useState(null),[Ke,Ft]=w.useState(!1),[Nt,ht]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Mt,Qt]=w.useState(null),[Wt,Ue]=w.useState(null),[dt,pt]=w.useState(!1),[De,Le]=w.useState({}),[at,Ce]=w.useState({}),We=ge=>{Y(ge),eye(ge),o(i("settings.toast.settingsSaved"),"success")},Xe=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},Qe=!!T?.default_sidebar_order,Ze=async ge=>{try{if(ge){let mt;const Je=localStorage.getItem("sidebarOrder");try{mt=Je?JSON.parse(Je):Pu.map(tn=>tn.id)}catch{mt=Pu.map(tn=>tn.id)}(!Array.isArray(mt)||mt.length===0)&&(mt=Pu.map(tn=>tn.id));const $t=JSON.stringify({order:mt});await pe.updateSettings({default_sidebar_order:$t}),C(tn=>tn&&{...tn,default_sidebar_order:$t}),o(i("settings.sidebarDefaultSet"),"success")}else await pe.updateSettings({default_sidebar_order:""}),C(mt=>mt&&{...mt,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:rt,isLoading:bt}=et({queryKey:["settings"],queryFn:pe.getSettings}),{data:Pt,isLoading:vt,isFetching:He}=et({queryKey:["storage-usage"],queryFn:()=>pe.getStorageUsage(),enabled:W==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),St=async()=>{Me(!0);try{const ge=await pe.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],ge)}catch(ge){const mt=ge instanceof Error?ge.message:"Failed to refresh storage usage";o(mt,"error")}finally{Me(!1)}},{data:Ct,isLoading:Zt}=et({queryKey:["smart-plugs"],queryFn:pe.getSmartPlugs}),{data:Jt,isLoading:Nn}=et({queryKey:["smart-plugs-energy",Ct?.map(ge=>ge.id)],queryFn:async()=>{if(!Ct||Ct.length===0)return null;const ge=await Promise.all(Ct.filter(gr=>gr.enabled).map(async gr=>{try{const Kn=await pe.getSmartPlugStatus(gr.id);return{plug:gr,status:Kn}}catch{return{plug:gr,status:null}}}));let mt=0,Je=0,$t=0,tn=0,fn=0;for(const{plug:gr,status:Kn}of ge){const sn=gr.plug_type==="mqtt"&&Kn?.energy?.power!=null;(Kn?.reachable||sn)&&Kn?.energy&&(fn++,Kn.energy?.power!=null&&(mt+=Kn.energy.power),Kn.energy?.today!=null&&(Je+=Kn.energy.today),Kn.energy?.yesterday!=null&&($t+=Kn.energy.yesterday),Kn.energy?.total!=null&&(tn+=Kn.energy.total))}return{totalPower:mt,totalToday:Je,totalYesterday:$t,totalLifetime:tn,reachableCount:fn,totalPlugs:Ct.filter(gr=>gr.enabled).length}},enabled:W==="plugs"&&!!Ct&&Ct.length>0,refetchInterval:W==="plugs"?1e4:!1}),{data:vn,isLoading:yn}=et({queryKey:["notification-providers"],queryFn:pe.getNotificationProviders}),{data:an,isLoading:rn}=et({queryKey:["api-keys"],queryFn:pe.getAPIKeys}),bn=lt({mutationFn:ge=>pe.createAPIKey(ge),onSuccess:ge=>{U(ge.key||null),V(!1),ie(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:ge=>{o(`Failed to create API key: ${ge.message}`,"error")}}),Gn=lt({mutationFn:ge=>pe.deleteAPIKey(ge),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyDeleted"))},onError:ge=>{o(`Failed to delete API key: ${ge.message}`,"error")}}),{data:ar}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:On,isLoading:mi}=et({queryKey:["notification-templates"],queryFn:pe.getNotificationTemplates}),{data:Rn}=et({queryKey:["virtual-printer-settings"],queryFn:jxe.getSettings,refetchInterval:1e4}),na=Rn?.status?.running??!1,{data:ra}=et({queryKey:["ffmpeg-status"],queryFn:pe.checkFfmpeg}),{data:jr}=et({queryKey:["version"],queryFn:pe.getVersion}),{data:In,refetch:Bi,isRefetching:Hi}=et({queryKey:["updateCheck"],queryFn:pe.checkForUpdates,enabled:rt?.check_updates!==!1,staleTime:300*1e3}),{data:Ci,refetch:Hc}=et({queryKey:["updateStatus"],queryFn:pe.getUpdateStatus,refetchInterval:ge=>{const mt=ge.state.data;return mt?.status==="downloading"||mt?.status==="installing"?1e3:!1}}),{data:pa}=et({queryKey:["mqtt-status"],queryFn:pe.getMQTTStatus,refetchInterval:W==="network"?5e3:!1}),{data:jt}=et({queryKey:["github-backup-status"],queryFn:pe.getGitHubBackupStatus}),{data:Wn}=et({queryKey:["cloud-status"],queryFn:pe.getCloudStatus}),{data:En={advanced_auth_enabled:!1,smtp_configured:!1}}=et({queryKey:["advancedAuthStatus"],queryFn:()=>pe.getAdvancedAuthStatus()}),{data:Vt}=et({queryKey:["ldapStatus"],queryFn:()=>pe.getLDAPStatus()}),{data:sc=[],isLoading:mm}=et({queryKey:["users"],queryFn:()=>pe.getUsers(),enabled:l&&u("users:read")}),{data:hs=[],isLoading:qc}=et({queryKey:["groups"],queryFn:()=>pe.getGroups(),enabled:l&&u("groups:read")}),Lo=lt({mutationFn:ge=>pe.createUser(ge),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),tt(!1),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:ge=>{o(ge.message,"error")}}),$c=lt({mutationFn:({id:ge,data:mt})=>pe.updateUser(ge,mt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),xt(!1),Ht(null),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:ge=>{o(ge.message,"error")}}),Is=lt({mutationFn:({id:ge,deleteItems:mt})=>pe.deleteUser(ge,mt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),Kt(null),en(null)},onError:ge=>{o(ge.message,"error")}}),ps=lt({mutationFn:ge=>pe.resetUserPassword({user_id:ge}),onSuccess:ge=>{o(ge.message,"success")},onError:ge=>{o(ge.message,"error")}}),qi=async ge=>{Kt(ge),Ft(!0);try{const mt=await pe.getUserItemsCount(ge);en(mt)}catch{en({archives:0,queue_items:0,library_files:0})}finally{Ft(!1)}},Id=lt({mutationFn:ge=>pe.deleteGroup(ge),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:ge=>{o(ge.message,"error")}}),Pi=()=>{const ge=En?.advanced_auth_enabled||!1;if(!Nt.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(ge&&!Nt.email){o("Email is required when advanced authentication is enabled","error");return}if(!ge){if(!Nt.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(Nt.password!==Nt.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Nt.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}Lo.mutate({username:Nt.username,password:ge?void 0:Nt.password,email:Nt.email||void 0,role:Nt.role,group_ids:Nt.group_ids.length>0?Nt.group_ids:void 0})},lo=ge=>{if(Nt.password){if(Nt.password!==Nt.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Nt.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const mt={username:Nt.username||void 0,password:Nt.password||void 0,email:Nt.email||void 0,role:Nt.role,group_ids:Nt.group_ids};mt.password||delete mt.password,$c.mutate({id:ge,data:mt})},hm=ge=>{Ht(ge.id),ht({username:ge.username,password:"",email:ge.email||"",confirmPassword:"",role:ge.role,group_ids:ge.groups?.map(mt=>mt.id)||[]}),xt(!0)},zs=ge=>{ht(mt=>({...mt,group_ids:mt.group_ids.includes(ge)?mt.group_ids.filter(Je=>Je!==ge):[...mt.group_ids,ge]}))},pm=lt({mutationFn:pe.applyUpdate,onSuccess:ge=>{ge.is_docker?o(ge.message,"error"):Hc()}}),[$i,Oo]=w.useState(null),oc=lt({mutationFn:pe.testAllNotificationProviders,onSuccess:ge=>{Oo(ge),t.invalidateQueries({queryKey:["notification-providers"]}),ge.failed===0?o(`All ${ge.tested} providers tested successfully!`,"success"):o(`${ge.success}/${ge.tested} providers succeeded`,ge.failed>0?"error":"success")},onError:ge=>{o(`Failed to test providers: ${ge.message}`,"error")}}),ja=lt({mutationFn:async ge=>{if(!Ct)return{success:0,failed:0};const mt=Ct.filter($t=>$t.enabled),Je=await Promise.all(mt.map(async $t=>{try{return await pe.controlSmartPlug($t.id,ge),{success:!0}}catch{return{success:!1}}}));return{success:Je.filter($t=>$t.success).length,failed:Je.filter($t=>!$t.success).length}},onSuccess:(ge,mt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ge.failed===0?o(`All ${ge.success} plugs turned ${mt}`,"success"):o(`${ge.success} plugs turned ${mt}, ${ge.failed} failed`,"error")},onError:ge=>{o(`Failed: ${ge.message}`,"error")}}),Us=w.useRef(null),fs=w.useRef(null),Io=w.useRef(!1),up=w.useRef(!0);w.useEffect(()=>{if(rt&&!T){const ge={...rt,external_url:rt.external_url||window.location.origin};C(ge),setTimeout(()=>{up.current=!1},100)}},[rt,T]);const zd=lt({mutationFn:pe.updateSettings,onSuccess:ge=>{t.setQueryData(["settings"],ge),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ge=>{o(`Failed to save: ${ge.message}`,"error")},onSettled:()=>{Io.current=!1}}),fm=lt({mutationFn:({id:ge,data:mt})=>pe.updatePrinter(ge,mt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:ge=>{o(`Failed to update printer: ${ge.message}`,"error")}});w.useEffect(()=>{if(!(up.current||!T||!rt||!(rt.auto_archive!==T.auto_archive||rt.save_thumbnails!==T.save_thumbnails||rt.capture_finish_photo!==T.capture_finish_photo||rt.default_filament_cost!==T.default_filament_cost||rt.currency!==T.currency||rt.energy_cost_per_kwh!==T.energy_cost_per_kwh||rt.energy_tracking_mode!==T.energy_tracking_mode||rt.check_updates!==T.check_updates||(rt.check_printer_firmware??!0)!==(T.check_printer_firmware??!0)||(rt.include_beta_updates??!1)!==(T.include_beta_updates??!1)||rt.notification_language!==T.notification_language||(rt.bed_cooled_threshold??35)!==(T.bed_cooled_threshold??35)||rt.ams_humidity_good!==T.ams_humidity_good||rt.ams_humidity_fair!==T.ams_humidity_fair||rt.ams_temp_good!==T.ams_temp_good||rt.ams_temp_fair!==T.ams_temp_fair||rt.ams_history_retention_days!==T.ams_history_retention_days||rt.disable_filament_warnings!==T.disable_filament_warnings||rt.prefer_lowest_filament!==T.prefer_lowest_filament||(rt.queue_drying_enabled??!1)!==(T.queue_drying_enabled??!1)||(rt.queue_drying_block??!1)!==(T.queue_drying_block??!1)||(rt.ambient_drying_enabled??!1)!==(T.ambient_drying_enabled??!1)||(rt.drying_presets??"")!==(T.drying_presets??"")||rt.per_printer_mapping_expanded!==T.per_printer_mapping_expanded||rt.date_format!==T.date_format||rt.time_format!==T.time_format||rt.default_printer_id!==T.default_printer_id||rt.ftp_retry_enabled!==T.ftp_retry_enabled||rt.ftp_retry_count!==T.ftp_retry_count||rt.ftp_retry_delay!==T.ftp_retry_delay||rt.ftp_timeout!==T.ftp_timeout||rt.mqtt_enabled!==T.mqtt_enabled||rt.mqtt_broker!==T.mqtt_broker||rt.mqtt_port!==T.mqtt_port||rt.mqtt_username!==T.mqtt_username||rt.mqtt_password!==T.mqtt_password||rt.mqtt_topic_prefix!==T.mqtt_topic_prefix||rt.mqtt_use_tls!==T.mqtt_use_tls||rt.external_url!==T.external_url||rt.ha_enabled!==T.ha_enabled||rt.ha_url!==T.ha_url||rt.ha_token!==T.ha_token||(rt.library_archive_mode??"ask")!==(T.library_archive_mode??"ask")||Number(rt.library_disk_warning_gb??5)!==Number(T.library_disk_warning_gb??5)||(rt.camera_view_mode??"window")!==(T.camera_view_mode??"window")||(rt.preferred_slicer??"bambu_studio")!==(T.preferred_slicer??"bambu_studio")||rt.prometheus_enabled!==T.prometheus_enabled||rt.prometheus_token!==T.prometheus_token||(rt.user_notifications_enabled??!0)!==(T.user_notifications_enabled??!0)||(rt.default_bed_levelling??!0)!==(T.default_bed_levelling??!0)||(rt.default_flow_cali??!1)!==(T.default_flow_cali??!1)||(rt.default_vibration_cali??!0)!==(T.default_vibration_cali??!0)||(rt.default_layer_inspect??!1)!==(T.default_layer_inspect??!1)||(rt.default_timelapse??!1)!==(T.default_timelapse??!1)||(rt.stagger_group_size??2)!==(T.stagger_group_size??2)||(rt.stagger_interval_minutes??5)!==(T.stagger_interval_minutes??5)||(rt.require_plate_clear??!0)!==(T.require_plate_clear??!0)))&&!Io.current)return Us.current&&clearTimeout(Us.current),Us.current=setTimeout(()=>{if(Io.current)return;Io.current=!0;const mt={auto_archive:T.auto_archive,save_thumbnails:T.save_thumbnails,capture_finish_photo:T.capture_finish_photo,default_filament_cost:T.default_filament_cost,currency:T.currency,energy_cost_per_kwh:T.energy_cost_per_kwh,energy_tracking_mode:T.energy_tracking_mode,check_updates:T.check_updates,check_printer_firmware:T.check_printer_firmware,include_beta_updates:T.include_beta_updates,notification_language:T.notification_language,bed_cooled_threshold:T.bed_cooled_threshold,ams_humidity_good:T.ams_humidity_good,ams_humidity_fair:T.ams_humidity_fair,ams_temp_good:T.ams_temp_good,ams_temp_fair:T.ams_temp_fair,ams_history_retention_days:T.ams_history_retention_days,disable_filament_warnings:T.disable_filament_warnings,prefer_lowest_filament:T.prefer_lowest_filament,queue_drying_enabled:T.queue_drying_enabled,queue_drying_block:T.queue_drying_block,ambient_drying_enabled:T.ambient_drying_enabled,drying_presets:T.drying_presets,per_printer_mapping_expanded:T.per_printer_mapping_expanded,date_format:T.date_format,time_format:T.time_format,default_printer_id:T.default_printer_id,ftp_retry_enabled:T.ftp_retry_enabled,ftp_retry_count:T.ftp_retry_count,ftp_retry_delay:T.ftp_retry_delay,ftp_timeout:T.ftp_timeout,mqtt_enabled:T.mqtt_enabled,mqtt_broker:T.mqtt_broker,mqtt_port:T.mqtt_port,mqtt_username:T.mqtt_username,mqtt_password:T.mqtt_password,mqtt_topic_prefix:T.mqtt_topic_prefix,mqtt_use_tls:T.mqtt_use_tls,external_url:T.external_url,ha_enabled:T.ha_enabled,ha_url:T.ha_url,ha_token:T.ha_token,library_archive_mode:T.library_archive_mode,library_disk_warning_gb:T.library_disk_warning_gb,camera_view_mode:T.camera_view_mode,preferred_slicer:T.preferred_slicer,prometheus_enabled:T.prometheus_enabled,prometheus_token:T.prometheus_token,user_notifications_enabled:T.user_notifications_enabled,default_bed_levelling:T.default_bed_levelling,default_flow_cali:T.default_flow_cali,default_vibration_cali:T.default_vibration_cali,default_layer_inspect:T.default_layer_inspect,default_timelapse:T.default_timelapse,stagger_group_size:T.stagger_group_size,stagger_interval_minutes:T.stagger_interval_minutes,require_plate_clear:T.require_plate_clear};zd.mutate(mt)},500),()=>{Us.current&&clearTimeout(Us.current)}},[T,rt,zd]);const cn=w.useCallback((ge,mt)=>{C(Je=>Je?{...Je,[ge]:mt}:null)},[]),gs=async(ge,mt,Je)=>{if(!mt){o(i("settings.toast.enterCameraUrl"),"error");return}Ce($t=>({...$t,[ge]:!0})),Le($t=>({...$t,[ge]:null}));try{const $t=await pe.testExternalCamera(ge,mt,Je);Le(tn=>({...tn,[ge]:$t})),$t.success?o(i("settings.toast.cameraConnected",{resolution:$t.resolution||""}),"success"):o($t.error||i("settings.toast.connectionFailed"),"error")}catch($t){const tn=$t instanceof Error?$t.message:i("settings.toast.testFailed");Le(fn=>({...fn,[ge]:{success:!1,error:tn}})),o(tn,"error")}finally{Ce($t=>({...$t,[ge]:!1}))}},[ul,gg]=w.useState({}),mp=w.useRef({}),bg=w.useRef(new Set);w.useEffect(()=>{if(ar){const ge={};ar.forEach(mt=>{mt.external_camera_url&&!bg.current.has(mt.id)&&(ge[mt.id]=mt.external_camera_url,bg.current.add(mt.id))}),Object.keys(ge).length>0&&gg(mt=>({...mt,...ge}))}},[ar]);const Vc=(ge,mt)=>{gg(Je=>({...Je,[ge]:mt})),mp.current[ge]&&clearTimeout(mp.current[ge]),mp.current[ge]=setTimeout(()=>{fm.mutate({id:ge,data:{external_camera_url:mt||null}})},800)},hp=(ge,mt)=>{const Je={};mt.type!==void 0&&(Je.external_camera_type=mt.type||null),mt.enabled!==void 0&&(Je.external_camera_enabled=mt.enabled),mt.rotation!==void 0&&(Je.camera_rotation=mt.rotation),fm.mutate({id:ge,data:Je})};if(bt||!T)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const _y=[{label:i("settings.general"),tab:"general",keywords:"language date time format printer model printers cards",anchor:"card-general"},{label:i("settings.appearance"),tab:"general",keywords:"theme dark light mode colors",anchor:"card-appearance"},{label:i("settings.archiveSettings"),tab:"general",keywords:"archive auto save thumbnails captures",anchor:"card-archive"},{label:i("settings.camera"),tab:"general",keywords:"camera external video stream",anchor:"card-camera"},{label:i("settings.costTracking"),tab:"general",keywords:"currency filament cost energy kwh price",anchor:"card-cost"},{label:i("settings.fileManager"),tab:"general",keywords:"file manager archive mode disk warning storage",anchor:"card-filemanager"},{label:i("settings.updates"),tab:"general",keywords:"updates version firmware beta check",anchor:"card-updates"},{label:i("settings.dataManagement"),tab:"general",keywords:"data reset clear logs notifications preferences",anchor:"card-data"},{label:i("settings.smartPlugs"),tab:"plugs",keywords:"smart plug energy power automation tapo kasa tplink shelly",anchor:"card-plugs"},{label:i("settings.providers"),tab:"notifications",keywords:"telegram discord email notification providers webhook",anchor:"card-providers"},{label:i("settings.messageTemplates"),tab:"notifications",keywords:"message templates notification text edit",anchor:"card-templates"},{label:i("settings.defaultPrintOptions","Default Print Options"),tab:"queue",keywords:"print bed leveling flow calibration vibration first layer timelapse",anchor:"card-print-options"},{label:i("settings.staggeredStart","Staggered Start"),tab:"queue",keywords:"staggered batch delay start queue group",anchor:"card-staggered"},{label:i("settings.plateClear","Plate-Clear Confirmation"),tab:"queue",keywords:"plate clear confirm auto queue",anchor:"card-plate"},{label:i("settings.gcodeInjection","G-code Injection"),tab:"queue",keywords:"gcode injection start end autoprint farmloop swapmod autoclear printflow",anchor:"card-gcode"},{label:i("settings.queueDrying"),tab:"queue",keywords:"drying presets temperature time humidity ams",anchor:"card-drying"},{label:i("settings.filamentChecks"),tab:"filament",keywords:"filament check warning runout remaining",anchor:"card-filamentchecks"},{label:i("settings.printModal"),tab:"filament",keywords:"print modal custom mapping",anchor:"card-printmodal"},{label:i("settings.amsDisplayThresholds"),tab:"filament",keywords:"ams humidity temperature threshold history retention",anchor:"card-amsthresholds"},{label:i("settings.externalUrl"),tab:"network",keywords:"external url reverse proxy public notification link",anchor:"card-externalurl"},{label:i("settings.ftpRetry"),tab:"network",keywords:"ftp retry upload retries backoff",anchor:"card-ftpretry"},{label:i("settings.homeAssistant"),tab:"network",keywords:"home assistant ha hass mqtt integration",anchor:"card-ha"},{label:i("settings.mqttPublishing"),tab:"network",keywords:"mqtt publish broker topic",anchor:"card-mqtt"},{label:i("settings.prometheusMetrics"),tab:"network",keywords:"prometheus metrics grafana monitoring bearer token",anchor:"card-prometheus"},{label:i("settings.createNewApiKey"),tab:"apikeys",keywords:"api key create permission scope",anchor:"card-createapi"},{label:i("settings.webhookEndpoints"),tab:"apikeys",keywords:"webhook endpoint post http",anchor:"card-webhooks"},{label:i("settings.apiBrowser"),tab:"apikeys",keywords:"api browser endpoint documentation test",anchor:"card-apibrowser"},{label:i("settings.tabs.virtualPrinter"),tab:"virtual-printer",keywords:"virtual printer proxy archive slicer bambustudio orcaslicer ip bind",anchor:"card-vp"},{label:i("settings.currentUser"),tab:"users",subTab:"users",keywords:"current user profile password change",anchor:"card-currentuser"},{label:i("settings.users"),tab:"users",subTab:"users",keywords:"users accounts list",anchor:"card-users"},{label:i("settings.groups"),tab:"users",subTab:"users",keywords:"groups roles permissions administrators operators viewers",anchor:"card-groups"},{label:i("settings.email.smtpSettings","SMTP Configuration"),tab:"users",subTab:"email",keywords:"smtp email send server port password auth starttls ssl",anchor:"card-smtp"},{label:i("settings.ldap.title","LDAP Authentication"),tab:"users",subTab:"ldap",keywords:"ldap active directory ad authentication bind dn search base group mapping",anchor:"card-ldap"},{label:i("settings.tabs.backup"),tab:"backup",keywords:"backup github restore download cloud sync profiles archives",anchor:"card-backup"}],gm=ne.trim().toLowerCase(),pp=gm?_y.filter(ge=>ge.label.toLowerCase().includes(gm)||ge.keywords.toLowerCase().includes(gm)).slice(0,8):[],gt=ge=>{G(ge.tab),ge.subTab&&O(ge.subTab),oe(""),setTimeout(()=>{const mt=document.getElementById(ge.anchor);mt&&(mt.scrollIntoView({behavior:"smooth",block:"start"}),mt.classList.add("ring-2","ring-bambu-green"),setTimeout(()=>mt.classList.remove("ring-2","ring-bambu-green"),1500))},50)};return a.jsx(Dxe,{density:"dense",children:a.jsxs("div",{className:"p-4 md:p-6",children:[a.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"flex items-baseline gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),a.jsx("p",{className:"text-sm text-bambu-gray hidden md:block",children:i("settings.configureBambuddy")})]}),a.jsxs("div",{className:"relative sm:w-72",children:[a.jsx(Sr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),a.jsx("input",{type:"text",value:ne,onChange:ge=>oe(ge.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"}),ne&&a.jsx("button",{onClick:()=>oe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear",children:a.jsx(Bt,{className:"w-3.5 h-3.5"})}),pp.length>0&&a.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-30 overflow-hidden",children:pp.map(ge=>a.jsxs("button",{onClick:()=>gt(ge),className:"w-full px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors border-b border-bambu-dark-tertiary last:border-b-0",children:[a.jsx("p",{className:"text-sm text-white",children:ge.label}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i(`settings.tabs.${ge.tab==="virtual-printer"?"virtualPrinter":ge.tab}`),ge.subTab?` › ${i(`settings.tabs.${ge.subTab}`,ge.subTab)}`:""]})]},ge.anchor))}),gm&&pp.length===0&&a.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-30 p-3",children:a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noSearchResults","No matching settings.")})})]})]}),a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("nav",{className:"flex flex-wrap gap-1 border-b border-bambu-dark-tertiary lg:flex-col lg:flex-nowrap lg:gap-0 lg:border-b-0 lg:border-r lg:w-48 lg:flex-shrink-0 lg:self-start lg:sticky lg:top-4",children:[a.jsxs("button",{onClick:()=>G("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 ${W==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ow,{className:"w-4 h-4"}),i("settings.tabs.general")]}),a.jsxs("button",{onClick:()=>G("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 ${W==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(ql,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Ct&&Ct.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ct.length})]}),a.jsxs("button",{onClick:()=>G("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 ${W==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ah,{className:"w-4 h-4"}),i("settings.tabs.notifications"),vn&&vn.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:vn.length})]}),a.jsxs("button",{onClick:()=>G("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 ${W==="queue"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(nN,{className:"w-4 h-4"}),i("settings.tabs.queue","Workflow")]}),a.jsxs("button",{onClick:()=>G("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 ${W==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(ufe,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),a.jsxs("button",{onClick:()=>G("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 ${W==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(vf,{className:"w-4 h-4"}),i("settings.tabs.network"),a.jsx("span",{className:`w-2 h-2 rounded-full ${pa?.enabled?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>G("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 ${W==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(El,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),an&&an.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:an.length})]}),a.jsxs("button",{onClick:()=>G("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 ${W==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Pr,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),a.jsx("span",{className:`w-2 h-2 rounded-full ${na?"bg-green-400":"bg-gray-500"}`})]}),a.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 ${W==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(_u,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>G("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 ${W==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ul,{className:"w-4 h-4"}),i("settings.tabs.backup"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Wn?.is_authenticated&&jt?.configured&&jt?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[W==="general"&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(Dt,{id:"card-general",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(yd,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:s.language,onChange:ge=>{s.changeLanguage(ge.target.value),pe.updateSettings({language:ge.target.value}),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:G8.map(ge=>a.jsxs("option",{value:ge.code,children:[ge.nativeName," (",ge.name,")"]},ge.code))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:B,onChange:ge=>We(ge.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:Pu.map(ge=>a.jsx("option",{value:ge.to,children:i(ge.labelKey)},ge.id))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.dateFormat")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:T.date_format||"system",onChange:ge=>cn("date_format",ge.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"us",children:i("settings.dateFormatUs")}),a.jsx("option",{value:"eu",children:i("settings.dateFormatEu")}),a.jsx("option",{value:"iso",children:i("settings.dateFormatIso")})]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.timeFormat")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:T.time_format||"system",onChange:ge=>cn("time_format",ge.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"12h",children:i("settings.timeFormat12")}),a.jsx("option",{value:"24h",children:i("settings.timeFormat24")})]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultPrinter")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:T.default_printer_id??"",onChange:ge=>cn("default_printer_id",ge.target.value?Number(ge.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),ar?.map(ge=>a.jsx("option",{value:ge.id,children:ge.name},ge.id))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultPrinterDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:T.preferred_slicer??"bambu_studio",onChange:ge=>cn("preferred_slicer",ge.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"bambu_studio",children:i("settings.slicerBambuStudio")}),a.jsx("option",{value:"orcaslicer",children:i("settings.slicerOrcaSlicer")})]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[i("settings.sidebarOrderDescription"),l&&u("settings:update")&&` ${i("settings.sidebarOrderSetDefaultHint")}`]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Xe,children:[a.jsx(jo,{className:"w-4 h-4"}),i("settings.reset")]}),l&&u("settings:update")&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:i("settings.setDefault")}),a.jsx(Vn,{checked:Qe,onChange:Ze,disabled:bt})]})]})]})]})]}),a.jsxs(Dt,{id:"card-appearance",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Dw,{className:"w-5 h-5"}),i("settings.appearance")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${m==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.darkMode"),m==="dark"&&a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),a.jsxs("select",{value:f,onChange:ge=>{k(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),a.jsx("option",{value:"warm",children:i("settings.bgWarm")}),a.jsx("option",{value:"cool",children:i("settings.bgCool")}),a.jsx("option",{value:"oled",children:i("settings.bgOled")}),a.jsx("option",{value:"slate",children:i("settings.bgSlate")}),a.jsx("option",{value:"forest",children:i("settings.bgForest")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),a.jsxs("select",{value:y,onChange:ge=>{P(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:i("settings.accentGreen")}),a.jsx("option",{value:"teal",children:i("settings.accentTeal")}),a.jsx("option",{value:"blue",children:i("settings.accentBlue")}),a.jsx("option",{value:"orange",children:i("settings.accentOrange")}),a.jsx("option",{value:"purple",children:i("settings.accentPurple")}),a.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),a.jsxs("select",{value:p,onChange:ge=>{_(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:i("settings.styleClassic")}),a.jsx("option",{value:"glow",children:i("settings.styleGlow")}),a.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${m==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.lightMode"),m==="light"&&a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),a.jsxs("select",{value:b,onChange:ge=>{M(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),a.jsx("option",{value:"warm",children:i("settings.bgWarm")}),a.jsx("option",{value:"cool",children:i("settings.bgCool")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),a.jsxs("select",{value:g,onChange:ge=>{A(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:i("settings.accentGreen")}),a.jsx("option",{value:"teal",children:i("settings.accentTeal")}),a.jsx("option",{value:"blue",children:i("settings.accentBlue")}),a.jsx("option",{value:"orange",children:i("settings.accentOrange")}),a.jsx("option",{value:"purple",children:i("settings.accentPurple")}),a.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),a.jsxs("select",{value:v,onChange:ge=>{N(ge.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:i("settings.styleClassic")}),a.jsx("option",{value:"glow",children:i("settings.styleGlow")}),a.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.themeToggleHint")})]})]}),a.jsxs(Dt,{id:"card-archive",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.autoArchivePrints")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoArchiveDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.auto_archive,onChange:ge=>cn("auto_archive",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.saveThumbnailsDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.save_thumbnails,onChange:ge=>cn("save_thumbnails",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.captureFinishPhotoDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.capture_finish_photo,onChange:ge=>cn("capture_finish_photo",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),T.capture_finish_photo&&ra&&!ra.installed&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(Ln,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-yellow-500 font-medium",children:i("settings.ffmpegNotInstalled")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:i("settings.ffmpegRequired")})]})]})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-md",children:[a.jsxs(Dt,{id:"card-camera",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gO,{className:"w-5 h-5 text-bambu-green"}),i("settings.camera")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.cameraViewMode")}),a.jsxs("select",{value:T.camera_view_mode??"window",onChange:ge=>cn("camera_view_mode",ge.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"window",children:i("settings.newWindow")}),a.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:T.camera_view_mode==="embedded"?i("settings.cameraOverlayDescription"):i("settings.cameraWindowDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:i("settings.externalCamerasDescription")}),ar&&ar.length>0?a.jsx("div",{className:"space-y-3",children:ar.map(ge=>a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-white font-medium text-sm",children:ge.name}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ge.external_camera_enabled,onChange:mt=>hp(ge.id,{enabled:mt.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ge.external_camera_enabled&&a.jsxs("div",{className:"space-y-2 mt-2",children:[a.jsx("input",{type:"text",placeholder:ge.external_camera_type==="usb"?i("settings.cameraPlaceholderUsb"):i("settings.cameraPlaceholderUrl"),value:ul[ge.id]??ge.external_camera_url??"",onChange:mt=>Vc(ge.id,mt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:ge.external_camera_type||"mjpeg",onChange:mt=>hp(ge.id,{type:mt.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"mjpeg",children:i("settings.cameraTypeMjpeg")}),a.jsx("option",{value:"rtsp",children:i("settings.cameraTypeRtsp")}),a.jsx("option",{value:"snapshot",children:i("settings.cameraTypeSnapshot")}),a.jsx("option",{value:"usb",children:i("settings.cameraTypeUsb")})]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>gs(ge.id,ul[ge.id]??ge.external_camera_url??"",ge.external_camera_type||"mjpeg"),disabled:at[ge.id]||!(ul[ge.id]??ge.external_camera_url),children:at[ge.id]?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("settings.test")})]}),De[ge.id]&&a.jsx("div",{className:`text-xs flex items-center gap-1 ${De[ge.id]?.success?"text-green-500":"text-red-500"}`,children:De[ge.id]?.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-3 h-3"}),i("settings.connected"),De[ge.id]?.resolution&&` (${De[ge.id]?.resolution})`]}):a.jsxs(a.Fragment,{children:[a.jsx($a,{className:"w-3 h-3"}),De[ge.id]?.error||i("settings.toast.connectionFailed")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:i("settings.cameraRotation")}),a.jsxs("select",{value:ge.camera_rotation||0,onChange:mt=>hp(ge.id,{rotation:parseInt(mt.target.value)}),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:0,children:"0°"}),a.jsx("option",{value:90,children:"90°"}),a.jsx("option",{value:180,children:"180°"}),a.jsx("option",{value:270,children:"270°"})]})]})]})]},ge.id))}):a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),a.jsxs(Dt,{id:"card-cost",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.currency")}),a.jsx("select",{value:T.currency,onChange:ge=>cn("currency",ge.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:MVe.map(ge=>a.jsx("option",{value:ge.code,children:ge.label},ge.code))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultFilamentCost")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:yo(T.currency)}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:T.default_filament_cost,onChange:ge=>cn("default_filament_cost",parseFloat(ge.target.value)||0),style:{paddingLeft:`${Math.max(2,yo(T.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.electricityCost")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:yo(T.currency)}),a.jsx("input",{type:"number",step:"0.001",min:"0",value:T.energy_cost_per_kwh,onChange:ge=>cn("energy_cost_per_kwh",parseFloat(ge.target.value)||0),style:{paddingLeft:`${Math.max(2,yo(T.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.energyDisplayMode")}),a.jsxs("select",{value:T.energy_tracking_mode||"total",onChange:ge=>cn("energy_tracking_mode",ge.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"print",children:i("settings.printsOnly")}),a.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:T.energy_tracking_mode==="print"?i("settings.energyModePrintDescription"):i("settings.energyModeTotalDescription")})]})]})]}),a.jsxs(Dt,{id:"card-filemanager",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),i("settings.fileManager")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.createArchiveEntry")}),a.jsxs("select",{value:T.library_archive_mode??"ask",onChange:ge=>cn("library_archive_mode",ge.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),a.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),a.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.createArchiveEntryDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.lowDiskSpaceWarning")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:T.library_disk_warning_gb??5,onChange:ge=>cn("library_disk_warning_gb",parseFloat(ge.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.lowDiskSpaceDescription")})]})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-sm",children:[a.jsx(ktt,{}),a.jsxs(Dt,{id:"card-updates",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.updates")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider",children:i("settings.printerFirmware")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.checkFirmwareDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.check_printer_firmware??!0,onChange:ge=>cn("check_printer_firmware",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider mb-4",children:i("settings.bambuddySoftware")})}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoCheckDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.check_updates,onChange:ge=>cn("check_updates",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:`flex items-center justify-between ${T.check_updates?"":"opacity-50"}`,children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.includeBetaUpdates")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.includeBetaUpdatesDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.include_beta_updates??!1,onChange:ge=>cn("include_beta_updates",ge.target.checked),disabled:!T.check_updates,className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",jr?.version||"..."]})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Bi(),disabled:Hi,children:[Hi?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),i("settings.checkNow")]})]}),In?.update_available?a.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",In.latest_version]}),In.release_name&&In.release_name!==In.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:In.release_name})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[In.release_notes&&a.jsx("button",{onClick:()=>je(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:i("settings.releaseNotes")}),In.release_url&&a.jsx("a",{href:In.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:a.jsx(sa,{className:"w-4 h-4"})})]})]}),Ci?.status==="downloading"||Ci?.status==="installing"?a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:Ci.message})]}),a.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ci.progress}%`}})})]}):Ci?.status==="complete"?a.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:Ci.message}):Ci?.status==="error"?a.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:Ci.error||Ci.message}):In?.is_docker?a.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.updateViaDocker")}),a.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):a.jsxs(Ie,{className:"mt-3",onClick:()=>pm.mutate(),disabled:pm.isPending,children:[pm.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(va,{className:"w-4 h-4"}),i("settings.installUpdate")]})]}):In?.error?a.jsx("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:i("settings.failedToCheckUpdates",{error:In.error})}):In&&!In.update_available?a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:i("settings.latestVersionRunning")}):null]})]})]}),a.jsxs(Dt,{id:"card-data",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Ae(!0),children:[a.jsx(un,{className:"w-4 h-4"}),i("common.clear")]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Te(!0),children:[a.jsx(un,{className:"w-4 h-4"}),i("settings.reset")]})]}),a.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.storageUsage","Storage Usage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageDescription","Breakdown of data usage by category")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:St,disabled:He||Pe,children:[a.jsx(vr,{className:`w-4 h-4 ${He||Pe?"animate-spin":""}`}),i("common.refresh","Refresh")]})]}),a.jsx("div",{className:"mt-3",children:vt?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("common.loading","Loading")]}):Pt?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:Pt.categories.filter(ge=>ge.bytes>0).map((ge,mt)=>a.jsx("div",{className:`${eX(ge.key,mt)} h-full`,style:{width:`${ge.percent_of_total}%`},title:`${ge.label}: ${ge.formatted}`},ge.key))}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:Pt.categories.filter(ge=>ge.bytes>0).map((ge,mt)=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:`w-3 h-3 rounded-full ${eX(ge.key,mt)}`}),a.jsx("span",{className:"text-bambu-gray",children:ge.label}),a.jsx("span",{className:"text-white",children:ge.formatted}),a.jsxs("span",{className:"text-bambu-gray",children:["(",ge.percent_of_total.toFixed(1),"%)"]})]},ge.key))}),a.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[i("settings.storageUsageTotal","Total"),": ",a.jsx("span",{className:"text-white",children:Pt.total_formatted}),Pt.scan_errors>0&&a.jsxs("span",{className:"ml-2 text-amber-400",children:[i("settings.storageUsageErrors","Scan errors"),": ",Pt.scan_errors]})]}),Pt.other_breakdown?.length>0&&a.jsxs("div",{className:"mt-4",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("settings.storageUsageOtherBreakdown","Other breakdown")}),a.jsx("div",{className:"space-y-2",children:Pt.other_breakdown.map(ge=>a.jsxs("div",{className:"flex items-center justify-between text-xs",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white",children:ge.label}),a.jsx("span",{className:`px-2 py-0.5 rounded-full border ${ge.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:ge.kind==="system"?i("settings.storageUsageSystem","System"):i("settings.storageUsageData","Data")})]}),a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:ge.formatted}),a.jsxs("span",{children:["(",ge.percent_of_total.toFixed(1),"%)"]})]})]},`${ge.bucket}-${ge.kind}`))})]})]}):a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.backupRestore")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.backupRestoreDescription")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>G("backup"),children:[a.jsx(Ul,{className:"w-4 h-4"}),i("settings.goToBackup")]})]})]})]})]})]}),W==="network"&&T&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[a.jsxs(Dt,{id:"card-externalurl",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(yd,{className:"w-5 h-5 text-blue-400"}),i("settings.externalUrl")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.externalUrlDescription")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bambuddyUrl")}),a.jsx("input",{type:"text",value:T.external_url??"",onChange:ge=>cn("external_url",ge.target.value),placeholder:"http://192.168.1.100:8000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.externalUrlHint")})]})]})]}),a.jsxs(Dt,{id:"card-ftpretry",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(vr,{className:"w-5 h-5 text-blue-400"}),i("settings.ftpRetry")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.ftpRetryDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoRetryDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.ftp_retry_enabled??!0,onChange:ge=>cn("ftp_retry_enabled",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),T.ftp_retry_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryAttempts")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:T.ftp_retry_count??3,onChange:ge=>cn("ftp_retry_count",parseInt(ge.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(ge=>a.jsx("option",{value:ge,children:i("settings.time",{count:ge})},ge))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryDelay")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:T.ftp_retry_delay??2,onChange:ge=>cn("ftp_retry_delay",parseInt(ge.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(ge=>a.jsx("option",{value:ge,children:i("settings.second",{count:ge})},ge))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.connectionTimeout")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:T.ftp_timeout??30,onChange:ge=>cn("ftp_timeout",parseInt(ge.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(ge=>a.jsx("option",{value:ge,children:i("settings.nSeconds",{count:ge})},ge))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.increaseForWeakWifi")})]})]})]})]})]}),a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[a.jsxs(Dt,{id:"card-ha",children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Mw,{className:"w-5 h-5 text-bambu-green"}),i("settings.homeAssistant")]}),T.ha_enabled&&Wt&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Wt.success?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${Wt.success?"text-green-400":"text-red-400"}`,children:Wt.success?i("settings.connected"):i("settings.disconnected")})]})]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.homeAssistantFullDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),T.ha_env_managed&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx(ld,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.ha_enabled??!1,onChange:ge=>cn("ha_enabled",ge.target.checked),disabled:T.ha_env_managed,className:"sr-only peer"}),a.jsx("div",{className:`w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green ${T.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),T.ha_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.homeAssistantUrl"),T.ha_url_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:T.ha_url??"",onChange:ge=>cn("ha_url",ge.target.value),placeholder:"http://192.168.1.100:8123",disabled:T.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 ${T.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),T.ha_url_from_env&&a.jsx(ld,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),T.ha_url_from_env&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.longLivedAccessToken"),T.ha_token_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"password",value:T.ha_token??"",onChange:ge=>cn("ha_token",ge.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:T.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 ${T.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),T.ha_token_from_env&&a.jsx(ld,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),T.ha_token_from_env?a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.haTokenHint")})]}),T.ha_url&&T.ha_token&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs(Ie,{variant:"secondary",size:"sm",disabled:dt,onClick:async()=>{pt(!0),Ue(null);try{const ge=await pe.testHAConnection(T.ha_url,T.ha_token);Ue(ge)}catch(ge){Ue({success:!1,message:null,error:ge instanceof Error?ge.message:i("common.unknownError")})}finally{pt(!1)}},children:[dt?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vf,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),a.jsxs(Dt,{id:"card-mqtt",children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(vf,{className:"w-5 h-5 text-blue-400"}),i("settings.mqttPublishing")]}),pa?.enabled&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${pa.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${pa.connected?"text-green-400":"text-red-400"}`,children:pa.connected?i("settings.connected"):i("settings.disconnected")})]})]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttEnableDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.mqtt_enabled??!1,onChange:ge=>cn("mqtt_enabled",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),T.mqtt_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.brokerHostname")}),a.jsx("input",{type:"text",value:T.mqtt_broker??"",onChange:ge=>cn("mqtt_broker",ge.target.value),placeholder:"mqtt.example.com or 192.168.1.100",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-end gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.port")}),a.jsx("input",{type:"number",min:"1",max:"65535",value:T.mqtt_port??1883,onChange:ge=>cn("mqtt_port",Math.min(65535,Math.max(1,parseInt(ge.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.mqtt_use_tls??!1,onChange:ge=>{const mt=ge.target.checked;cn("mqtt_use_tls",mt);const Je=T.mqtt_port??1883;mt&&Je===1883?cn("mqtt_port",8883):!mt&&Je===8883&&cn("mqtt_port",1883)},className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]}),a.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.usernameOptional")}),a.jsx("input",{type:"text",value:T.mqtt_username??"",onChange:ge=>cn("mqtt_username",ge.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.passwordOptional")}),a.jsx("input",{type:"password",value:T.mqtt_password??"",onChange:ge=>cn("mqtt_password",ge.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.topicPrefix")}),a.jsx("input",{type:"text",value:T.mqtt_topic_prefix??"bambuddy",onChange:ge=>cn("mqtt_topic_prefix",ge.target.value),placeholder:"bambuddy",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.topicPrefixHint",{prefix:T.mqtt_topic_prefix||"bambuddy"})})]}),pa&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${pa.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:"text-bambu-gray",children:pa.connected?a.jsxs(a.Fragment,{children:[i("settings.mqttConnectedTo")," ",a.jsxs("span",{className:"text-white",children:[pa.broker,":",pa.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),a.jsx("div",{className:"flex-1 lg:max-w-md space-y-3",children:a.jsxs(Dt,{id:"card-prometheus",children:[a.jsx(Dn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx($3,{className:"w-5 h-5 text-orange-400"}),i("settings.prometheusMetrics")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.prometheusEndpointDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.prometheus_enabled??!1,onChange:ge=>cn("prometheus_enabled",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),T.prometheus_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bearerTokenOptional")}),a.jsx("input",{type:"password",value:T.prometheus_token??"",onChange:ge=>cn("prometheus_token",ge.target.value),placeholder:i("settings.leaveEmptyForNoAuth"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.bearerTokenHint")})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),a.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - ",i("settings.metricsConnectionStatus")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - ",i("settings.metricsPrinterState")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - ",i("settings.metricsPrintProgress")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - ",i("settings.metricsBedTemp")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - ",i("settings.metricsNozzleTemp")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - ",i("settings.metricsPrintsTotal")]}),a.jsx("p",{className:"text-bambu-gray/70 italic",children:i("settings.metricsMore")})]})]})]})]})]})})]}),Wt&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Wt.success?a.jsx(fr,{className:"w-8 h-8 text-green-400"}):a.jsx($a,{className:"w-8 h-8 text-red-400"}),a.jsx("h3",{className:"text-lg font-medium text-white",children:Wt.success?i("settings.connectionSuccessful"):i("settings.connectionFailed")})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:Wt.success?Wt.message||i("settings.haConnectionSuccess"):Wt.error||i("settings.haConnectionFailed")}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Ie,{variant:"primary",onClick:()=>Ue(null),children:i("settings.ok")})})]})}),W==="plugs"&&a.jsxs("div",{id:"card-plugs",children:[a.jsxs("div",{className:"flex items-start justify-between mb-6",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ql,{className:"w-5 h-5 text-bambu-green"}),i("settings.smartPlugs")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.smartPlugsDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Ct&&Ct.filter(ge=>ge.enabled).length>1&&a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Ee("on"),disabled:ja.isPending,title:i("settings.turnAllPlugsOn"),children:[ja.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(im,{className:"w-4 h-4 text-bambu-green"}),i("settings.allOn")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Ee("off"),disabled:ja.isPending,title:i("settings.turnAllPlugsOff"),children:[ja.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Rw,{className:"w-4 h-4 text-red-400"}),i("settings.allOff")]})]}),a.jsxs(Ie,{className:"whitespace-nowrap",onClick:()=>{X(null),$(!0)},children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addSmartPlug")]})]})]}),Ct&&Ct.length>0&&a.jsxs(Dt,{className:"mb-6",children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-yellow-400"}),i("settings.energySummary"),Nn&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),a.jsx(Rt,{children:Jt?a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Xl,{className:"w-3 h-3"}),i("settings.currentPower")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[Jt.totalPower.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:i("settings.plugsOnline",{reachable:Jt.reachableCount,total:Jt.totalPlugs})})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Wr,{className:"w-3 h-3"}),i("settings.today")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[Jt.totalToday.toFixed(3),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(T?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(Jt.totalToday*(T?.energy_cost_per_kwh??0)).toFixed(2)," ",yo(T?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx($3,{className:"w-3 h-3"}),i("settings.yesterday")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[Jt.totalYesterday.toFixed(3),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(T?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(Jt.totalYesterday*(T?.energy_cost_per_kwh??0)).toFixed(2)," ",yo(T?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Zk,{className:"w-3 h-3"}),i("settings.total")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[Jt.totalLifetime.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(T?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(Jt.totalLifetime*(T?.energy_cost_per_kwh??0)).toFixed(2)," ",yo(T?.currency||"USD")]})]})]}):Nn?null:a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.enablePlugsForSummary")})})]}),Zt?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ct&&Ct.length>0?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Ct.map(ge=>a.jsx(dtt,{plug:ge,onEdit:mt=>{X(mt),$(!0)}},ge.id))}):a.jsx(Dt,{children:a.jsx(Rt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(ql,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),a.jsxs(Ie,{onClick:()=>{X(null),$(!0)},children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),W==="notifications"&&a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-providers",children:[a.jsx(Ah,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>_e(!0),children:[a.jsx(L0,{className:"w-4 h-4"}),i("settings.log")]}),vn&&vn.length>0&&a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>{Oo(null),oc.mutate()},disabled:oc.isPending,children:[oc.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),i("settings.testAll")]}),a.jsxs(Ie,{size:"sm",onClick:()=>{ee(null),te(!0)},children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addNotificationProvider")]})]})]}),a.jsx(Dt,{className:"mb-4",children:a.jsx(Rt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),a.jsx("select",{value:T.notification_language||"en",onChange:ge=>cn("notification_language",ge.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:G8.map(ge=>a.jsx("option",{value:ge.code,children:ge.nativeName},ge.code))})]})})}),a.jsx(Dt,{className:"mb-4",children:a.jsx(Rt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.bedCooledThreshold")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.bedCooledThresholdDescription")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:20,max:80,step:1,value:T.bed_cooled_threshold??35,onChange:ge=>cn("bed_cooled_threshold",Number(ge.target.value)),className:"w-16 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm text-center focus:outline-none focus:ring-1 focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),a.jsx(Dt,{className:"mb-4",children:a.jsx(Rt,{className:"py-3",children:a.jsxs("div",{className:`flex items-center justify-between ${En?.advanced_auth_enabled?"":"opacity-50"}`,children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.userNotificationsEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:En?.advanced_auth_enabled?i("settings.userNotificationsEnabledDescription"):i("settings.userNotificationsDisabledHint")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",className:"sr-only peer",checked:T.user_notifications_enabled??!0,disabled:!En?.advanced_auth_enabled,onChange:ge=>cn("user_notifications_enabled",ge.target.checked)}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green peer-disabled:cursor-not-allowed"})]})]})})}),$i&&a.jsx(Dt,{className:"mb-4",children:a.jsxs(Rt,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),a.jsx("button",{onClick:()=>Oo(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(fr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:$i.success})]}),$i.failed>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx($a,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:$i.failed})]})]}),$i.results.filter(ge=>!ge.success).length>0&&a.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:$i.results.filter(ge=>!ge.success).map(ge=>a.jsxs("div",{className:"text-xs text-red-400",children:[a.jsxs("span",{className:"font-medium",children:[ge.provider_name,":"]})," ",ge.message]},ge.provider_id))})]})}),yn?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):vn&&vn.length>0?a.jsx("div",{className:"space-y-3",children:vn.map(ge=>a.jsx(mtt,{provider:ge,onEdit:mt=>{ee(mt),te(!0)}},ge.id))}):a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ah,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),a.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),a.jsxs(Ie,{size:"sm",onClick:()=>{ee(null),te(!0)},children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-2",id:"card-templates",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:i("settings.messageTemplatesDescription")}),a.jsxs("div",{className:"relative mb-3",children:[a.jsx(Sr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),a.jsx("input",{type:"text",value:ue,onChange:ge=>K(ge.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"}),ue&&a.jsx("button",{onClick:()=>K(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear filter",children:a.jsx(Bt,{className:"w-3.5 h-3.5"})})]}),mi?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):On&&On.length>0?(()=>{const ge=ue.trim().toLowerCase(),mt=[...On].sort((Je,$t)=>Je.name.localeCompare($t.name)).filter(Je=>!ge||Je.name.toLowerCase().includes(ge)||(Je.title_template||"").toLowerCase().includes(ge));return mt.length===0?a.jsx("p",{className:"text-sm text-bambu-gray italic text-center py-6",children:i("settings.noTemplatesMatch","No templates match your filter.")}):a.jsx("div",{className:"space-y-2",children:mt.map(Je=>a.jsx(Dt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>le(Je),children:a.jsx(Rt,{className:"py-2.5 px-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium text-sm truncate",children:Je.name}),a.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:Je.title_template})]}),a.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:$t=>{$t.stopPropagation(),le(Je)},children:a.jsx(xh,{className:"w-4 h-4 text-bambu-gray"})})]})})},Je.id))})})():a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ms,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),W==="apikeys"&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-createapi",children:[a.jsx(El,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),a.jsxs(Ie,{size:"sm",onClick:()=>V(!0),className:"flex-shrink-0",children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.createKey")]})]}),se&&a.jsx(Dt,{className:"mb-6 border-bambu-green",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(fr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[a.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:se}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(se);else{const ge=document.createElement("textarea");ge.value=se,ge.style.position="fixed",ge.style.left="-999999px",document.body.appendChild(ge),ge.select(),document.execCommand("copy"),document.body.removeChild(ge)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:a.jsx(Mo,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-2 mt-3",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>{we(se),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>U(null),children:i("common.dismiss")})]})]})]})})}),Q&&a.jsxs(Dt,{className:"mb-6",children:[a.jsx(Dn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),a.jsx("input",{type:"text",value:J,onChange:ge=>ie(ge.target.value),placeholder:i("settings.keyNamePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:he.can_read_status,onChange:ge=>fe(mt=>({...mt,can_read_status:ge.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.readStatus")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:he.can_queue,onChange:ge=>fe(mt=>({...mt,can_queue:ge.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:he.can_control_printer,onChange:ge=>fe(mt=>({...mt,can_control_printer:ge.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[a.jsxs(Ie,{onClick:()=>bn.mutate({name:J||i("settings.unnamedKey"),...he}),disabled:bn.isPending,children:[bn.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ur,{className:"w-4 h-4"}),i("settings.createKey")]}),a.jsx(Ie,{variant:"secondary",onClick:()=>V(!1),children:i("common.cancel")})]})]})]}),rn?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):an&&an.length>0?a.jsx("div",{className:"space-y-3",children:an.map(ge=>a.jsx(Dt,{children:a.jsx(Rt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(El,{className:`w-5 h-5 ${ge.enabled?"text-bambu-green":"text-bambu-gray"}`}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:ge.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[ge.key_prefix,"••••••••",ge.last_used&&` · ${i("settings.lastUsed")}: ${Uf(ge.last_used)}`]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex gap-1 text-xs",children:[ge.can_read_status&&a.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),ge.can_queue&&a.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),ge.can_control_printer&&a.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>re(ge.id),children:a.jsx(un,{className:"w-4 h-4 text-red-400"})})]})]})})},ge.id))}):a.jsx(Dt,{children:a.jsx(Rt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(El,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),a.jsxs(Ie,{onClick:()=>V(!0),children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),a.jsxs(Dt,{className:"mt-6",children:[a.jsx(Dn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",id:"card-webhooks",children:i("settings.webhookEndpoints")})}),a.jsxs(Rt,{className:"space-y-3 text-sm",children:[a.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),a.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-green-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-red-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-apibrowser",children:[a.jsx(yd,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),a.jsx(Dt,{className:"mb-4",children:a.jsxs(Rt,{className:"py-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),a.jsx("input",{type:"text",value:xe,onChange:ge=>we(ge.target.value),placeholder:i("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),a.jsx(Itt,{apiKey:xe})]})]}),W==="virtual-printer"&&a.jsx("div",{id:"card-vp",children:a.jsx(Ptt,{})}),W==="queue"&&T&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"lg:w-1/2 space-y-3",children:[a.jsxs(Dt,{id:"card-print-options",children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(nN,{className:"w-4 h-4 text-bambu-green"}),i("settings.defaultPrintOptions","Default Print Options")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.defaultPrintOptionsDescription","Set default values for print options when starting new prints. These can be overridden per print in the print dialog.")}),[{key:"default_bed_levelling",label:i("settings.defaultBedLevelling","Bed Levelling"),desc:i("settings.defaultBedLevellingDesc","Auto-level bed before print"),fallback:!0},{key:"default_flow_cali",label:i("settings.defaultFlowCali","Flow Calibration"),desc:i("settings.defaultFlowCaliDesc","Calibrate extrusion flow"),fallback:!1},{key:"default_vibration_cali",label:i("settings.defaultVibrationCali","Vibration Calibration"),desc:i("settings.defaultVibrationCaliDesc","Reduce ringing artifacts"),fallback:!0},{key:"default_layer_inspect",label:i("settings.defaultLayerInspect","First Layer Inspection"),desc:i("settings.defaultLayerInspectDesc","AI inspection of first layer"),fallback:!1},{key:"default_timelapse",label:i("settings.defaultTimelapse","Timelapse"),desc:i("settings.defaultTimelapseDesc","Record timelapse video"),fallback:!1}].map(({key:ge,label:mt,desc:Je,fallback:$t})=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 mr-4",children:[a.jsx("p",{className:"text-sm text-white",children:mt}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:Je})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T[ge]??$t,onChange:tn=>cn(ge,tn.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]},ge))]})]}),a.jsxs(Dt,{id:"card-staggered",children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-green"}),i("settings.staggeredStart","Staggered Start")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.staggeredStartDescription","Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.")}),a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerGroupSize","Group size")}),a.jsx("input",{type:"number",min:1,max:50,value:T.stagger_group_size??2,onChange:ge=>cn("stagger_group_size",Math.max(1,Math.min(50,parseInt(ge.target.value)||1))),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerGroupSizeHelp","Printers to start simultaneously per group")})]}),a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerInterval","Interval (minutes)")}),a.jsx("input",{type:"number",min:1,max:60,value:T.stagger_interval_minutes??5,onChange:ge=>cn("stagger_interval_minutes",Math.max(1,Math.min(60,parseInt(ge.target.value)||1))),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerIntervalHelp","Delay between each group starting")})]})]})]})]}),a.jsxs(Dt,{id:"card-plate",children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(Wb,{className:"w-4 h-4 text-bambu-green"}),i("settings.plateClear","Plate-Clear Confirmation")]})}),a.jsx(Rt,{className:"space-y-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 mr-4",children:[a.jsx("p",{className:"text-sm text-white",children:i("settings.requirePlateClear","Require plate-clear confirmation")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.requirePlateClearDescription","When enabled, the scheduler waits for per-printer plate-clear confirmation before starting queued prints on printers with finished jobs. Disable for farm workflows where plates are verified physically.")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.require_plate_clear??!0,onChange:ge=>cn("require_plate_clear",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})})]}),a.jsxs(Dt,{id:"card-gcode",children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(ey,{className:"w-4 h-4 text-bambu-green"}),i("settings.gcodeInjection","G-code Injection")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.gcodeInjectionDescription",'Configure custom G-code to inject at the start and/or end of prints for auto-print systems like Farmloop, SwapMod, AutoClear, and Printflow 3D. Snippets are configured per printer model and applied when "Inject G-code" is enabled on a queue item.')}),(()=>{const ge=(()=>{try{return T.gcode_snippets?JSON.parse(T.gcode_snippets):{}}catch{return{}}})(),mt=[...new Set((ar||[]).filter(tn=>tn.model).map(tn=>tn.model))].sort(),Je=(tn,fn,gr)=>{const Kn={...ge};Kn[tn]||(Kn[tn]={start_gcode:"",end_gcode:""}),Kn[tn][fn]=gr,!Kn[tn].start_gcode&&!Kn[tn].end_gcode&&delete Kn[tn];const sn=Object.keys(Kn).length>0?JSON.stringify(Kn):"";C(Mn=>Mn?{...Mn,gcode_snippets:sn}:null),fs.current=sn},$t=()=>{fs.current!==null&&(zd.mutate({gcode_snippets:fs.current}),fs.current=null)};return mt.length===0?a.jsx("p",{className:"text-sm text-bambu-gray italic",children:i("settings.gcodeInjectionNoPrinters","No printers found. Add printers to configure G-code snippets.")}):mt.map(tn=>{const fn=ge[tn]||{start_gcode:"",end_gcode:""},gr=!!(fn.start_gcode||fn.end_gcode);return a.jsx(lle,{defaultOpen:gr,className:"border border-bambu-dark-tertiary rounded-lg px-3 py-2",summary:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:tn}),gr&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:i("settings.gcodeConfigured","Configured")})]}),children:a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeStartLabel","Start G-code")}),a.jsx("textarea",{value:fn.start_gcode,onChange:Kn=>Je(tn,"start_gcode",Kn.target.value),onBlur:$t,placeholder:i("settings.gcodeStartPlaceholder","G-code prepended before the print starts..."),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono focus:outline-none focus:border-bambu-green resize-y"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeEndLabel","End G-code")}),a.jsx("textarea",{value:fn.end_gcode,onChange:Kn=>Je(tn,"end_gcode",Kn.target.value),onBlur:$t,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"})]})]})},tn)})})()]})]})]}),a.jsx("div",{className:"lg:w-1/2 space-y-3",children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",id:"card-drying",children:[a.jsx(Qp,{className:"w-4 h-4 text-amber-400"}),i("settings.queueDrying")]})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.queueDryingDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingEnabledDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.queue_drying_enabled??!1,onChange:ge=>cn("queue_drying_enabled",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),T.queue_drying_enabled&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingBlock")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingBlockDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.queue_drying_block??!1,onChange:ge=>cn("queue_drying_block",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-amber-500"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.ambientDryingEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.ambientDryingEnabledDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.ambient_drying_enabled??!1,onChange:ge=>cn("ambient_drying_enabled",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:i("settings.dryingPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.dryingPresetsDescription")}),a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-1.5",children:i("settings.dryingFilament")}),a.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS 2 Pro"}),a.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS-HT"})]})}),a.jsx("tbody",{children:(()=>{const ge={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 mt={...ge};try{if(T.drying_presets){const $t=JSON.parse(T.drying_presets);typeof $t=="object"&&$t!==null&&(mt={...ge,...$t})}}catch{}const Je=($t,tn,fn)=>{const gr={...mt,[$t]:{...mt[$t],[tn]:fn}};cn("drying_presets",JSON.stringify(gr))};return Object.entries(mt).map(([$t,tn])=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50",children:[a.jsx("td",{className:"py-1.5 pr-2 text-white font-medium",children:$t}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a.jsx("input",{type:"number",min:30,max:65,value:tn.n3f,onChange:fn=>Je($t,"n3f",Math.max(1,parseInt(fn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:tn.n3f_hours,onChange:fn=>Je($t,"n3f_hours",Math.max(1,parseInt(fn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"h"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a.jsx("input",{type:"number",min:30,max:85,value:tn.n3s,onChange:fn=>Je($t,"n3s",Math.max(1,parseInt(fn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:tn.n3s_hours,onChange:fn=>Je($t,"n3s_hours",Math.max(1,parseInt(fn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"h"})]})})]},$t))})()})]})})]})]})]})})]}),W==="filament"&&T&&a.jsx(a.Fragment,{children:a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"lg:w-1/3 space-y-3",children:[a.jsx(vtt,{}),a.jsxs(Dt,{id:"card-filamentchecks",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.filamentChecks")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.disableFilamentWarnings")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.disableFilamentWarningsDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.disable_filament_warnings,onChange:ge=>cn("disable_filament_warnings",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.preferLowestFilament")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.preferLowestFilamentDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.prefer_lowest_filament,onChange:ge=>cn("prefer_lowest_filament",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})]})]}),a.jsxs(Dt,{id:"card-printmodal",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.printModal")})}),a.jsx(Rt,{className:"space-y-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.expandCustomMapping")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.expandCustomMappingDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.per_printer_mapping_expanded??!1,onChange:ge=>cn("per_printer_mapping_expanded",ge.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})})]}),a.jsxs(Dt,{id:"card-amsthresholds",children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),a.jsxs(Rt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(mO,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:T.ams_humidity_good??40,onChange:ge=>cn("ams_humidity_good",parseInt(ge.target.value)||40),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:T.ams_humidity_fair??60,onChange:ge=>cn("ams_humidity_fair",parseInt(ge.target.value)||60),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")}),a.jsx("p",{className:"text-xs text-amber-400/70",children:i("settings.fairAlsoDryingThreshold")})]}),a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(PP,{className:"w-4 h-4 text-orange-400"}),a.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:T.ams_temp_good??28,onChange:ge=>cn("ams_temp_good",parseFloat(ge.target.value)||28),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:T.ams_temp_fair??35,onChange:ge=>cn("ams_temp_fair",parseFloat(ge.target.value)||35),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Ul,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"1",max:"365",value:T.ams_history_retention_days??30,onChange:ge=>cn("ams_history_retention_days",parseInt(ge.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]})]})]})]}),a.jsxs("div",{className:"lg:w-2/3 space-y-3",children:[a.jsx(wtt,{}),a.jsx(Stt,{})]})]})}),R!==null&&a.jsx(kn,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{Gn.mutate(R),re(null)},onCancel:()=>re(null)}),F&&a.jsx(utt,{plug:I,onClose:()=>{$(!1),X(null)}}),L&&a.jsx(ptt,{provider:ae,onClose:()=>{te(!1),ee(null)}}),me&&a.jsx(ftt,{template:me,onClose:()=>le(null)}),be&&a.jsx(btt,{onClose:()=>_e(!1)}),ye&&a.jsx(kn,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{Ae(!1);try{const ge=await pe.clearNotificationLogs(30);o(ge.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>Ae(!1)}),ve&&a.jsx(kn,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{Te(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>Te(!1)}),Fe&&a.jsx(kn,{title:`Turn All Plugs ${Fe==="on"?"On":"Off"}`,message:`This will turn ${Fe==="on"?"ON":"OFF"} all ${Ct?.filter(ge=>ge.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 ge=Fe;Ee(null),ja.mutate(ge)},onCancel:()=>Ee(null)}),Se&&In?.release_notes&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>je(!1),children:a.jsxs(Dt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ge=>ge.stopPropagation(),children:[a.jsxs(Dn,{className:"flex flex-row items-center justify-between shrink-0",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",In.latest_version]}),In.release_name&&In.release_name!==In.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray",children:In.release_name})]}),a.jsx("button",{onClick:()=>je(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx(Rt,{className:"overflow-y-auto flex-1",children:a.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:In.release_notes})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[In.release_url&&a.jsx("a",{href:In.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:a.jsxs(Ie,{variant:"secondary",className:"w-full",children:[a.jsx(sa,{className:"w-4 h-4"}),"View on GitHub"]})}),a.jsx(Ie,{onClick:()=>je(!1),className:"flex-1",children:"Close"})]})]})}),W==="users"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>O("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 ${de==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(_u,{className:"w-4 h-4"}),i("settings.tabs.users")]}),a.jsxs("button",{onClick:()=>O("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 ${de==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(vx,{className:"w-4 h-4"}),i("settings.tabs.emailAuth")||"Email Authentication",En?.advanced_auth_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>O("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 ${de==="ldap"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Wb,{className:"w-4 h-4"}),i("settings.tabs.ldap")||"LDAP",Vt?.ldap_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]})]}),de==="users"&&a.jsxs(a.Fragment,{children:[a.jsx(Dt,{children:a.jsx(Rt,{className:"py-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?a.jsx(ld,{className:"w-5 h-5 text-green-400"}):a.jsx(s0,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&a.jsxs(Ie,{variant:"secondary",onClick:()=>Re(!0),children:[a.jsx(s0,{className:"w-4 h-4"}),i("common.disable")]}):a.jsxs(Ie,{onClick:()=>e("/setup"),children:[a.jsx(ld,{className:"w-4 h-4"}),i("common.enable")]})]})})}),En?.advanced_auth_enabled&&a.jsx(Dt,{className:"border-blue-500/30 bg-blue-500/5",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(vx,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-3",children:[c&&a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-currentuser",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),c.auth_source!=="ldap"&&a.jsxs(Ie,{size:"sm",variant:"ghost",onClick:()=>ce(!0),children:[a.jsx(El,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),c.groups?.map(ge=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ge.name==="Administrators"?"bg-purple-500/20 text-purple-300":ge.name==="Operators"?"bg-blue-500/20 text-blue-300":ge.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ge.name},ge.id))]})]})})})]}),a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-users",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),u("users:create")&&a.jsxs(Ie,{size:"sm",onClick:()=>{tt(!0),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),a.jsx(Rt,{children:mm?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):sc.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:sc.map(ge=>a.jsxs("div",{className:"py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:ge.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ge.auth_source==="ldap"&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-cyan-500/20 text-cyan-300",children:"LDAP"}),ge.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),ge.groups?.map(mt=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${mt.name==="Administrators"?"bg-purple-500/20 text-purple-300":mt.name==="Operators"?"bg-blue-500/20 text-blue-300":mt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:mt.name},mt.id))]})]}),a.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[u("users:update")&&a.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>hm(ge),children:a.jsx(xh,{className:"w-4 h-4"})}),u("users:delete")&&ge.id!==c?.id&&a.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>qi(ge.id),children:a.jsx(un,{className:"w-4 h-4"})})]})]},ge.id))})})]})]}),a.jsx("div",{children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-groups",children:[a.jsx(Wb,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),u("groups:create")&&a.jsxs(Ie,{size:"sm",onClick:()=>e("/groups/new"),children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),a.jsx(Rt,{children:qc?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):hs.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:hs.map(ge=>a.jsxs("div",{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wb,{className:`w-4 h-4 ${ge.name==="Administrators"?"text-purple-400":ge.name==="Operators"?"text-blue-400":ge.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),a.jsx("span",{className:"text-white font-medium",children:ge.name}),ge.is_system&&a.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[u("groups:update")&&a.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${ge.id}/edit`),children:a.jsx(xh,{className:"w-4 h-4"})}),u("groups:delete")&&!ge.is_system&&a.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>Qt(ge.id),children:a.jsx(un,{className:"w-4 h-4"})})]})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ge.description||i("settings.noDescription")}),a.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[a.jsx("span",{children:i("settings.userCount",{count:ge.user_count})}),a.jsx("span",{children:i("settings.permissionCount",{count:ge.permissions.length})})]})]},ge.id))})})]})})]}),!l&&a.jsx(Dt,{children:a.jsx(Rt,{className:"py-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx(s0,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),a.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature1")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature2")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),a.jsxs(Ie,{onClick:()=>e("/setup"),children:[a.jsx(ld,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),de==="email"&&a.jsx("div",{className:"max-w-5xl",id:"card-smtp",children:a.jsx(Ett,{})}),de==="ldap"&&a.jsx("div",{className:"max-w-5xl",id:"card-ldap",children:a.jsx(Ftt,{})})]}),Ve&&!En?.advanced_auth_enabled&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{tt(!1),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:ge=>ge.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{tt(!1),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),a.jsx("input",{type:"text",value:Nt.username,onChange:ge=>ht({...Nt,username: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("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),a.jsx("input",{type:"password",value:Nt.password,onChange:ge=>ht({...Nt,password: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("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Nt.confirmPassword,onChange:ge=>ht({...Nt,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 ${Nt.confirmPassword&&Nt.password!==Nt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),Nt.confirmPassword&&Nt.password!==Nt.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[hs.map(ge=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Nt.group_ids.includes(ge.id),onChange:()=>zs(ge.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ge.name}),ge.is_system&&a.jsx("span",{className:"text-xs text-yellow-400",children:i("settings.systemBadge")})]},ge.id)),hs.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>{tt(!1),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("common.cancel")}),a.jsx(Ie,{onClick:Pi,disabled:Lo.isPending||!Nt.username||!Nt.password||Nt.password!==Nt.confirmPassword||Nt.password.length<6,children:Lo.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("settings.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:"w-4 h-4"}),i("settings.createUser")]})})]})]})]})}),Ve&&En?.advanced_auth_enabled&&a.jsx(ytt,{formData:Nt,setFormData:ht,groups:hs,onClose:()=>{tt(!1),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:Pi,isCreating:Lo.isPending,isCreateButtonDisabled:Lo.isPending||!Nt.username||!Nt.email}),ut&&wt!==null&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{xt(!1),Ht(null),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:ge=>ge.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{xt(!1),Ht(null),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",En?.advanced_auth_enabled&&a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:Nt.username,onChange:ge=>ht({...Nt,username: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("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",En?.advanced_auth_enabled?a.jsx("span",{className:"text-red-400",children:"*"}):a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),a.jsx("input",{type:"email",value:Nt.email,onChange:ge=>ht({...Nt,email: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("users.form.emailPlaceholder")||"user@example.com",required:En?.advanced_auth_enabled})]}),!En?.advanced_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),a.jsx("input",{type:"password",value:Nt.password,onChange:ge=>ht({...Nt,password:ge.target.value,confirmPassword:""}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),Nt.password&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Nt.confirmPassword,onChange:ge=>ht({...Nt,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 ${Nt.confirmPassword&&Nt.password!==Nt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Nt.confirmPassword&&Nt.password!==Nt.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),En?.advanced_auth_enabled&&a.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>wt&&ps.mutate(wt),disabled:ps.isPending||!Nt.email,className:"w-full",children:ps.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):a.jsxs(a.Fragment,{children:[a.jsx(jo,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),a.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:hs.map(ge=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Nt.group_ids.includes(ge.id),onChange:()=>zs(ge.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ge.name}),ge.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},ge.id))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>{xt(!1),Ht(null),ht({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),a.jsx(Ie,{onClick:()=>lo(wt),disabled:$c.isPending||!Nt.username||En?.advanced_auth_enabled&&!Nt.email||!!(!En?.advanced_auth_enabled&&Nt.password&&(Nt.password!==Nt.confirmPassword||Nt.password.length<6)),children:$c.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),Xt!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Kt(null),en(null)},children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:ge=>ge.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[a.jsx(un,{className:"w-5 h-5"}),a.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),a.jsx(Rt,{className:"space-y-3",children:Ke?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):Ut&&Ut.archives+Ut.queue_items+Ut.library_files>0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),a.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[Ut.archives>0&&a.jsxs("li",{children:[Ut.archives," archive",Ut.archives!==1?"s":""]}),Ut.queue_items>0&&a.jsxs("li",{children:[Ut.queue_items," queue item",Ut.queue_items!==1?"s":""]}),Ut.library_files>0&&a.jsxs("li",{children:[Ut.library_files," library file",Ut.library_files!==1?"s":""]})]}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(Ie,{variant:"danger",onClick:()=>Is.mutate({id:Xt,deleteItems:!0}),disabled:Is.isPending,className:"justify-center",children:i("settings.deleteUserAndItems")}),a.jsx(Ie,{variant:"secondary",onClick:()=>Is.mutate({id:Xt,deleteItems:!1}),disabled:Is.isPending,className:"justify-center",children:i("settings.deleteUserKeepItems")}),a.jsx(Ie,{variant:"ghost",onClick:()=>{Kt(null),en(null)},disabled:Is.isPending,className:"justify-center",children:i("common.cancel")})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ie,{variant:"ghost",onClick:()=>{Kt(null),en(null)},disabled:Is.isPending,children:i("common.cancel")}),a.jsx(Ie,{variant:"danger",onClick:()=>Is.mutate({id:Xt,deleteItems:!1}),disabled:Is.isPending,children:i("settings.deleteUserTitle")})]})]})})]})}),Mt!==null&&a.jsx(kn,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{Id.mutate(Mt),Qt(null)},onCancel:()=>Qt(null)}),W==="backup"&&a.jsx("div",{id:"card-backup",children:a.jsx(Att,{})}),qe&&a.jsx(kn,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await pe.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await d(),Re(!1),window.location.href="/"}catch(ge){const mt=ge instanceof Error?ge.message:i("settings.toast.authDisableFailed");o(mt,"error")}},onCancel:()=>Re(!1)}),Ye&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{ce(!1),Ne({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:ge=>ge.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(El,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{ce(!1),Ne({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),a.jsx("input",{type:"password",value:ze.currentPassword,onChange:ge=>Ne({...ze,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("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),a.jsx("input",{type:"password",value:ze.newPassword,onChange:ge=>Ne({...ze,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("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),a.jsx("input",{type:"password",value:ze.confirmPassword,onChange:ge=>Ne({...ze,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 ${ze.confirmPassword&&ze.newPassword!==ze.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),ze.confirmPassword&&ze.newPassword!==ze.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>{ce(!1),Ne({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),a.jsx(Ie,{onClick:async()=>{if(ze.newPassword!==ze.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(ze.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}$e(!0);try{await pe.changePassword(ze.currentPassword,ze.newPassword),o(i("settings.toast.passwordChanged"),"success"),ce(!1),Ne({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ge){const mt=ge instanceof Error?ge.message:"Failed to change password";o(mt,"error")}finally{$e(!1)}},disabled:Ge||!ze.currentPassword||!ze.newPassword||ze.newPassword!==ze.confirmPassword||ze.newPassword.length<6,children:Ge?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("settings.changing")]}):a.jsxs(a.Fragment,{children:[a.jsx(El,{className:"w-4 h-4"}),i("settings.changePassword")]})})]})]})]})})]})]})]})})}const cle=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},Htt=t=>t.startsWith("HH")?"HF":"S",qtt=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},dle=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function o3({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:s,note:o}){const l=Htt(t.nozzle_id),c=t.nozzle_diameter,d=()=>{r&&s?s():e()};return a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?a.jsx(us,{className:"w-4 h-4 text-bambu-green"}):a.jsx(eo,{className:"w-4 h-4"})}),a.jsxs("button",{onClick:d,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${i?"ring-1 ring-bambu-green":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:cle(t.k_value)}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&a.jsx("span",{title:"Has note",children:a.jsx(SQ,{className:"w-3 h-3 text-yellow-500"})}),a.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&a.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&a.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:a.jsx(Mo,{className:"w-4 h-4"})})]})}function l3({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:i=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:d,onSaveNote:u,hasPermission:m}){const{t:p}=Lt(),{showToast:f}=xn(),[y,v]=w.useState(t?.name||""),[b,g]=w.useState(t?.k_value?cle(t.k_value):"0.020"),[_,k]=w.useState(t?.filament_id||""),[P,N]=w.useState(t?.nozzle_id?qtt(t.nozzle_id):"HH00"),[M,A]=w.useState(t?.nozzle_diameter||n),[T,C]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[F,$]=w.useState(!1),[I,X]=w.useState({current:0,total:0}),[L,te]=w.useState(o),ae=Qr.useMemo(()=>{const oe=new Map;for(const _e of i)oe.set(_e.filament_id,_e.name);const be=new Map;for(const _e of r)if(_e.filament_id&&!be.has(_e.filament_id)){const Y=oe.get(_e.filament_id)||dle(_e.name||"");be.set(_e.filament_id,{id:_e.filament_id,name:Y||_e.filament_id})}return Array.from(be.values()).sort((_e,B)=>_e.name.localeCompare(B.name))},[r,i]),ee=lt({mutationFn:oe=>(console.log("[KProfile] Calling API..."),pe.setKProfile(e,oe)),onSuccess:oe=>{if(console.log("[KProfile] Save success:",oe),f(p("kProfiles.toast.profileSaved")),u&&L!==o){let be;L===""&&l?be=l:t&&t.slot_id>0?be=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:be=`name_${y}_${_}`,u(be,L)}$(!0),setTimeout(()=>{$(!1),d()},2500)},onError:oe=>{console.error("[KProfile] Save error:",oe),f(oe.message,"error"),$(!1)}}),me=lt({mutationFn:oe=>(console.log("[KProfile] Deleting profile..."),pe.deleteKProfile(e,oe)),onSuccess:oe=>{console.log("[KProfile] Delete success:",oe),f(p("kProfiles.toast.profileDeleted")),$(!0),setTimeout(()=>{$(!1),c()},4e3)},onError:oe=>{console.error("[KProfile] Delete error:",oe),f(oe.message,"error"),$(!1)}}),[le,ue]=w.useState(!1),K=()=>{t&&me.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})},ne=async oe=>{if(oe.preventDefault(),s&&!t&&T.length===0){f(p("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const be=parseFloat(b).toFixed(6),_e=`${P}-${M}`;if(t||T.length===1){const Y={name:y,k_value:be,filament_id:_,nozzle_id:_e,nozzle_diameter:M,extruder_id:t?t.extruder_id:T[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",Y),ee.mutate(Y);return}$(!0),X({current:1,total:T.length});const B=T.map(Y=>({name:y,k_value:be,filament_id:_,nozzle_id:_e,nozzle_diameter:M,extruder_id:Y,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${B.length} profiles in batch:`,B);try{if(await pe.setKProfilesBatch(e,B),f(p("kProfiles.toast.profilesSaved",{count:T.length})),u&&L){const Y=`name_${y}_${_}`;u(Y,L)}}catch(Y){console.error("[KProfile] Failed to save batch:",Y),f(p("kProfiles.toast.failedToSaveBatch"),"error"),$(!1),X({current:0,total:0});return}X({current:T.length,total:T.length}),setTimeout(()=>{$(!1),X({current:0,total:0}),d()},3e3)};return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[a.jsxs(Dt,{className:"w-full max-w-md relative",children:[F&&a.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),a.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")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:p("kProfiles.modal.pleaseWait")})]}),a.jsxs(Rt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:p(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),a.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:F,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:ne,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.profileName")}),a.jsx("input",{type:"text",value:y,onChange:oe=>v(oe.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:p("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.kValue")}),a.jsx("input",{type:"text",inputMode:"decimal",value:b,onChange:oe=>{const be=oe.target.value;(be===""||/^\d*\.?\d*$/.test(be))&&g(be)},onBlur:oe=>{const be=parseFloat(oe.target.value);isNaN(be)||g((Math.trunc(be*1e3)/1e3).toFixed(3))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono",placeholder:p("kProfiles.modal.kValuePlaceholder"),required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.kValueHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.filament")}),a.jsxs("select",{value:_,onChange:oe=>{const be=oe.target.value;if(k(be),!t&&be&&!y){const _e=ae.find(B=>B.id===be);_e&&v(`${P==="HH00"?"HF":"S"} ${_e.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[a.jsx("option",{value:"",children:p("kProfiles.modal.selectFilament")}),t?.filament_id&&a.jsx("option",{value:t.filament_id,children:ae.find(oe=>oe.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&ae.map(oe=>a.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),!t&&ae.length===0&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.noFilamentsHelp")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.flowType")}),a.jsxs("select",{value:P,onChange:oe=>{const be=oe.target.value;if(N(be),!t&&_&&!y){const _e=ae.find(B=>B.id===_);_e&&v(`${be==="HS00"?"HF":"S"} ${_e.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"HH00",children:p("kProfiles.modal.highFlow")}),a.jsx("option",{value:"HS00",children:p("kProfiles.modal.standard")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.nozzleSize")}),a.jsxs("select",{value:M,onChange:oe=>A(oe.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?a.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?p("kProfiles.modal.left"):p("kProfiles.modal.right")}):a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.includes(1),onChange:oe=>{oe.target.checked?C([...T,1]):C(T.filter(be=>be!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:p("kProfiles.modal.left")})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:T.includes(0),onChange:oe=>{oe.target.checked?C([...T,0]):C(T.filter(be=>be!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:p("kProfiles.modal.right")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.notes")}),a.jsx("textarea",{value:L,onChange:oe=>te(oe.target.value),placeholder:p("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none resize-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.notesHelp")})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&a.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>ue(!0),disabled:me.isPending||F||!m("kprofiles:delete"),title:m("kprofiles:delete")?void 0:p("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:me.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"})}),a.jsx(Ie,{type:"button",variant:"secondary",onClick:c,disabled:F,className:"flex-1",children:p("common.cancel")}),a.jsxs(Ie,{type:"submit",disabled:ee.isPending||F||!m(t?"kprofiles:update":"kprofiles:create"),title:m(t?"kprofiles:update":"kprofiles:create")?void 0:p(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[ee.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Aw,{className:"w-4 h-4"}),p("common.save")]})]})]})]})]}),le&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:a.jsx(Dt,{className:"w-full max-w-sm",children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(un,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:p("kProfiles.deleteConfirm.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:p("kProfiles.deleteConfirm.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:p("kProfiles.deleteConfirm.message",{name:t?.name})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>ue(!1),className:"flex-1",children:p("common.cancel")}),a.jsxs(Ie,{onClick:()=>{ue(!1),K()},disabled:me.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[me.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),p("common.delete")]})]})]})})})]})}const pk={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function $tt(){const{t}=Lt(),{showToast:e}=xn(),{hasPermission:n}=_r(),[r,i]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(pk.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[k,P]=w.useState(()=>localStorage.getItem(pk.SORT_OPTION)||"name"),[N,M]=w.useState(!1),[A,T]=w.useState(new Set),[C,F]=w.useState(!1),[$,I]=w.useState(!1),X=w.useCallback(R=>`${R.slot_id}_${R.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(pk.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(pk.SORT_OPTION,k)},[k]);const{data:L,isLoading:te}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:ae,isLoading:ee,isFetching:me,error:le,refetch:ue}=et({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const R=await pe.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",R?.profiles?.length||0,"profiles"),R},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:K}=et({queryKey:["kprofiles",r,"0.4"],queryFn:()=>pe.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:ne}=et({queryKey:["builtinFilaments"],queryFn:()=>pe.getBuiltinFilaments(),staleTime:3e5}),{data:oe}=et({queryKey:["filamentIdMap"],queryFn:()=>pe.getFilamentIdMap(),staleTime:3e5}),{data:be,refetch:_e}=et({queryKey:["kprofile-notes",r],queryFn:()=>pe.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),B=le?.message?.includes("not connected");w.useEffect(()=>{if(!r&&L&&L.length>0){const R=L.find(re=>re.is_active);R&&i(R.id)}},[r,L]),w.useEffect(()=>{if(r){const R=setTimeout(()=>{ue()},150);return()=>clearTimeout(R)}},[r,s]);const Y=L?.filter(R=>R.is_active)||[],D=Qr.useMemo(()=>{const R=new Map;if(ne)for(const re of ne)R.set(re.filament_id,re.name);if(oe)for(const[re,xe]of Object.entries(oe))R.has(re)||R.set(re,xe);return R},[ne,oe]),j=Qr.useMemo(()=>Array.from(D.entries()).map(([R,re])=>({filament_id:R,name:re})),[D]),z=Qr.useCallback(R=>D.get(R.filament_id)||dle(R.name),[D]),W=Qr.useMemo(()=>ae?.profiles?ae.profiles.filter(re=>{const xe=f.toLowerCase(),we=!xe||re.name.toLowerCase().includes(xe)||re.filament_id.toLowerCase().includes(xe),ye=v==="all"||v==="left"&&re.extruder_id===1||v==="right"&&re.extruder_id===0,Ae=g==="all"||g==="hf"&&re.nozzle_id.startsWith("HH")||g==="s"&&re.nozzle_id.startsWith("HS");return we&&ye&&Ae}).sort((re,xe)=>{switch(k){case"k_value":return parseFloat(re.k_value)-parseFloat(xe.k_value);case"filament":return z(re).localeCompare(z(xe));default:return re.name.localeCompare(xe.name)}}):[],[ae?.profiles,f,v,g,k,z]),q=L?.find(R=>R.id===r),de=q?.nozzle_count===2;w.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(),ue()):re.key==="n"||re.key==="N"?(re.preventDefault(),u(!0)):re.key==="Escape"&&N&&(re.preventDefault(),M(!1),T(new Set)))};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[l,d,m,N,ue]);const O=w.useCallback(()=>{if(!ae?.profiles||ae.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const R={version:1,exported_at:new Date().toISOString(),printer:q?.name||"Unknown",nozzle_diameter:s,profiles:ae.profiles.map(ye=>({name:ye.name,k_value:ye.k_value,filament_id:ye.filament_id,nozzle_id:ye.nozzle_id,nozzle_diameter:ye.nozzle_diameter,extruder_id:ye.extruder_id}))},re=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),xe=URL.createObjectURL(re),we=document.createElement("a");we.href=xe,we.download=`kprofiles_${q?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(we),we.click(),document.body.removeChild(we),URL.revokeObjectURL(xe),e(t("kProfiles.toast.exportedProfiles",{count:ae.profiles.length}))},[ae?.profiles,q,s,e,t]),G=w.useCallback(()=>{const R=document.createElement("input");R.type="file",R.accept=".json",R.onchange=async re=>{const xe=re.target.files?.[0];if(xe)try{const we=await xe.text(),ye=JSON.parse(we);if(!ye.profiles||!Array.isArray(ye.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let Ae=0;for(const ve of ye.profiles)if(!(!ve.name||!ve.k_value||!ve.filament_id))try{await pe.setKProfile(r,{name:ve.name,k_value:parseFloat(ve.k_value).toFixed(6),filament_id:ve.filament_id,nozzle_id:ve.nozzle_id||`HH00-${s}`,nozzle_diameter:ve.nozzle_diameter||s,extruder_id:ve.extruder_id??0,slot_id:0}),Ae++,await new Promise(Te=>setTimeout(Te,500))}catch(Te){console.error("Failed to import profile:",ve.name,Te)}e(t("kProfiles.toast.importedProfiles",{count:Ae,total:ye.profiles.length})),ue()}catch(we){console.error("Import error:",we),e(t("kProfiles.toast.failedToParseImport"),"error")}},R.click()},[r,s,e,ue,t]),Q=w.useCallback(R=>{T(re=>{const xe=new Set(re);return xe.has(R)?xe.delete(R):xe.add(R),xe})},[]),V=w.useCallback(()=>{T(new Set(W.map(R=>X(R))))},[W,X]),J=w.useCallback(()=>{A.size!==0&&F(!0)},[A.size]),ie=w.useCallback(async()=>{const R=W.filter(xe=>A.has(X(xe)));I(!0);let re=0;for(const xe of R)try{await pe.deleteKProfile(r,{slot_id:xe.slot_id,extruder_id:xe.extruder_id,nozzle_id:xe.nozzle_id,nozzle_diameter:xe.nozzle_diameter,filament_id:xe.filament_id,setting_id:xe.setting_id}),re++,await new Promise(we=>setTimeout(we,300))}catch(we){console.error("Failed to delete profile:",xe.name,we)}e(t("kProfiles.toast.profilesDeleted",{count:re})),I(!1),F(!1),M(!1),T(new Set),ue()},[r,A,W,e,ue,X,t]),he=w.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},[]),fe=w.useCallback(async(R,re)=>{if(r)try{await pe.setKProfileNote(r,R,re),_e()}catch(xe){console.error("Failed to save note:",xe),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,_e,e,t]),se=w.useCallback(R=>{if(!be?.notes)return{note:"",key:null};const re=he(R);for(const xe of re)if(be.notes[xe])return{note:be.notes[xe],key:xe};return{note:"",key:null}},[be,he]),U=w.useCallback(R=>se(R).note,[se]);return te?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!L||L.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-12 text-center",children:[a.jsx(qa,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):Y.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-12 text-center",children:[a.jsx(Pr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):a.jsxs(a.Fragment,{children:[me&&!ee&&a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[a.jsx(ct,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1 min-w-48",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),a.jsx("select",{value:r||"",onChange:R=>i(parseInt(R.target.value)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:Y.map(R=>a.jsx("option",{value:R.id,children:R.name},R.id))})]}),a.jsxs("div",{className:"w-32",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),a.jsxs("select",{value:s,onChange:R=>o(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>ue(),disabled:me||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[a.jsx(vr,{className:`w-4 h-4 ${me?"animate-spin":""}`}),t("kProfiles.refresh")]}),a.jsxs(Ie,{onClick:()=>u(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[a.jsx(ur,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[a.jsxs("div",{className:"flex-1 min-w-48 relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:f,onChange:R=>y(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"})]}),de&&a.jsx("div",{className:"w-36",children:a.jsxs("select",{value:v,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:[a.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),a.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),a.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:g,onChange:R=>_(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),a.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),a.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:k,onChange:R=>P(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("kProfiles.sortName")}),a.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),a.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[a.jsxs(Ie,{variant:"secondary",onClick:O,disabled:!ae?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[a.jsx(va,{className:"w-4 h-4"}),t("kProfiles.export")]}),a.jsxs(Ie,{variant:"secondary",onClick:G,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[a.jsx(Ca,{className:"w-4 h-4"}),t("kProfiles.import")]}),a.jsx("div",{className:"flex-1"}),N?a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"secondary",onClick:V,children:[a.jsx(us,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),a.jsxs(Ie,{variant:"secondary",onClick:J,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:[a.jsx(un,{className:"w-4 h-4"}),t("kProfiles.delete")," (",A.size,")"]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>{M(!1),T(new Set)},children:[a.jsx(Bt,{className:"w-4 h-4"}),t("common.cancel")]})]}):a.jsxs(Ie,{variant:"secondary",onClick:()=>M(!0),disabled:!W.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(us,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),ee?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):B?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-12 text-center",children:[a.jsx(Ku,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),a.jsxs(Ie,{variant:"secondary",onClick:()=>ue(),children:[a.jsx(vr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):W.length>0?de?a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),a.jsx("div",{className:"space-y-1",children:W.filter(R=>R.extruder_id===1).map(R=>a.jsx(o3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:A.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),a.jsx("div",{className:"space-y-1",children:W.filter(R=>R.extruder_id===0).map(R=>a.jsx(o3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:A.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))})]})]}):a.jsx("div",{className:"space-y-1",children:W.map(R=>a.jsx(o3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:A.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))}):f||v!=="all"||g!=="all"?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-12 text-center",children:[a.jsx(Sr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-12 text-center",children:[a.jsx(Aw,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),a.jsxs(Ie,{onClick:()=>u(!0),children:[a.jsx(ur,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:R,key:re}=se(l);return a.jsx(l3,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:K?.profiles||ae?.profiles,builtinFilaments:j,isDualNozzle:de,initialNote:R,initialNoteKey:re,onSaveNote:fe,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ue()},onSave:()=>{c(null),ue()}})})(),d&&r&&a.jsx(l3,{printerId:r,nozzleDiameter:s,existingProfiles:K?.profiles||ae?.profiles,builtinFilaments:j,isDualNozzle:de,onSaveNote:fe,hasPermission:n,onClose:()=>{u(!1),ue()},onSave:()=>{u(!1),ue()}}),m&&r&&a.jsx(l3,{printerId:r,nozzleDiameter:s,existingProfiles:K?.profiles||ae?.profiles,builtinFilaments:j,isDualNozzle:de,onSaveNote:fe,hasPermission:n,profile:{...m,slot_id:0,name:`${m.name} (Copy)`},onClose:()=>{p(null),ue()},onSave:()=>{p(null),ue()}}),C&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-sm",children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(un,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:A.size})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>F(!1),disabled:$,className:"flex-1",children:t("common.cancel")}),a.jsxs(Ie,{onClick:ie,disabled:$,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[$?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const ule=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],Vtt={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 Gtt(t){const e=t.toUpperCase();for(const n of ule)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function Wtt(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of ule){const i=n.indexOf(r);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function c3({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:i}=Lt(),{hasPermission:s}=_r(),o=t.filament_type||Gtt(t.name),l=t.filament_vendor||Wtt(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=Vtt[o.toUpperCase()]||null),a.jsx(Dt,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:a.jsxs(Rt,{className:"p-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&a.jsx("div",{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0 ${!d&&!c?"opacity-25":d?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),a.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&a.jsx("span",{className:"text-xs text-bambu-gray",children:l}),a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&a.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:a.jsx(un,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?a.jsx(Yl,{className:"w-3.5 h-3.5"}):a.jsx(Fn,{className:"w-3.5 h-3.5"})})]})]}),r&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),a.jsx("span",{className:"text-white",children:o})]}),l&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),a.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),a.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),a.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),a.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),a.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),a.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),a.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),a.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function Ktt(){const{t}=Lt(),{hasPermission:e}=_r(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(""),[o,l]=w.useState(null),[c,d]=w.useState(!1),[u,m]=w.useState(null),{data:p,isLoading:f}=et({queryKey:["localPresets"],queryFn:()=>pe.getLocalPresets()}),y=lt({mutationFn:async A=>{const T=[];for(const C of Array.from(A)){const F=new FormData;F.append("file",C),T.push(await pe.importLocalPresets(F))}return T},onSuccess:A=>{n.invalidateQueries({queryKey:["localPresets"]});let T=0,C=0,F=0;for(const $ of A)T+=$.imported,C+=$.skipped,F+=$.errors.length;T>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:T})),C>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:C}),"warning"),F>0&&r(t("profiles.localProfiles.toast.importError",{count:F}),"error")},onError:A=>{r(A.message,"error")}}),v=lt({mutationFn:A=>pe.deleteLocalPreset(A),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),m(null),r(t("profiles.localProfiles.toast.deleted"))}}),b=w.useCallback(A=>{!A||A.length===0||y.mutate(A)},[y]),g=w.useCallback(A=>{A.preventDefault(),d(!1),b(A.dataTransfer.files)},[b]),_=w.useCallback(A=>{if(!i)return A;const T=i.toLowerCase();return A.filter(C=>C.name.toLowerCase().includes(T)||C.filament_type?.toLowerCase().includes(T)||C.filament_vendor?.toLowerCase().includes(T))},[i]),k=w.useMemo(()=>_(p?.filament||[]),[p?.filament,_]),P=w.useMemo(()=>_(p?.printer||[]),[p?.printer,_]),N=w.useMemo(()=>_(p?.process||[]),[p?.process,_]),M=k.length+P.length+N.length;return f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&a.jsxs("div",{onDragOver:A=>{A.preventDefault(),d(!0)},onDragLeave:()=>d(!1),onDrop:g,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:A=>b(A.target.files)}),y.isPending?a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"}),a.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ca,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),M>0&&a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:i,onChange: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"})]}),M===0&&!f&&a.jsxs("div",{className:"text-center py-12",children:[a.jsx(ty,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),M>0&&a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[k.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(SP,{className:"w-4 h-4 text-bambu-green"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:k.map(A=>a.jsx(c3,{preset:A,onDelete:T=>m(T),onExpand:l,isExpanded:o===A.id},A.id))})]}),N.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(ea,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:N.map(A=>a.jsx(c3,{preset:A,onDelete:T=>m(T),onExpand:l,isExpanded:o===A.id},A.id))})]}),P.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Nd,{className:"w-4 h-4 text-orange-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",P.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:P.map(A=>a.jsx(c3,{preset:A,onDelete:T=>m(T),onExpand:l,isExpanded:o===A.id},A.id))})]})]}),u!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(qa,{className:"w-5 h-5 text-red-400"}),a.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{variant:"secondary",size:"sm",onClick:()=>m(null),children:t("profiles.localProfiles.cancel")}),a.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>v.mutate(u),disabled:v.isPending,children:[v.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function Kz(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),i=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,d=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),u=d?d[1].toUpperCase():null;return{printer:i,nozzle:o,layerHeight:c,filamentType:u}}function kw(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function Ytt({onSuccess:t,t:e}){const{showToast:n}=xn(),[r,i]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(""),[m,p]=w.useState(""),[f,y]=w.useState("global"),[v,b]=w.useState(null),[g,_]=w.useState(null),k=lt({mutationFn:()=>pe.cloudLogin(s,l,f),onSuccess:T=>{T.success?(n(e("profiles.login.toast.loggedIn")),t()):T.needs_verification?(b(T.verification_type||"email"),_(T.tfa_key||null),T.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(T.message,"error")},onError:T=>n(T.message,"error")}),P=lt({mutationFn:()=>pe.cloudVerify(s,d,g||void 0),onSuccess:T=>{T.success?(n(e("profiles.login.toast.loggedIn")),t()):n(T.message,"error")},onError:T=>n(T.message,"error")}),N=lt({mutationFn:()=>pe.cloudSetToken(m),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:T=>n(T.message,"error")}),M=T=>{T.preventDefault(),r==="email"?k.mutate():r==="code"?P.mutate():r==="token"&&N.mutate()},A=k.isPending||P.isPending||N.isPending;return a.jsx(Dt,{className:"max-w-md mx-auto",children:a.jsxs(Rt,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:a.jsx(Jx,{className:"w-6 h-6 text-bambu-green"})}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),a.jsxs("form",{onSubmit:M,className:"space-y-4",children:[r==="email"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),a.jsx("input",{type:"email",value:s,onChange:T=>o(T.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),a.jsx("input",{type:"password",value:l,onChange:T=>c(T.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"••••••••",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),a.jsxs("select",{value:f,onChange:T=>y(T.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),a.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),a.jsx("input",{type:"text",value:d,onChange:T=>u(T.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),a.jsx("textarea",{value:m,onChange:T=>p(T.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r==="code"&&a.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),a.jsxs(Ie,{type:"submit",disabled:A,className:"flex-1",children:[A?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(u6,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(El,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(u6,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Lb({label:t,value:e,options:n,onChange:r}){const[i,s]=w.useState(!1),o=n.find(l=>l.value===e);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),a.jsx("span",{children:o?.label||"All"}),a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),a.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>a.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[a.jsx("span",{children:l.label}),l.count!==void 0&&a.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function Xtt(){const[t,e]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?a.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:a.jsx(Lf,{className:"w-5 h-5"})}):null}function d3({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=Kz(t.name),d=kw(t.setting_id);return a.jsxs("div",{className:"flex items-center gap-2 group",children:[a.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${i?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&a.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!i&&d&&a.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),a.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:a.jsx(Mo,{className:"w-4 h-4"})})]})}function BL(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(`
  8334. `)){const i=t.replace(/\\n/g,`
  8335. `).replace(/\\"/g,'"').replace(/\\t/g," ").split(`
  8336. `);if(i.length>1)return`"""
  8337. `+i.map(s=>n+" "+s).join(`
  8338. `)+`
  8339. `+n+'"""'}return JSON.stringify(t)}if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":`[
  8340. `+t.map(i=>n+" "+BL(i,e+1)).join(`,
  8341. `)+`
  8342. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{
  8343. `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+BL(o,e+1)).join(`,
  8344. `)+`
  8345. `+n+"}"}return String(t)}function Qtt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=xn(),c=mn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=et({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>pe.getCloudSettingDetail(t.setting_id)}),f=lt({mutationFn:()=>pe.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=kw(t.setting_id),v=Kz(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&a.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:BL(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Ln,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Ie,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Ie,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Mo,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(Za,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Ie,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]})})]})})})}function mle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function hle(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Ztt({onClose:t,onApply:e,t:n}){const{showToast:r}=xn(),[i,s]=w.useState(mle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,k]=w.useState(null),P=o==="all"?i:i.filter(X=>X.type===o),N=X=>{s(X),hle(X)},M=X=>{const L=i.filter(te=>te.id!==X);N(L),k(null),r(n("profiles.templates.toast.deleted"))},A=X=>{d(X.id),m(X.name),f(X.description),v(JSON.stringify(X.settings,null,2)),g(null)},T=()=>{if(!(!c||!u.trim()))try{const X=JSON.parse(y),L=i.map(te=>te.id===c?{...te,name:u.trim(),description:p.trim(),settings:X}:te);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(X){g(X.message)}},C=()=>{d(null),m(""),f(""),v("{}"),g(null)},F=X=>{const L=i.map(te=>te.id===X?{...te,showInModal:!te.showInModal}:te);N(L)},$={filament:{label:n("profiles.presets.types.filament"),icon:SP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Nd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Pr,color:"text-purple-400"}},I=_?i.find(X=>X.id===_):null;return w.useEffect(()=>{const X=L=>{L.key==="Escape"&&(_?k(null):c?C():t())};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(Dt,{className:"w-full max-w-md",children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Ln,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Ie,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(un,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(Dt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(X=>a.jsx("button",{onClick:()=>l(X),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:X==="all"?n("common.all"):$[X].label},X))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(wx,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(X=>{const L=$[X.type],te=L.icon;return c===X.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ae=>m(ae.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:y,onChange:ae=>{v(ae.target.value),g(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:T,disabled:!u.trim(),children:[a.jsx(cs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},X.id):a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[a.jsx(te,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:X.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:X.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(X.settings).length})}),a.jsx("button",{onClick:()=>F(X.id),className:`p-1 transition-colors ${X.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:X.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:X.showInModal?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(X),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>A(X),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>k(X.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]},X.id)})})})]})})]})}function ple({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],k=b in e,P=b in n;let N;!k&&P?N="added":k&&!P?N="removed":JSON.stringify(g)!==JSON.stringify(_)?N="changed":N="same",v.push({key:b,left:g,right:_,status:N})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...u];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[u,o,c]),p=w.useMemo(()=>({added:u.filter(y=>y.status==="added").length,removed:u.filter(y=>y.status==="removed").length,changed:u.filter(y=>y.status==="changed").length,same:u.filter(y=>y.status==="same").length}),[u]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(ur,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(rN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(O3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(uj,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:y=>d(y.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),a.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(uj,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:a.jsx(ur,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(rN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(O3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(uj,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Jtt({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=xn(),s=mn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[k,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,M]=w.useState(null),[A,T]=w.useState(""),[C,F]=w.useState(!1),[$,I]=w.useState(""),[X,L]=w.useState(!1),[te,ae]=w.useState(mle),[ee,me]=w.useState(!1),[le,ue]=w.useState(""),[K,ne]=w.useState(""),[oe,be]=w.useState(!0),[_e,B]=w.useState(null),[Y,D]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),z=w.useMemo(()=>j.filter(je=>kw(je.setting_id)),[j]),{data:W}=et({queryKey:["cloudFields",d],queryFn:()=>pe.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:q}=et({queryKey:["allPresetDetails",d,z.map(je=>je.setting_id).join(",")],queryFn:async()=>{const je={};for(let Re=0;Re<z.length;Re+=5){const Ye=z.slice(Re,Re+5);(await Promise.all(Ye.map(async ze=>{try{const Ne=await pe.getCloudSettingDetail(ze.setting_id);return{id:ze.setting_id,detail:Ne}}catch{return null}}))).forEach(ze=>{ze&&(je[ze.id]=ze.detail)})}return je},enabled:z.length>0,staleTime:1e3*60*10}),{data:de,isLoading:O}=et({queryKey:["cloudSettingDetail",f],queryFn:()=>pe.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(g,null,2))},[g,l]);const G=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(qe=>!kw(qe.setting_id)).sort((qe,Re)=>qe.name.localeCompare(Re.name)),[n,d]);w.useEffect(()=>{if(!f)return;const je=G.find(qe=>qe.setting_id===f);je&&(b(je.name),o||(_({inherits:je.name}),P(JSON.stringify({inherits:je.name},null,2))))},[f,G,o]);const Q=w.useMemo(()=>{const je=W?.fields||[],qe=new Set(je.map(ze=>ze.key)),Re=new Set,Ye=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);q&&Object.values(q).forEach(ze=>{ze?.setting&&Object.keys(ze.setting).forEach(Ne=>{!qe.has(Ne)&&!Ye.has(Ne)&&Re.add(Ne)})}),Object.keys(g).forEach(ze=>{!qe.has(ze)&&!Ye.has(ze)&&Re.add(ze)});const ce=Array.from(Re).sort().map(ze=>({key:ze,label:ze.replace(/_/g," ").replace(/\b\w/g,Ne=>Ne.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...je,...ce]},[W,q,g,r]),V=Q.filter(je=>je.label.toLowerCase().includes(A.toLowerCase())||je.key.toLowerCase().includes(A.toLowerCase())),J=()=>{if($.trim()){const je=$.trim().toLowerCase().replace(/\s+/g,"_");ie(je,""),I(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:je}))}},ie=(je,qe)=>{_(Re=>{const Ye={...Re};return qe===""||qe===void 0?delete Ye[je]:Ye[je]=qe,Ye})},he=je=>{_(qe=>({...qe,...je.settings})),B(je.name),i(r("profiles.templates.toast.applied"))},fe=()=>{if(!le.trim())return;const je={...g};if(delete je.inherits,Object.keys(je).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const qe={id:Date.now().toString(),name:le.trim(),description:K.trim()||r("profiles.presets.customTemplate"),type:d,settings:je,showInModal:oe},Re=[...te,qe];ae(Re),hle(Re),me(!1),ue(""),ne(""),be(!0),i(r("profiles.templates.toast.created"))},se=w.useMemo(()=>te.filter(je=>je.type===d&&je.showInModal),[d,te]),U=je=>{P(je);try{const qe=JSON.parse(je);_(qe),M(null)}catch(qe){M(qe.message)}},R=je=>{je.preventDefault(),F(!1);const qe=je.dataTransfer.files[0];if(qe&&qe.name.endsWith(".json")){const Re=new FileReader;Re.onload=Ye=>{try{const ce=Ye.target?.result,ze=JSON.parse(ce),Ne=ze.setting||ze;_(Ge=>({...Ge,...Ne})),P(JSON.stringify({...g,...Ne},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Re.readAsText(qe)}},re=lt({mutationFn:()=>{const je={...g},qe=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";je[qe]=`"${m}"`;const Re={type:d,name:m,base_id:f,setting:je};return pe.createCloudSetting(Re)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),xe=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return pe.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),we=o?xe:re,ye=de?.setting?.inherits,Ae=ye?G.find(je=>je.name===ye):void 0,{data:ve}=et({queryKey:["cloudSettingDetail",Ae?.setting_id],queryFn:()=>pe.getCloudSettingDetail(Ae.setting_id),enabled:!!Ae?.setting_id}),Te=w.useMemo(()=>{const je=ve?.setting||{},qe=de?.setting||{},Re=f&&q?.[f]?.setting?q[f].setting:{};return{...je,...qe,...Re}},[f,de,ve,q]),Fe=je=>{if(je==null)return"";if(Array.isArray(je)){const qe=[...new Set(je.map(Re=>String(Re)))];return qe.length===1?qe[0]:je.join(", ")}return String(je)},Ee=je=>{const qe=g[je.key],Re=Te[je.key],Ye=Fe(Re),ce=O?r("common.loading"):Ye||"",ze="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(je.type==="boolean"){const Ne=qe==="1"||qe===void 0&&Re==="1";return a.jsx("button",{type:"button",onClick:()=>ie(je.key,qe==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ne?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ne?"translate-x-3.5":"translate-x-0.5"}`})})}return je.type==="select"?a.jsxs("select",{value:qe||"",onChange:Ne=>ie(je.key,Ne.target.value),className:ze,children:[a.jsx("option",{value:"",children:ce}),je.options?.map(Ne=>a.jsx("option",{value:Ne.value,children:Ne.label},Ne.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:je.type==="number"?"number":"text",value:qe!==void 0?String(qe):"",onChange:Ne=>ie(je.key,Ne.target.value),step:je.step,min:je.min,max:je.max,placeholder:ce,className:ze}),je.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:je.unit})]})},Se=w.useMemo(()=>de?.setting?de.setting:{},[de]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:je=>{je.preventDefault(),F(!0)},onDragLeave:()=>F(!1),onDrop:R,children:[Y&&f&&a.jsx(ple,{onClose:()=>D(!1),leftPreset:Se,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(Dt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>D(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[a.jsx(tx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),C&&a.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(Ca,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:je=>{u(je.target.value),y("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:je=>y(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),G.map(je=>a.jsx("option",{value:je.setting_id,children:je.name},je.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:m,onChange:je=>p(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),O&&a.jsx(ct,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(m6,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Ew,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(ey,{className:"w-4 h-4"}),"JSON",N&&a.jsx(qa,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const je={name:m,type:d,base_id:f,setting:g},qe=new Blob([JSON.stringify(je,null,2)],{type:"application/json"}),Re=URL.createObjectURL(qe),Ye=document.createElement("a");Ye.href=Re,Ye.download=`${m||"preset"}.json`,document.body.appendChild(Ye),Ye.click(),document.body.removeChild(Ye),URL.revokeObjectURL(Re),i(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[a.jsx(va,{className:"w-4 h-4"}),r("common.download")]}),a.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[a.jsx(Ca,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:je=>{const qe=je.target.files?.[0];if(qe){const Re=new FileReader;Re.onload=Ye=>{try{const ce=JSON.parse(Ye.target?.result),ze=ce.setting||ce;_(Ne=>({...Ne,...ze})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Re.readAsText(qe)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsxs("button",{onClick:()=>me(!ee),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(cs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),ee&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:le,onChange:je=>ue(je.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:K,onChange:je=>ne(je.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:fe,disabled:!le.trim(),children:[a.jsx(cs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>me(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>be(!oe),className:`flex items-center gap-1.5 text-xs transition-colors ${oe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[oe?a.jsx(Dc,{className:"w-3.5 h-3.5"}):a.jsx(Tw,{className:"w-3.5 h-3.5"}),r(oe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),_e&&a.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[a.jsx(Kr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:_e})]}),a.jsx("button",{onClick:()=>B(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[se.map(je=>a.jsxs("button",{onClick:()=>he(je),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:je.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:je.description})]},je.id)),se.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:Q.slice(0,10).map(je=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:je.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ee(je)})]},je.key))})]}),Object.keys(g).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([je])=>je!=="inherits").map(([je,qe])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[je,": ",String(qe).slice(0,20),a.jsx("button",{onClick:()=>ie(je,void 0),className:"hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},je))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:q?r("profiles.templates.fieldsCount",{count:Q.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:A,onChange:je=>T(je.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[V.filter(je=>!(je.key in g)).map(je=>{const qe=Te[je.key],Re=Fe(qe);return a.jsxs("div",{onClick:()=>{_(Ye=>({...Ye,[je.key]:Re||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:je.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:je.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Re&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Re,children:[Re.slice(0,20),Re.length>20?"...":""]}),a.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:a.jsx(ur,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},je.key)}),V.filter(je=>!(je.key in g)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(A?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:X?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:$,onChange:je=>I(je.target.value),onKeyDown:je=>je.key==="Enter"&&J(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx(Ie,{size:"sm",onClick:J,disabled:!$.trim(),children:a.jsx(ur,{className:"w-4 h-4"})}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>L(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(ur,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(je=>je!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([je])=>je!=="inherits").map(([je,qe])=>{const Re=Q.find(Ye=>Ye.key===je);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Re?.label||je}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:je})]}),a.jsx("button",{onClick:()=>ie(je,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),Re?Ee(Re):a.jsx("input",{type:"text",value:String(qe),onChange:Ye=>ie(je,Ye.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"})]},je)}),Object.keys(g).filter(je=>je!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(m6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{me(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(cs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(qa,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:k,onChange:je=>U(je.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ie,{onClick:()=>we.mutate(),disabled:we.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[we.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o?a.jsx(cs,{className:"w-4 h-4"}):a.jsx(ur,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function ent({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[k,P]=w.useState("all"),[N,M]=w.useState(null),[A,T]=w.useState(!1),[C,F]=w.useState(!1),[$,I]=w.useState(null),[X,L]=w.useState(null),[te,ae]=w.useState(null),[ee,me]=w.useState(!1),[le,ue]=w.useState([null,null]),[K,ne]=w.useState(!1),[oe,be]=w.useState(null),_e=mn(),B=w.useMemo(()=>[...t.filament.map(J=>({...J,type:"filament"})),...t.printer.map(J=>({...J,type:"printer"})),...t.process.map(J=>({...J,type:"process"}))].map(J=>({...J,meta:Kz(J.name)})),[t]),Y=w.useMemo(()=>{const V=new Set,J=new Set,ie=new Set;return B.forEach(he=>{he.meta.nozzle&&V.add(he.meta.nozzle),he.meta.filamentType&&J.add(he.meta.filamentType),he.meta.layerHeight&&ie.add(he.meta.layerHeight)}),{printers:i.map(he=>({id:he.id.toString(),name:he.name})),nozzles:Array.from(V).sort((he,fe)=>parseFloat(he)-parseFloat(fe)),filaments:Array.from(J).sort(),layerHeights:Array.from(ie).sort((he,fe)=>parseFloat(he)-parseFloat(fe))}},[B,i]),D=w.useMemo(()=>f==="all"?null:i.find(J=>J.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>B.filter(V=>d==="all"||V.type===d).filter(V=>{if(m==="all")return!0;const J=kw(V.setting_id);return m==="custom"?J:!J}).filter(V=>{if(f==="all"||!D)return!0;const J=V.meta.printer?.toLowerCase()||"",ie=D.toLowerCase();return J.includes(ie)||ie.includes(J)}).filter(V=>v==="all"||V.meta.nozzle===v).filter(V=>g==="all"||V.meta.filamentType===g).filter(V=>k==="all"||V.meta.layerHeight===k).filter(V=>l===""||V.name.toLowerCase().includes(l.toLowerCase())).sort((V,J)=>V.name.localeCompare(J.name)),[B,d,m,f,D,v,g,k,l]),z=V=>{if(ee){const J=le[0]?.setting_id===V.setting_id,ie=le[1]?.setting_id===V.setting_id;if(J)ue([le[1],null]);else if(ie)ue([le[0],null]);else if(!le[0])ue([V,null]);else if(le[1]){if(le[0].type!==V.type)return;ue([le[0],V])}else{if(le[0].type!==V.type)return;ue([le[0],V])}}else M(V)},W=V=>{if(le[0]?.setting_id===V.setting_id)return 0;if(le[1]?.setting_id===V.setting_id)return 1},q=async V=>{try{const J=await pe.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;I({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{}}),M(null)}catch(J){console.error("Failed to fetch preset details for duplication:",J)}},de=async V=>{try{_e.removeQueries({queryKey:["cloudSettingDetail",V.setting_id]});const J=await pe.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;L({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{},setting_id:V.setting_id}),M(null)}catch(J){console.error("Failed to fetch preset details for editing:",J)}},O=()=>{u("all"),p("all"),y("all"),b("all"),_("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||k!=="all"||l!=="",Q=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:V=>c(V.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Ie,{variant:ee?"primary":"secondary",onClick:()=>{ee?(me(!1),ue([null,null])):me(!0)},children:[a.jsx(tx,{className:"w-4 h-4"}),o(ee?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(wx,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Ie,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(vr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Ie,{onClick:()=>T(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(Lb,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:Q},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:V=>u(V)}),a.jsx(Lb,{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:V=>p(V)}),Y.printers.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(V=>({value:V.id,label:V.name}))],onChange:y}),Y.nozzles.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(V=>({value:V,label:V}))],onChange:b}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(V=>({value:V,label:V}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(V=>({value:V,label:V}))],onChange:P}),G&&a.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),ee&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:le[0]?o("profiles.cloudView.selectAnotherPreset",{type:le[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[0]?le[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(O3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[1]?le[1].name:o("profiles.cloudView.selectSecond")})]}),le[0]&&le[1]&&a.jsxs(Ie,{size:"sm",onClick:async()=>{try{const[V,J]=await Promise.all([pe.getCloudSettingDetail(le[0].setting_id),pe.getCloudSettingDetail(le[1].setting_id)]);be([V.setting||{},J.setting||{}]),ne(!0)}catch{}},children:[a.jsx(tx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Sx(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:Q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(ea,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&a.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(SP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="filament").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Nd,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="process").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Pr,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="printer").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx(Qtt,{setting:N,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>q(N),onEdit:()=>de(N),hasPermission:s,t:o}),(A||$||X||te)&&a.jsx(Jtt,{onClose:()=>{T(!1),I(null),L(null),ae(null)},initialData:X||$||(te?{type:te.type,name:"",base_id:"",setting:te.setting}:void 0),allPresets:t,t:o}),C&&a.jsx(Ztt,{onClose:()=>F(!1),onApply:V=>{ae({type:V.type,setting:V.settings}),F(!1)},t:o}),K&&oe&&le[0]&&le[1]&&a.jsx(ple,{onClose:()=>{ne(!1),be(null)},leftPreset:oe[0],rightPreset:oe[1],leftLabel:le[0].name,rightLabel:le[1].name,t:o})]})}function tnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=_r(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=et({queryKey:["cloudStatus"],queryFn:pe.getCloudStatus}),{data:u=[]}=et({queryKey:["printers"],queryFn:pe.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=et({queryKey:["cloudSettings"],queryFn:()=>pe.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=lt({mutationFn:pe.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Jx,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(ty,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Aw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(B3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(ent,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Ie,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Ytt,{onSuccess:b,t})]}),i==="local"&&a.jsx(Ktt,{}),i==="kprofiles"&&a.jsx($tt,{}),a.jsx(Xtt,{})]})}const r0={Droplet:SP,Flame:Qp,Ruler:bbe,Sparkles:wx,Square:eo,Cable:cO,Wrench:zf,Calendar:Wr,Timer:Pc,Cog:rfe,Fan:hQ,Zap:Xl,Wind:PQ,Thermometer:PP,Layers:ea,Box:si,Target:_Q,RefreshCw:vr,Settings:Ow,Filter:kP,CircleDot:Ipe};function A0(t){return t&&r0[t]||zf}function Ob(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function u3(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 nnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":m?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function rnt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=A0(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:Ob(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(f,"days",i)}):i("maintenance.timeLeft",{duration:Ob(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ob(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ob(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||nnt(t.maintenance_type_name,t.printer_model);return f?a.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:y=>y.stopPropagation(),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Ln,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(rr,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Kr,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(Vn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(Ie,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(jo,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function ant({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(Dt,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Ln,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Kr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(Pc,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Ie,{size:"sm",onClick:y,children:s("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[a.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),a.jsx(Of,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=A0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Rt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(rnt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function int({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,k]=w.useState(!1),[P,N]=w.useState(""),[M,A]=w.useState("100"),[T,C]=w.useState("hours"),[F,$]=w.useState("Wrench"),[I,X]=w.useState(""),[L,te]=w.useState(new Set),[ae,ee]=w.useState(null),[me,le]=w.useState(null),ue=w.useMemo(()=>t?t.map(U=>({id:U.printer_id,name:U.printer_name})):[],[t]),K=U=>t?t.filter(R=>R.maintenance_items.some(re=>re.maintenance_type_id===U)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(re=>re.maintenance_type_id===U)?.id})):[],ne=U=>{if(!t)return[];const R=new Set(K(U).map(re=>re.printerId));return ue.filter(re=>!R.has(re.id))},[oe,be]=w.useState(null),[_e,B]=w.useState(""),[Y,D]=w.useState(""),[j,z]=w.useState("hours"),[W,q]=w.useState("Wrench"),[de,O]=w.useState(""),G=U=>{be(U),B(U.name),D(U.default_interval_hours.toString()),z(U.interval_type||"hours"),q(U.icon||"Wrench"),O(U.wiki_url||"")},Q=()=>{oe&&_e.trim()&&parseFloat(Y)>0&&(i(oe.id,{name:_e.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:W,wiki_url:de.trim()||null}),be(null))},V=(U,R,re)=>{const xe=parseFloat(y);if(!isNaN(xe)&&xe>0){const we=Math.abs(xe-R)<.01?null:xe;n(U,{custom_interval_hours:we,custom_interval_type:b!==re?b:null})}f(null)},J=U=>{U.preventDefault(),P.trim()&&parseFloat(M)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(M),interval_type:T,icon:F,wiki_url:I.trim()||null},Array.from(L)),N(""),A("100"),C("hours"),X(""),te(new Set),k(!1))},ie=U=>{te(R=>{const re=new Set(R);return re.has(U)?re.delete(U):re.add(U),re})},he=t?.map(U=>({printerId:U.printer_id,printerName:U.printer_name,items:U.maintenance_items.sort((R,re)=>R.maintenance_type_id-re.maintenance_type_id)})).sort((U,R)=>U.printerName.localeCompare(R.printerName))||[],fe=e.filter(U=>U.is_system),se=e.filter(U=>!U.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(Ie,{onClick:()=>k(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(ur,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(Dt,{className:"mb-6",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("form",{onSubmit:J,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:U=>N(U.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:T,onChange:U=>{C(U.target.value),U.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:T==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),a.jsx("input",{type:"number",value:M,onChange:U=>A(U.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(r0).map(U=>{const R=r0[U];return a.jsx("button",{type:"button",onClick:()=>$(U),className:`p-2 rounded-lg transition-colors ${F===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},U)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:I,onChange:U=>X(U.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map(U=>a.jsx("button",{type:"button",onClick:()=>ie(U.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(U.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:U.name},U.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>{k(!1),te(new Set)},children:m("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[fe.map(U=>{const R=A0(U.icon),re=U.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[re==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,re,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&le(U)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(un,{className:"w-4 h-4"})})]})},U.id)}),se.map(U=>{const R=A0(U.icon),re=U.interval_type||"hours";if(oe?.id===U.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:_e,onChange:ve=>B(ve.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:ve=>z(ve.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:ve=>D(ve.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(r0).map(ve=>{const Te=r0[ve];return a.jsx("button",{type:"button",onClick:()=>q(ve),className:`p-1.5 rounded transition-colors ${W===ve?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(Te,{className:"w-3.5 h-3.5"})},ve)})}),a.jsx("input",{type:"url",value:de,onChange:ve=>O(ve.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{size:"sm",onClick:Q,disabled:!_e.trim(),children:m("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},U.id);const we=K(U.id),ye=ne(U.id),Ae=ae===U.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[re==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,re,m)]})]}),a.jsxs("button",{onClick:()=>ee(Ae?null:U.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${we.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:we.length}),children:[a.jsx(Pr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:we.length}),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${Ae?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>G(U),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(Of,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:U.name}))&&s(U.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(un,{className:"w-4 h-4"})})]}),Ae&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),we.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:we.map(ve=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ve.printerName,a.jsx("button",{onClick:()=>ve.itemId&&d(ve.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},ve.printerId))}),ye.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ye.map(ve=>a.jsxs("button",{onClick:()=>c(ve.id,U.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",ve.name]},ve.id))]})]})]},U.id)})]})]}),he.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:he.map(U=>a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:U.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:U.items.map(R=>{const re=A0(R.maintenance_type_icon),xe=e.find(Te=>Te.id===R.maintenance_type_id),we=xe?.default_interval_hours||R.interval_hours,ye=xe?.interval_type||"hours",Ae=R.interval_type||"hours",ve=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(re,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),ve?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(Pc,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:Te=>g(Te.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:y,onChange:Te=>v(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&V(R.id,we,ye),Te.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),a.jsx(Ie,{size:"sm",onClick:()=>V(R.id,we,ye),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),g(Ae))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[Ae==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(R.interval_hours,Ae,m),a.jsx(Of,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},U.printerId))})]}),he.length===0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-12",children:[a.jsx(rr,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),me&&a.jsx(kn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:me.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(me.id),le(null)},onCancel:()=>le(null)})]})}function snt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=_r(),[i,s]=w.useState("status"),{data:o,isLoading:l}=et({queryKey:["maintenanceOverview"],queryFn:pe.getMaintenanceOverview}),{data:c}=et({queryKey:["maintenanceTypes"],queryFn:pe.getMaintenanceTypes}),d=lt({mutationFn:({id:M,notes:A})=>pe.performMaintenance(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),u=lt({mutationFn:({id:M,data:A})=>pe.updateMaintenanceItem(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),m=lt({mutationFn:({id:M,data:A})=>pe.updateMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),p=lt({mutationFn:pe.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),f=lt({mutationFn:pe.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),y=lt({mutationFn:({printerId:M,hours:A})=>pe.setPrinterHours(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=lt({mutationFn:({printerId:M,typeId:A})=>pe.assignMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),b=lt({mutationFn:pe.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),g=M=>{d.mutate({id:M})},_=(M,A)=>{u.mutate({id:M,data:{enabled:A}})},k=(M,A)=>{y.mutate({printerId:M,hours:A})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((M,A)=>M+A.due_count,0)||0,N=o?.reduce((M,A)=>M+A.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),a.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,A)=>{const T=M.due_count*10+M.warning_count,C=A.due_count*10+A.warning_count;return T!==C?C-T:M.printer_name.localeCompare(A.printer_name)}).map(M=>a.jsx(ant,{overview:M,onPerform:g,onToggle:_,onSetHours:k,hasPermission:r,t},M.printer_id)):a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-16",children:[a.jsx(zf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(int,{overview:o,types:c||[],onUpdateInterval:(M,A)=>u.mutate({id:M,data:A}),onAddType:async(M,A)=>{const T=await pe.createMaintenanceType(M);for(const C of A)await pe.assignMaintenanceType(C,T.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,A)=>m.mutate({id:M,data:A}),onDeleteType:M=>p.mutate(M),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(M,A)=>v.mutate({printerId:M,typeId:A}),onRemoveItem:M=>b.mutate(M),hasPermission:r,t})]})}const tX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function fle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||tX[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,k]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[M,A]=w.useState(t?.priority||"normal"),[T,C]=w.useState(t?.budget?.toString()||""),F=$=>{$.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:M,budget:T.trim()?parseFloat(T):null,...t&&{status:b}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:F,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:$=>l($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:$=>d($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:tX.map($=>a.jsx("button",{type:"button",onClick:()=>m($),className:`w-8 h-8 rounded-full transition-transform ${u===$?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:$}},$))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:$=>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:s("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:y,onChange:$=>v($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:$=>k($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:$=>N($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:M,onChange:$=>A($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:T,onChange:$=>C($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:b,onChange:$=>g($.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ont({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=w.useState(!1),f=c?{icon:Cc,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:Qs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:rr,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[a.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?a.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&a.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&a.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[a.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:a.jsx(Mh,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4"}),s("common.edit")]}),a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(un,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?a.jsx("img",{src:pe.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(Na,{className:"w-6 h-6"})}),y.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Ln,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(ea,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(Na,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(U3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function lnt(){const{t}=Lt(),e=Eo(),n=mn(),{showToast:r}=xn(),{hasPermission:i}=_r(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=et({queryKey:["settings"],queryFn:pe.getSettings}),y=yo(f?.currency||"USD"),{data:v,isLoading:b}=et({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>pe.getProjects(d==="all"?void 0:d)}),g=lt({mutationFn:te=>pe.createProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:te=>{r(te.message,"error")}}),_=lt({mutationFn:({id:te,data:ae})=>pe.updateProject(te,ae),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:te=>{r(te.message,"error")}}),k=lt({mutationFn:te=>pe.deleteProject(te),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:te=>{p(null),r(te.message,"error")}}),P=lt({mutationFn:te=>pe.importProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:te=>{r(te.message,"error")}}),N=w.useRef(null),M=async()=>{try{const te=await pe.getProjects(),ae=await Promise.all(te.map(async ue=>await pe.exportProjectJson(ue.id))),ee=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),me=URL.createObjectURL(ee),le=document.createElement("a");le.href=me,le.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,le.click(),URL.revokeObjectURL(me),r(t("projects.toast.exported"),"success")}catch(te){r(te.message,"error")}},A=()=>{N.current?.click()},T=async te=>{const ae=te.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await pe.importProjectFile(ae),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const me=await ae.text(),le=JSON.parse(me),ue=Array.isArray(le)?le:[le];for(const K of ue)await P.mutateAsync(K);ue.length>1&&r(t("projects.toast.multipleImported",{count:ue.length}),"success")}}catch(ee){r(`${t("projects.toast.importFailed")}: ${ee.message}`,"error")}te.target.value=""}},C=te=>{l?_.mutate({id:l.id,data:te}):g.mutate(te)},F=te=>{c(te),o(!0)},$=te=>{e(`/projects/${te.id}`)},I=te=>{p(te)},X=()=>{m!==null&&k.mutate(m)},L=v?.reduce((te,ae)=>(te[ae.status]=(te[ae.status]||0)+1,te.all=(te.all||0)+1,te),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:T,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(js,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:A,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Ie,{variant:"secondary",onClick:M,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Ie,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:rr},{key:"completed",label:t("projects.statusCompleted"),icon:Cc},{key:"archived",label:t("projects.statusArchived"),icon:Qs},{key:"all",label:t("common.all"),icon:js}].map(({key:te,label:ae,icon:ee})=>a.jsxs("button",{onClick:()=>u(te),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===te?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(ee,{className:"w-4 h-4"}),a.jsx("span",{children:ae}),L[te]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===te?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[te]})]},te))}),b?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(js,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&a.jsxs(Ie,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(te=>a.jsx(ont,{project:te,onClick:()=>$(te),onEdit:()=>F(te),onDelete:()=>I(te.id),hasPermission:i,t},te.id))}),m!==null&&a.jsx(kn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:X,onCancel:()=>p(null)}),s&&a.jsx(fle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function cnt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function dnt({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function nX({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function unt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Na,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>a.jsxs(vo,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?a.jsx("img",{src:pe.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(Na,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx($a,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mnt({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Ln,{className:"w-3 h-3"}),i]})}function m3(t,e){if(!t)return null;const n=Qn(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function hnt(){const{id:t}=Cw(),e=Eo(),{t:n}=Lt(),r=mn(),{showToast:i}=xn(),{hasPermission:s}=_r(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=et({queryKey:["project",p],queryFn:()=>pe.getProject(p),enabled:p>0}),{data:b,isLoading:g}=et({queryKey:["project-archives",p],queryFn:()=>pe.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:k}=et({queryKey:["project-bom",p],queryFn:()=>pe.getProjectBOM(p),enabled:p>0}),{data:P,isLoading:N}=et({queryKey:["project-timeline",p],queryFn:()=>pe.getProjectTimeline(p,20),enabled:p>0}),{data:M}=et({queryKey:["settings"],queryFn:pe.getSettings}),{data:A}=et({queryKey:["project-folders",p],queryFn:()=>pe.getLibraryFoldersByProject(p),enabled:p>0}),T=yo(M?.currency||"USD"),C=M?.time_format||"system",F=lt({mutationFn:Re=>pe.updateProject(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:Re=>{i(Re.message,"error")}}),$=()=>{m(f?.notes||""),d(!0)},I=()=>{F.mutate({notes:u})},X=()=>{d(!1),m("")},[L,te]=w.useState(""),[ae,ee]=w.useState(1),[me,le]=w.useState(""),[ue,K]=w.useState(""),[ne,oe]=w.useState(""),[be,_e]=w.useState(!1),[B,Y]=w.useState(!1),[D,j]=w.useState(null),[z,W]=w.useState(""),[q,de]=w.useState(1),[O,G]=w.useState(""),[Q,V]=w.useState(""),[J,ie]=w.useState(""),[he,fe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),se=lt({mutationFn:Re=>pe.createBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),te(""),ee(1),le(""),K(""),oe(""),_e(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:Re=>i(Re.message,"error")}),U=lt({mutationFn:({itemId:Re,data:Ye})=>pe.updateBOMItem(p,Re,Ye),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),j(null)},onError:Re=>i(Re.message,"error")}),R=lt({mutationFn:Re=>pe.deleteBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:Re=>i(Re.message,"error")}),re=Re=>{Re.preventDefault(),L.trim()&&se.mutate({name:L.trim(),quantity_needed:ae,unit_price:me?parseFloat(me):void 0,sourcing_url:ue.trim()||void 0,remarks:ne.trim()||void 0})},xe=Re=>{const Ye=Re.is_complete?0:Re.quantity_needed;U.mutate({itemId:Re.id,data:{quantity_acquired:Ye}})},we=(Re,Ye)=>{fe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ye}),onConfirm:()=>{fe(ce=>({...ce,isOpen:!1})),R.mutate(Re)}})},ye=Re=>{j(Re),W(Re.name),de(Re.quantity_needed),G(Re.unit_price?.toString()||""),V(Re.sourcing_url||""),ie(Re.remarks||"")},Ae=Re=>{Re.preventDefault(),!(!D||!z.trim())&&U.mutate({itemId:D.id,data:{name:z.trim(),quantity_needed:q,unit_price:O?parseFloat(O):void 0,sourcing_url:Q.trim()||void 0,remarks:J.trim()||void 0}})},ve=()=>{j(null)},Te=async()=>{try{const{blob:Re,filename:Ye}=await pe.exportProjectZip(Number(p)),ce=URL.createObjectURL(Re),ze=document.createElement("a");ze.href=ce,ze.download=Ye||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,ze.click(),URL.revokeObjectURL(ce),i(n("projectDetail.toast.projectExported"),"success")}catch(Re){i(Re.message,"error")}},Fe=lt({mutationFn:()=>pe.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:Re=>i(Re.message,"error")}),Ee=Re=>Bf(Re,C,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),a.jsx(Ie,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Se=f.stats,je=Se?.progress_percent??0,qe=Se?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(vo,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),a.jsx(Va,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:f.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(uQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),a.jsx(dnt,{status:f.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:Te,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Ie,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4 space-y-4",children:[f.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(je,100)}%`,backgroundColor:je>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:je.toFixed(0)})}),Se?.remaining_prints!=null&&Se.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_prints})})]})]}),f.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(qe,100)}%`,backgroundColor:qe>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:qe.toFixed(0)})}),Se?.remaining_parts!=null&&Se.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_parts})})]})]})]})}),Se&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(Na,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[Se.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Se.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Se.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Se.completed_prints})})]})]})})}),a.jsx(nX,{icon:rr,label:n("projectDetail.stats.printTime"),value:Wxe(Se.total_print_time_hours),color:"text-yellow-400"}),a.jsx(nX,{icon:Pr,label:n("projectDetail.stats.filamentUsed"),value:cnt(Se.total_filament_grams),color:"text-purple-400"})]}),Se&&(()=>{const Re=Se.estimated_cost+Se.total_energy_cost+Se.bom_cost;return Se.estimated_cost>0||Re>0||f.budget!==null})()&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[T,Se.estimated_cost.toFixed(2)]})]}),Se.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Se.total_energy_kwh.toFixed(3)," kWh",Se.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",T,Se.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Re=Se.estimated_cost+Se.total_energy_cost+Se.bom_cost;return Re<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[T,Re.toFixed(2)]}),Se.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const Re=Se.estimated_cost+Se.total_energy_cost+Se.bom_cost,Ye=f.budget-Re;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[T,f.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${Ye>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[T,Ye.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(Hfe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),a.jsx("div",{className:"space-y-2",children:f.children.map(Re=>a.jsxs(vo,{to:`/projects/${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Re.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:Re.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Re.status==="completed"?"bg-status-ok/20 text-status-ok":Re.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Re.status})]}),Re.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[Re.progress_percent.toFixed(0),"%"]})]},Re.id))})]})}),f.parent_id&&f.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(vo,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(mnt,{priority:f.priority,t:n})]}),f.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:Uf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),m3(f.due_date,n)&&a.jsxs("span",{className:`text-xs ${m3(f.due_date,n).color}`,children:["(",m3(f.due_date,n).label,")"]})]}),f.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gu,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((Re,Ye)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Re.trim()},Ye))})]})]}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:X,disabled:F.isPending,children:[a.jsx(Bt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Ie,{size:"sm",onClick:I,disabled:F.isPending,children:[F.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(cs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:$,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(FL,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:Bae.sanitize(f.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Fc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(vo,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),A&&A.length>0?a.jsx("div",{className:"space-y-2",children:A.map(Re=>a.jsxs(vo,{to:`/files?folder=${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Fc,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Re.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Re.file_count})})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Re.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(vQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Se&&Se.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Se.bom_completed_items,total:Se.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(Re=>Re.is_complete)&&a.jsx("button",{onClick:()=>Y(!B),className:`text-xs px-2 py-1 rounded transition-colors ${B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(B?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!be&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>_e(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),be&&a.jsxs("form",{onSubmit:re,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:L,onChange:Re=>te(Re.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ae,onChange:Re=>ee(parseInt(Re.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:me,onChange:Re=>le(Re.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:T})})]})]}),a.jsx("input",{type:"url",value:ue,onChange:Re=>K(Re.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:ne,onChange:Re=>oe(Re.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>_e(!1),children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!L.trim()||se.isPending,children:se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?a.jsxs("div",{className:"space-y-2",children:[_.filter(Re=>!B||!Re.is_complete).map(Re=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${Re.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:D?.id===Re.id?a.jsxs("form",{onSubmit:Ae,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:z,onChange:Ye=>W(Ye.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:q,onChange:Ye=>de(parseInt(Ye.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:O,onChange:Ye=>G(Ye.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:T})})]})]}),a.jsx("input",{type:"url",value:Q,onChange:Ye=>V(Ye.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:J,onChange:Ye=>ie(Ye.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:ve,children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!z.trim()||U.isPending,children:U.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&xe(Re),disabled:U.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${Re.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:Re.is_complete&&a.jsx(fr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${Re.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Re.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Re.quantity_needed]})]}),Re.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[T,(Re.unit_price*Re.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&ye(Re),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&we(Re.id,Re.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]}),Re.sourcing_url&&a.jsxs("a",{href:Re.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:Ye=>Ye.stopPropagation(),children:[a.jsx(sa,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Re.sourcing_url).hostname.replace("www.","")}catch{return Re.sourcing_url}})()})]}),Re.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Re.remarks})]})]})},Re.id)),Se&&Se.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[T,Se.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(L0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),N?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):P&&P.length>0?a.jsx("div",{className:"space-y-3",children:P.slice(0,10).map((Re,Ye)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${Re.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Re.event_type==="print_failed"?"bg-status-error/20 text-status-error":Re.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Re.event_type==="print_completed"&&a.jsx(fr,{className:"w-4 h-4"}),Re.event_type==="print_failed"&&a.jsx($a,{className:"w-4 h-4"}),Re.event_type==="print_started"&&a.jsx(Pr,{className:"w-4 h-4"}),Re.event_type==="queued"&&a.jsx(U3,{className:"w-4 h-4"}),Re.event_type==="project_created"&&a.jsx(ur,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:Re.title}),Re.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Re.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ee(Re.timestamp)})]})]},Ye))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Fe.mutate(),disabled:Fe.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Fe.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Mo,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Se&&(Se.queued_prints>0||Se.in_progress_prints>0)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(U3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(vo,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Se.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Se.in_progress_prints})}),Se.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Se.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(unt,{archives:b||[],t:n})]}),o&&a.jsx(fle,{t:n,currencySymbol:T,project:{...f,archive_count:Se?.total_archives||0,total_items:Se?.total_items||0,completed_count:Se?.completed_prints||0,failed_count:Se?.failed_prints||0,queue_count:Se?.queued_prints||0,progress_percent:Se?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Re=>F.mutate(Re),isLoading:F.isPending}),he.isOpen&&a.jsx(kn,{title:he.title,message:he.message,confirmText:n("common.delete"),variant:"danger",onConfirm:he.onConfirm,onCancel:()=>fe(Re=>({...Re,isOpen:!1}))})]})}function pnt({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function fnt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function gnt({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.jsx("input",{type:"text",value:c,onChange:m=>d(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function bnt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...d(y.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Fc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ie,{onClick:()=>i(l),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function xnt({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:d}=et({queryKey:["projects"],queryFn:()=>pe.getProjects()}),{data:u}=et({queryKey:["archives-for-link"],queryFn:()=>pe.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Lu,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(mQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(Qs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:y.name})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(yf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(Ie,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(qh,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{onClick:m,disabled:!l||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function gle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:d}){const[u,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id,b=t.is_external;return a.jsxs("div",{children:[a.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[y?a.jsx("button",{onClick:g=>{g.stopPropagation(),m(!u)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Va,{className:`w-3.5 h-3.5 transition-transform ${u?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),b?a.jsx(tN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Fc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:g=>{g.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[a.jsx(Lu,{className:"w-3 h-3"}),t.project_name?a.jsx(mQ,{className:"w-3 h-3"}):a.jsx(Qs,{className:"w-3 h-3"})]}),b&&t.external_readonly&&a.jsx("span",{title:d("fileManager.readOnly"),children:a.jsx(ld,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&!b&&a.jsx("button",{onClick:g=>{g.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:d("fileManager.linkToProjectOrArchive"),children:a.jsx(Lu,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Mh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionRenameFolder"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),d("common.rename")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(i(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionLinkFolder"),children:[a.jsx(Lu,{className:"w-3.5 h-3.5"}),d(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:d("fileManager.noPermissionDeleteFolder"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),d("common.delete")]})]})]})]})})]}),y&&u&&a.jsx("div",{children:t.children.map(g=>a.jsx(gle,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:d},g.id))})]})}function HL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function ynt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return a.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${pe.getLibraryFileThumbnailUrl(t.id)}${m?(pe.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/30"}),a.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:_o(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Wu,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Mh,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Pr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(si,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(va,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(Vu,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function vnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=_r(),[l]=eO(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(!1),[M,A]=w.useState(null),[T,C]=w.useState(null),[F,$]=w.useState(null),[I,X]=w.useState(null),[L,te]=w.useState(null),[ae,ee]=w.useState(null),[me,le]=w.useState({}),[ue,K]=w.useState(null),[ne,oe]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[be,_e]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[B,Y]=w.useState(()=>{const Ke=localStorage.getItem("library-sidebar-width");return Ke?parseInt(Ke,10):256}),[D,j]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{if(!D)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ke=Nt=>{if(!z.current)return;const ht=z.current.parentElement?.getBoundingClientRect();if(!ht)return;const Mt=Nt.clientX-ht.left,Qt=Math.min(500,Math.max(200,Mt));Y(Qt)},Ft=()=>{j(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(B))};return document.addEventListener("mousemove",Ke),document.addEventListener("mouseup",Ft),()=>{document.removeEventListener("mousemove",Ke),document.removeEventListener("mouseup",Ft),document.body.style.userSelect="",document.body.style.cursor=""}},[D,B]);const[W,q]=w.useState(""),[de,O]=w.useState("all"),[G,Q]=w.useState(""),[V,J]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ie,he]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),fe=Eae();w.useEffect(()=>{const Ke=l.get("folder");if(Ke){const Ft=parseInt(Ke,10);m(Ft)}},[l]);const{data:se}=et({queryKey:["settings"],queryFn:()=>pe.getSettings()}),{data:U,isLoading:R}=et({queryKey:["library-folders"],queryFn:()=>pe.getLibraryFolders()}),{data:re,isLoading:xe}=et({queryKey:["library-files",u],queryFn:()=>pe.getLibraryFiles(u,u===null)}),{data:we}=et({queryKey:["library-stats"],queryFn:()=>pe.getLibraryStats()}),{data:ye}=et({queryKey:["users"],queryFn:()=>pe.getUsers()}),Ae=w.useMemo(()=>{if(!re)return[];const Ke=new Set(re.map(Ft=>Ft.file_type));return Array.from(Ke).sort()},[re]),ve=w.useMemo(()=>{if(!re)return[];let Ke=[...re];if(W.trim()){const Ft=W.toLowerCase();Ke=Ke.filter(Nt=>Nt.filename.toLowerCase().includes(Ft)||Nt.print_name&&Nt.print_name.toLowerCase().includes(Ft))}if(de!=="all"&&(Ke=Ke.filter(Ft=>Ft.file_type===de)),G.trim()){const Ft=G.toLowerCase();Ke=Ke.filter(Nt=>Nt.created_by_username&&Nt.created_by_username.toLowerCase().includes(Ft))}return Ke.sort((Ft,Nt)=>{let ht=0;switch(V){case"name":ht=(Ft.print_name||Ft.filename).localeCompare(Nt.print_name||Nt.filename);break;case"date":ht=(Qn(Ft.created_at)?.getTime()??0)-(Qn(Nt.created_at)?.getTime()??0);break;case"size":ht=Ft.file_size-Nt.file_size;break;case"type":ht=Ft.file_type.localeCompare(Nt.file_type);break;case"prints":ht=Ft.print_count-Nt.print_count;break}return ie==="asc"?ht:-ht}),Ke},[re,W,de,G,V,ie]),Te=w.useMemo(()=>{if(!we||!se)return!1;const Ke=(se.library_disk_warning_gb||5)*1024*1024*1024;return we.disk_free_bytes<Ke},[we,se]),Fe=lt({mutationFn:Ke=>pe.createLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ke=>n(Ke.message,"error")}),Ee=lt({mutationFn:async Ke=>{const Ft=await pe.createExternalFolder(Ke);return await pe.scanExternalFolder(Ft.id),Ft},onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),g(!1),m(Ke.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),Se=lt({mutationFn:Ke=>pe.scanExternalFolder(Ke),onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:Ke.added,removed:Ke.removed}),"success")},onError:Ke=>n(Ke.message,"error")}),je=lt({mutationFn:Ke=>pe.deleteLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===T?.id&&m(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ke=>{C(null),n(Ke.message,"error")}}),qe=lt({mutationFn:Ke=>pe.deleteLibraryFile(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(Ke=>Ke.filter(Ft=>Ft!==T?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ke=>{C(null),n(Ke.message,"error")}}),Re=lt({mutationFn:Ke=>pe.bulkDeleteLibrary(Ke,[]),onSuccess:(Ke,Ft)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Ft.length}),"success"),f([]),C(null)},onError:Ke=>{C(null),n(Ke.message,"error")}}),Ye=lt({mutationFn:({fileIds:Ke,folderId:Ft})=>pe.moveLibraryFiles(Ke,Ft),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),k(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ke=>n(Ke.message,"error")}),ce=lt({mutationFn:({id:Ke,data:Ft})=>pe.updateLibraryFolder(Ke,Ft),onSuccess:(Ke,Ft)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const Nt=Ft.data.project_id===0&&Ft.data.archive_id===0;n(t(Nt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),ze=lt({mutationFn:({id:Ke,filename:Ft})=>pe.updateLibraryFile(Ke,{filename:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ke=>{ee(null),n(Ke.message,"error")}}),Ne=lt({mutationFn:({id:Ke,name:Ft})=>pe.updateLibraryFolder(Ke,{name:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ke=>{ee(null),n(Ke.message,"error")}}),Ge=lt({mutationFn:()=>pe.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const Ft=Date.now(),Nt={};Ke.results.forEach(ht=>{ht.success&&(Nt[ht.file_id]=Ft)}),le(ht=>({...ht,...Nt}))}Ke.succeeded>0&&Ke.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ke.succeeded}),"success"):Ke.succeeded>0&&Ke.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ke.succeeded,failed:Ke.failed}),"success"):Ke.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),$e=lt({mutationFn:Ke=>pe.batchGenerateStlThumbnails({file_ids:[Ke]}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const Ft=Ke.results[0]?.file_id;Ft&&le(Nt=>({...Nt,[Ft]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),Pe=w.useCallback(Ke=>{const Ft=Ke.toLowerCase();return Ft.endsWith(".gcode")||Ft.includes(".gcode.")},[]),Me=w.useMemo(()=>re?re.filter(Ke=>p.includes(Ke.id)&&Pe(Ke.filename)):[],[re,p,Pe]),Ve=w.useCallback(Ke=>{f(Ft=>Ft.includes(Ke)?Ft.filter(Nt=>Nt!==Ke):[...Ft,Ke])},[]),tt=w.useCallback(()=>{ve.length>0&&f(ve.map(Ke=>Ke.id))},[ve]),ut=w.useCallback(()=>{f([])},[]),xt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},wt=Ke=>{pe.downloadLibraryFile(Ke).catch(Ft=>{console.error("Library file download failed:",Ft)})},Ht=()=>{T&&(T.type==="file"?qe.mutate(T.id):T.type==="folder"?je.mutate(T.id):T.type==="bulk"&&Re.mutate(p))},Xt=je.isPending||qe.isPending||Re.isPending,Kt=Ke=>{oe(Ke),localStorage.setItem("library-view-mode",Ke)},Ut=R||xe,en=w.useMemo(()=>{if(!u||!U)return null;const Ke=Ft=>{for(const Nt of Ft){if(Nt.id===u)return Nt;const ht=Ke(Nt.children);if(ht)return ht}return null};return Ke(U)},[u,U]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Fc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${ne==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(jw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${ne==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>Ge.mutate(),disabled:Ge.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Ge.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(Vu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(tN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(zfe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Te&&we&&se&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Ln,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:_o(we.disk_free_bytes),total:_o(we.disk_total_bytes),threshold:se.library_disk_warning_gb})})]})]}),we&&a.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(_P,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:we.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Fc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:we.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ty,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:_o(we.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${Te?"text-amber-500":"text-white"}`,children:_o(we.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:Ke=>m(Ke.target.value?parseInt(Ke.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),U&&(()=>{const Ke=(Ft,Nt=0)=>{const ht=[];for(const Mt of Ft)ht.push({id:Mt.id,name:Mt.name,fileCount:Mt.file_count,depth:Nt}),Mt.children.length>0&&ht.push(...Ke(Mt.children,Nt+1));return ht};return Ke(U).map(Ft=>a.jsxs("option",{value:Ft.id,children:["│ ".repeat(Ft.depth),"📂 ",Ft.name," ",Ft.fileCount>0?`(${Ft.fileCount})`:""]},Ft.id))})()]})}),a.jsxs("div",{ref:z,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:`${B}px`},children:[a.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${D?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ke=>{Ke.preventDefault(),j(!0)},onDoubleClick:()=>{Y(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${D?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const Ke=!be;_e(Ke),localStorage.setItem("library-wrap-folders",String(Ke))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${be?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(be?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(yf,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),U?.map(Ke=>a.jsx(gle,{folder:Ke,selectedFolderId:u,onSelect:m,onDelete:Ft=>C({type:"folder",id:Ft}),onLink:A,onRename:Ft=>ee({type:"folder",id:Ft.id,name:Ft.name}),wrapNames:be,hasPermission:r,t},Ke.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[en?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(tN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),en.external_readonly&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[a.jsx(ld,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:en.external_path||"",children:en.external_path})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>u&&Se.mutate(u),disabled:Se.isPending,title:t("fileManager.scanFolder"),children:[Se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),re&&re.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:W,onChange:Ke=>q(Ke.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:de,onChange:Ke=>O(Ke.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Ae.map(Ke=>a.jsx("option",{value:Ke,children:Ke.toUpperCase()},Ke))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:G,onChange:Ke=>Q(Ke.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 ${G?"pr-7":""}`,style:G?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),G&&a.jsx("button",{onClick:()=>Q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Bt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(Ke=>a.jsx("option",{value:Ke.username},Ke.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:V,onChange:Ke=>{const Ft=Ke.target.value;J(Ft),localStorage.setItem("library-sort-field",Ft)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>he(Ke=>{const Ft=Ke==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ft),Ft}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ie==="asc"?"fileManager.ascending":"fileManager.descending"),children:ie==="asc"?a.jsx(Jhe,{className:"w-4 h-4 text-white"}):a.jsx(Ghe,{className:"w-4 h-4 text-white"})})]}),(W||de!=="all"||G)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:ve.length,total:re.length})})]}),ve.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[p.length===ve.length&&p.length>0?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(eo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:tt,children:[a.jsx(us,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Me.length===1&&a.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>X(Me[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(Ds,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Me.length===1&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>te(Me[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>k(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(Yge,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>{p.length===1?C({type:"file",id:p[0]}):C({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(un,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(Bt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ut?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):re?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):ve.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Sr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Ie,{variant:"secondary",onClick:()=>{q(""),O("all")},children:t("fileManager.clearFilters")})]}):ne==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:ve.map(Ke=>a.jsx(ynt,{file:Ke,isSelected:p.includes(Ke.id),isMobile:fe,t,onSelect:Ve,onDelete:Ft=>C({type:"file",id:Ft}),onDownload:wt,onAddToQueue:Ft=>{const Nt=re?.find(ht=>ht.id===Ft);Nt&&te(Nt)},onPrint:$,onPreview3d:K,onRename:Ft=>ee({type:"file",id:Ft.id,name:Ft.filename}),onGenerateThumbnail:Ft=>$e.mutate(Ft.id),thumbnailVersion:me[Ke.id],hasPermission:r,canModify:s,authEnabled:o},Ke.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),ve.map(Ke=>a.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${p.includes(Ke.id)?"bg-bambu-green/10":""}`,onClick:()=>Ve(Ke.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ke.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ke.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ke.thumbnail_path?a.jsx("img",{src:`${pe.getLibraryFileThumbnailUrl(Ke.id)}${me[Ke.id]?(pe.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${me[Ke.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(yf,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ke.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${pe.getLibraryFileThumbnailUrl(Ke.id)}${me[Ke.id]?(pe.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${me[Ke.id]}`:""}`,alt:Ke.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Ke.print_name||Ke.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ke.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(Wu,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ke.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ke.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ke.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ke.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ke.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:_o(Ke.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ke.print_count>0?`${Ke.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:Ft=>Ft.stopPropagation(),children:[HL(Ke.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&$(Ke),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Pr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&te(Ke)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(rr,{className:"w-4 h-4"})})]}),(Ke.file_type==="3mf"||Ke.file_type==="gcode"||Ke.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&K(Ke),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(si,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&wt(Ke.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&ee({type:"file",id:Ke.id,name:Ke.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ke.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ke.created_by_id),children:a.jsx(Za,{className:"w-4 h-4"})}),Ke.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&$e.mutate(Ke.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.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",Ke.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:$e.isPending||!s("library","update",Ke.created_by_id),children:a.jsx(Vu,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ke.created_by_id)&&C({type:"file",id:Ke.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ke.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",Ke.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ke.created_by_id),children:a.jsx(un,{className:"w-4 h-4"})})]})]},Ke.id))]})})]})]}),y&&a.jsx(pnt,{parentId:u,onClose:()=>v(!1),onSave:Ke=>Fe.mutate(Ke),isLoading:Fe.isPending,t}),b&&a.jsx(fnt,{onClose:()=>g(!1),onSave:Ke=>Ee.mutate(Ke),isLoading:Ee.isPending,t}),_&&U&&a.jsx(bnt,{folders:U,selectedFiles:p,currentFolderId:u,onClose:()=>k(!1),onMove:Ke=>Ye.mutate({fileIds:p,folderId:Ke}),isLoading:Ye.isPending,t}),P&&a.jsx(kae,{folderId:u,onClose:()=>N(!1),onUploadComplete:xt}),M&&a.jsx(xnt,{folder:M,onClose:()=>A(null),onLink:Ke=>ce.mutate({id:M.id,data:Ke}),isLoading:ce.isPending,t}),T&&a.jsx(kn,{title:T.type==="folder"?t("fileManager.deleteFolder"):T.type==="bulk"?t("fileManager.deleteFilesCount",{count:T.count}):t("fileManager.deleteFile"),message:T.type==="folder"?t("fileManager.deleteFolderConfirm"):T.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:T.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Xt,loadingText:t("fileManager.deleting"),onConfirm:Ht,onCancel:()=>C(null)}),F&&a.jsx(kd,{mode:"reprint",libraryFileId:F.id,archiveName:F.print_name||F.filename,onClose:()=>$(null),onSuccess:()=>{$(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),I&&a.jsx(kd,{mode:"reprint",libraryFileId:I.id,archiveName:I.print_name||I.filename,onClose:()=>X(null),onSuccess:()=>{X(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(kd,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>te(null),onSuccess:()=>{te(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&a.jsx(ez,{libraryFileId:ue.id,title:ue.print_name||ue.filename,fileType:ue.file_type,onClose:()=>K(null)}),ae&&a.jsx(gnt,{type:ae.type,currentName:ae.name,onClose:()=>ee(null),onSave:Ke=>{ae.type==="file"?ze.mutate({id:ae.id,filename:Ke}):Ne.mutate({id:ae.id,name:Ke})},isLoading:ze.isPending||Ne.isPending,t})]})}const fk=5,wnt=2e3,Snt=3e4,_nt=5e3;function knt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=_r(),{printerId:i}=Cw(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(0),[M,A]=w.useState(!1),[T,C]=w.useState(0),[F,$]=w.useState(1),[I,X]=w.useState({x:0,y:0}),[L,te]=w.useState(!1),[ae,ee]=w.useState({x:0,y:0}),[me,le]=w.useState(null),[ue,K]=w.useState(null),ne=w.useRef(null),oe=w.useRef(null),be=w.useRef(null),_e=w.useRef(null),B=w.useRef(null),{data:Y}=et({queryKey:["printer",s],queryFn:()=>pe.getPrinter(s),enabled:s>0}),{data:D}=et({queryKey:["printerStatus",s],queryFn:()=>pe.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),j=lt({mutationFn:Se=>pe.setChamberLight(s,Se),onMutate:async Se=>{await e.cancelQueries({queryKey:["printerStatus",s]});const je=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],qe=>({...qe,chamber_light:Se})),{previousStatus:je}},onSuccess:(Se,je)=>{n(`Chamber light ${je?"on":"off"}`)},onError:(Se,je,qe)=>{qe?.previousStatus&&e.setQueryData(["printerStatus",s],qe.previousStatus),n(Se.message||t("printers.toast.failedToControlChamberLight"),"error")}}),z=(D?.state==="RUNNING"||D?.state==="PAUSE")&&(D?.printable_objects_count??0)>=2;w.useEffect(()=>(Y&&(document.title=`${Y.name} - Camera`),()=>{document.title="Bambuddy"}),[Y]);const W=w.useRef(!1);w.useEffect(()=>{const Se=`/api/v1/printers/${s}/camera/stop`;W.current=!1;const je=()=>{if(s>0&&!W.current){W.current=!0;const Ye={},ce=Yu();ce&&(Ye.Authorization=`Bearer ${ce}`),fetch(Se,{method:"POST",keepalive:!0,headers:Ye}).catch(()=>{})}},qe=()=>{je()};window.addEventListener("beforeunload",qe);const Re=ne.current;return()=>{window.removeEventListener("beforeunload",qe),Re&&(Re.src=""),je()}},[s]),w.useEffect(()=>{if(p&&!b){const je=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(je)}},[o,p,y,b]),w.useEffect(()=>{const Se=()=>{const je=!!document.fullscreenElement;k(je),$(1),X({x:0,y:0}),o==="stream"&&!b&&(ne.current&&(ne.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Se),()=>document.removeEventListener("fullscreenchange",Se)},[o,b]),w.useEffect(()=>{let Se;const je=()=>{clearTimeout(Se),Se=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",je),()=>{clearTimeout(Se),window.removeEventListener("resize",je)}},[]),w.useEffect(()=>()=>{be.current&&clearTimeout(be.current),_e.current&&clearInterval(_e.current),B.current&&clearInterval(B.current)},[]);const q=w.useCallback(()=>{if(P>=fk){A(!1),m(!0);return}const Se=Math.min(wnt*Math.pow(2,P),Snt);A(!0),C(Math.ceil(Se/1e3)),_e.current=setInterval(()=>{C(je=>je<=1?(_e.current&&clearInterval(_e.current),0):je-1)},1e3),be.current=setTimeout(()=>{N(je=>je+1),A(!1),f(!0),m(!1),ne.current&&(ne.current.src=""),v(Date.now())},Se)},[P]);w.useEffect(()=>{if(o!=="stream"||p||M||b){B.current&&(clearInterval(B.current),B.current=null);return}return B.current=setInterval(async()=>{try{const Se=await pe.getCameraStatus(s);(Se.stalled||!Se.active&&!u)&&(console.log(`Stream issue detected: stalled=${Se.stalled}, active=${Se.active}, reconnecting...`),B.current&&(clearInterval(B.current),B.current=null),f(!1),q())}catch{}},_nt),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[o,p,u,M,b,s,q]);const de=()=>{f(!1),o==="stream"&&P<fk?q():m(!0)},O=()=>{if(f(!1),m(!1),N(0),A(!1),be.current&&clearTimeout(be.current),_e.current&&clearInterval(_e.current),ne.current&&!localStorage.getItem("cameraWindowState")){const Se=ne.current,je=Se.naturalWidth,qe=Se.naturalHeight;if(je>0&&qe>0){const ce=window.outerWidth-window.innerWidth,ze=window.outerHeight-window.innerHeight,Ne=je+16+ce,Ge=qe+45+16+ze;try{window.resizeTo(Ne,Ge)}catch{}}}},G=()=>{if(s>0){const Se={},je=Yu();je&&(Se.Authorization=`Bearer ${je}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Se}).catch(()=>{})}},Q=Se=>{o===Se||b||(g(!0),f(!0),m(!1),N(0),A(!1),$(1),X({x:0,y:0}),be.current&&clearTimeout(be.current),_e.current&&clearInterval(_e.current),ne.current&&(ne.current.src=""),o==="stream"&&G(),setTimeout(()=>{l(Se),v(Date.now()),g(!1)},100))},V=()=>{b||(g(!0),f(!0),m(!1),N(0),A(!1),be.current&&clearTimeout(be.current),_e.current&&clearInterval(_e.current),ne.current&&(ne.current.src=""),o==="stream"&&G(),setTimeout(()=>{v(Date.now()),g(!1)},100))},J=()=>{oe.current&&(document.fullscreenElement?document.exitFullscreen():oe.current.requestFullscreen())},ie=()=>{$(Se=>Math.min(Se+.5,4))},he=()=>{$(Se=>{const je=Math.max(Se-.5,1);return je===1&&X({x:0,y:0}),je})},fe=Se=>{Se.preventDefault(),Se.deltaY<0?ie():he()},se=Se=>{F>1&&(Se.preventDefault(),te(!0),ee({x:Se.clientX-I.x,y:Se.clientY-I.y}))},U=w.useCallback(()=>{if(!oe.current)return{x:300,y:200};const Se=oe.current.getBoundingClientRect(),je=Se.width*(F-1)/2,qe=Se.height*(F-1)/2;return{x:Math.max(50,je),y:Math.max(50,qe)}},[F]),R=Se=>{if(L&&F>1){const je=Se.clientX-ae.x,qe=Se.clientY-ae.y,Re=U();X({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,qe))})}},re=()=>{te(!1)},xe=Se=>{if(Se.length<2)return 0;const je=Se[0].clientX-Se[1].clientX,qe=Se[0].clientY-Se[1].clientY;return Math.sqrt(je*je+qe*qe)},we=Se=>Se.length<2?{x:Se[0].clientX,y:Se[0].clientY}:{x:(Se[0].clientX+Se[1].clientX)/2,y:(Se[0].clientY+Se[1].clientY)/2},ye=Se=>{Se.touches.length===2?(Se.preventDefault(),le(xe(Se.touches)),K(we(Se.touches))):Se.touches.length===1&&F>1&&(Se.preventDefault(),te(!0),ee({x:Se.touches[0].clientX-I.x,y:Se.touches[0].clientY-I.y}))},Ae=Se=>{if(Se.touches.length===2&&me!==null){Se.preventDefault();const je=xe(Se.touches),qe=je/me;$(Ye=>{const ce=Math.max(1,Math.min(4,Ye*qe));return ce===1&&X({x:0,y:0}),ce}),le(je);const Re=we(Se.touches);if(ue){const Ye=U();X(ce=>({x:Math.max(-Ye.x,Math.min(Ye.x,ce.x+(Re.x-ue.x))),y:Math.max(-Ye.y,Math.min(Ye.y,ce.y+(Re.y-ue.y)))}))}K(Re)}else if(Se.touches.length===1&&L&&F>1){Se.preventDefault();const je=Se.touches[0].clientX-ae.x,qe=Se.touches[0].clientY-ae.y,Re=U();X({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,qe))})}},ve=Se=>{Se.touches.length<2&&(le(null),K(null)),Se.touches.length===0&&te(!1)},Te=()=>{$(1),X({x:0,y:0})},Fe=b?"":Ra(o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`),Ee=p||b||M;return s?a.jsxs("div",{ref:oe,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(yx,{className:"w-4 h-4"}),Y?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>Q("stream"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>Q("snapshot"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>j.mutate(!D?.chamber_light),disabled:!D?.connected||j.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${D?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(YO,{on:D?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>d(!0),disabled:!z||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${z&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(z?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(zP,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:V,disabled:Ee,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(vr,{className:`w-4 h-4 text-bambu-gray ${Ee?"animate-spin":""}`})}),a.jsx("button",{onClick:J,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?a.jsx(bQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Ige,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:fe,onMouseMove:R,onMouseUp:re,onMouseLeave:re,onTouchStart:ye,onTouchMove:Ae,onTouchEnd:ve,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(vr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Ku,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:T,attempt:Math.min(P+1,fk),max:fk})}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),u&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Ln,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:ne,src:Fe,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${F}) translate(${I.x/F}px, ${I.y/F}px) rotate(${Y?.camera_rotation||0}deg)`,...Y?.camera_rotation===90||Y?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:F>1?L?"grabbing":"grab":"default"},onError:Fe?de:void 0,onLoad:Fe?O:void 0,onMouseDown:se,draggable:!1},y),a.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[a.jsx("button",{onClick:he,disabled:F<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(xO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:Te,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(F*100),"%"]}),a.jsx("button",{onClick:ie,disabled:F>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(bO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(XO,{printerId:s,isOpen:c,onClose:()=>d(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Nnt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function Cnt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Pnt(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 Tnt(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 Ant(){const{printerId:t}=Cw(),[e]=eO(),{t:n}=Lt(),r=mn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>Cnt(e),[e]),c=Tnt(l.size),{data:d}=et({queryKey:["printer",i],queryFn:()=>pe.getPrinter(i),enabled:i>0}),{data:u}=et({queryKey:["printerStatus",i],queryFn:()=>pe.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=et({queryKey:["settings"],queryFn:pe.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(_);return k.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},k.onerror=()=>{},()=>{k.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Ra(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src: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),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Pr,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Nnt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Pnt(u,n)}),l.showProgress&&y&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&a.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(ea,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Pc,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ls(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(rr,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",vO(u.remaining_time,p,n)]})]})]})]}),!y&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Mnt(){const{t}=Lt(),{id:e}=Cw(),{mode:n}=cg(),{data:r,isLoading:i,error:s}=et({queryKey:["external-link",e],queryFn:()=>pe.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Ln,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function rX(){const{id:t}=Cw(),e=Eo(),n=mn(),{t:r}=Lt(),{showToast:i}=xn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=et({queryKey:["group",t],queryFn:()=>pe.getGroup(Number(t)),enabled:s}),{data:_,isLoading:k}=et({queryKey:["permissions"],queryFn:()=>pe.getPermissions()});s&&b&&!y&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=lt({mutationFn:ee=>pe.createGroup(ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),N=lt({mutationFn:ee=>pe.updateGroup(Number(t),ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),M=P.isPending||N.isPending,A=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},T=ee=>{m(me=>me.includes(ee)?me.filter(le=>le!==ee):[...me,ee])},C=(ee,me)=>{const le=ee.permissions.map(ue=>ue.value);m(ue=>{const K=ue.filter(ne=>!le.includes(ne));return me?[...K,...le]:K})},F=ee=>ee.permissions.every(me=>u.includes(me.value)),$=ee=>{const me=ee.permissions.filter(le=>u.includes(le.value)).length;return me>0&&me<ee.permissions.length},I=()=>{_&&m(_.all_permissions)},X=()=>{m([])},L=p.toLowerCase(),te=w.useMemo(()=>_?L?_.categories.map(ee=>({...ee,permissions:ee.permissions.filter(me=>me.label.toLowerCase().includes(L))})).filter(ee=>ee.permissions.length>0):_.categories:[],[_,L]),ae=_?.all_permissions.length??0;return g||k?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:a.jsx(uQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&a.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[a.jsx(Ln,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:ee=>l(ee.target.value),disabled:s&&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:r("groups.form.groupNamePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:ee=>d(ee.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ae]}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:I,children:r("groups.editor.selectAll")}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:X,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:ee=>f(ee.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),te.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:te.map(ee=>{const me=_.categories.find(oe=>oe.name===ee.name),le=me.permissions.filter(oe=>u.includes(oe.value)).length,ue=me.permissions.length,K=F(me),ne=$(me);return a.jsxs(Dt,{children:[a.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>C(me,!K),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${K?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[K&&a.jsx(Kr,{className:"w-3 h-3 text-white"}),ne&&!K&&a.jsx(rN,{className:"w-3 h-3 text-white"})]}),a.jsx(Wb,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:ee.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[le,"/",ue]})]}),a.jsx("div",{className:"p-3 space-y-1",children:ee.permissions.map(oe=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(oe.value),onChange:()=>T(oe.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:oe.label})]},oe.value))})]},ee.name)})}),a.jsx("div",{className:"h-16"}),a.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(Ie,{onClick:A,disabled:M||!o.trim(),children:M?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const qL={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function ble(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const xle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],jnt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],M0=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],yle=[{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"}],Ent=[{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"}],aX=[...yle,...Ent],vle="bambuddy-recent-colors",Dnt=8,Fnt=[{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 Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of M0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of M0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function wle(t,e){const n=new Set(jnt);for(const r of t){const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function Rnt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Sle(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Rnt(n);if(r.length>0)return r}return Fnt}function _le(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function kle(){try{const t=localStorage.getItem(vle);if(t)return JSON.parse(t)}catch{}return[]}function Nle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Dnt);try{localStorage.setItem(vle,JSON.stringify(r))}catch{}return r}function h3(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(r);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Cle({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Lt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[A,T]=w.useState(""),[C,F]=w.useState(""),[$,I]=w.useState(""),[X,L]=w.useState(String(t.label_weight)),[te,ae]=w.useState(!1),ee=w.useRef(null),me=w.useRef(null),le=w.useRef(null),ue=w.useRef(null);w.useEffect(()=>{const B=Y=>{ee.current&&!ee.current.contains(Y.target)&&b(!1),ue.current&&!ue.current.contains(Y.target)&&M(!1),me.current&&!me.current.contains(Y.target)&&_(!1),le.current&&!le.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const K=w.useMemo(()=>{if(!i)return l;const B=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes(B)||Y.code.toLowerCase().includes(B))},[l,i]),ne=w.useMemo(()=>{if(!A)return c;const B=A.toLowerCase();return c.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[c,A]),oe=w.useMemo(()=>{if(!C)return M0;const B=C.toLowerCase();return M0.filter(Y=>Y.toLowerCase().includes(B))},[C]),be=w.useMemo(()=>{if(!$)return d;const B=$.toLowerCase();return d.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[$,d]);w.useEffect(()=>{te||L(String(t.label_weight))},[t.label_weight,te]);const _e=B=>{e("slicer_filament",B.code),s(B.displayName),b(!1);const Y=Jh(B.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(Jx,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(Wpe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:ee,children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchPresets"),value:i,onChange:B=>{s(B.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:K.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):K.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===B.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>_e(B),children:B.displayName},B.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:ue,children:[a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.selectMaterial"),value:N?$:t.material,onChange:B=>{I(B.target.value),M(!0)},onFocus:()=>{M(!0),I("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[be.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",B),M(!1),I("")},children:B},B)),$&&!be.includes($)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",$),M(!1),I("")},children:y("inventory.useCustomMaterial",{material:$})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:me,children:[a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchBrand"),value:g?A:t.brand,onChange:B=>{T(B.target.value),_(!0)},onFocus:()=>{_(!0),T("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ne.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):ne.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",B),_(!1),T("")},children:B},B)),A&&!ne.includes(A)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",A),_(!1),T("")},children:y("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:le,children:[a.jsx("input",{type:"text",value:k?C:t.subtype,onChange:B=>{F(B.target.value),P(!0)},onFocus:()=>{P(!0),F("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[oe.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):oe.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",B),P(!1),F("")},children:B},B)),C&&!M0.some(B=>B.toLowerCase()===C.toLowerCase().trim())&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",C),P(!1),F("")},children:y("inventory.useCustomBrand",{brand:C})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:X,min:0,onFocus:()=>ae(!0),onChange:B=>L(B.target.value),onBlur:()=>{ae(!1);const B=X.trim(),Y=Number(B);if(!B||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const D=Math.round(Y);e("label_weight",D),L(String(D))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),a.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:B=>{const Y=Math.max(1,Math.min(100,parseInt(B.target.value)||1));p(Y)}})]})]})}function Ple({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=g=>u.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(i.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),k=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const P=g?g.toLowerCase().split(/[\s\-_]+/).filter(A=>A.length>=2):[],N=A=>{if(P.length===0)return!0;const T=A.toLowerCase();return P.some(C=>T.includes(C))};if(g&&!_){const A=i.filter(T=>N(T.manufacturer));if(A.length>0)return A.map(T=>({name:T.color_name,hex:T.hex_color.replace("#","").substring(0,6),manufacturer:T.manufacturer,material:typeof T.material=="string"?T.material:void 0}))}const M=_&&k?`${_} ${k}`:"";if(M){const A=i.filter(C=>N(C.manufacturer)&&C.material?.toLowerCase()===M);if(A.length>0)return A.map(C=>({name:C.color_name,hex:C.hex_color.replace("#","").substring(0,6),manufacturer:C.manufacturer,material:typeof C.material=="string"?C.material:void 0}));const T=M.replace(/\+$/,"");if(T!==M){const C=i.filter(F=>N(F.manufacturer)&&F.material?.toLowerCase()===T);if(C.length>0)return C.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}}if(_){const A=i.filter(T=>N(T.manufacturer)&&(!T.material||T.material.toLowerCase().startsWith(_)));if(A.length>0)return A.map(T=>({name:T.color_name,hex:T.hex_color.replace("#","").substring(0,6),manufacturer:T.manufacturer,material:typeof T.material=="string"?T.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(k=>k.name.toLowerCase().includes(g)||(k.manufacturer?.toLowerCase().includes(g)??!1)||(k.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?aX.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?aX:yle,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(rr,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:g=>d(g.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(Yl,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(Fn,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.name})},g.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:g=>e("color_name",g.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Lnt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(vbe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:y,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Tle({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Lt(),{showToast:s}=xn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Lnt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=u.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{d(!1);const b=o.trim(),g=Number(b),_=t.core_weight,k=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>k){s(i("inventory.measuredWeightError",{min:_,max:k}),"error"),l(String(v));return}const P=Math.round(g),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(String(P))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:i("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function Ale({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Lt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const k of Array.from(_)){const P=k.split(":");`${P[0]}:${P[2]}`===b&&_.delete(k)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>h3(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const P=[..._].sort((N,M)=>M.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${g}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>h3(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return a.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&a.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(wx,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=i.has(String(p.id)),v=f.filter(P=>h3(P,t)),b=v.length,g=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),k=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[y?a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),y&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),k.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:k.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Ont(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 Int={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function znt({spoolId:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),{data:i,isLoading:s}=et({queryKey:["spool-usage",t],queryFn:()=>pe.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>pe.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(rr,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(un,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:Ont(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:Int[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Unt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Lt(),l=mn(),{showToast:c}=xn(),d=!!n,[u,m]=w.useState(qL),[p,f]=w.useState({}),[y,v]=w.useState("filament"),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(1),[M,A]=w.useState(!1),[T,C]=w.useState(!1),[F,$]=w.useState([]),[I,X]=w.useState(""),[L,te]=w.useState([]),[ae,ee]=w.useState([]),[me,le]=w.useState([]),[ue,K]=w.useState([]),[ne,oe]=w.useState([]),[be,_e]=w.useState(new Set),[B,Y]=w.useState(new Set),D=r.length>0?r:ne,j=w.useMemo(()=>be.size,[be]);w.useEffect(()=>{K(kle())},[]),w.useEffect(()=>{t&&((async()=>{C(!0);try{const Fe=await pe.getCloudStatus();if(A(Fe.is_authenticated),Fe.is_authenticated){const Ee=await pe.getFilamentPresets();$(Ee)}}catch(Fe){console.error("Failed to fetch cloud presets:",Fe),A(!1)}finally{C(!1)}})(),pe.getSpoolCatalog().then(te).catch(console.error),pe.getColorCatalog().then(le).catch(console.error),pe.getLocalPresets().then(Fe=>ee(Fe.filament)).catch(console.error),r.length===0&&(async()=>{try{const Fe=await pe.getPrinters(),Ee=await Promise.all(Fe.map(je=>pe.getPrinterStatus(je.id).catch(()=>null))),Se=[];for(let je=0;je<Fe.length;je++){const qe=Fe[je],Ye=Ee[je]?.connected??!1;let ce=[];if(Ye)try{ce=(await pe.getKProfiles(qe.id)).profiles.map(Ne=>({cali_idx:Ne.slot_id,filament_id:Ne.filament_id,setting_id:Ne.setting_id||"",name:Ne.name,k_value:parseFloat(Ne.k_value)||0,n_coef:parseFloat(Ne.n_coef)||0,extruder_id:Ne.extruder_id,nozzle_diameter:Ne.nozzle_diameter}))}catch{}Se.push({printer:{...qe,connected:Ye},calibrations:ce})}oe(Se)}catch(Fe){console.error("Failed to fetch printer calibrations:",Fe)}})())},[t,r.length]);const z=w.useMemo(()=>Sle(F,new Set,ae),[F,ae]),W=w.useMemo(()=>{const Te=wle(F,ae),Fe=me.map(Se=>Se.manufacturer?.trim()).filter(Se=>!!Se),Ee=new Set([...Te,...Fe]);return Array.from(Ee).sort((Se,je)=>Se.localeCompare(je))},[F,ae,me]),q=w.useMemo(()=>{const Te=me.map(Ee=>Ee.material?.trim()).filter(Ee=>!!Ee),Fe=new Set([...xle,...Te]);return Array.from(Fe).sort((Ee,Se)=>Ee.localeCompare(Se))},[me]),de=w.useMemo(()=>{const Te=[];for(const Fe of me){const Ee=Fe.manufacturer?.trim(),Se=Fe.material?.trim();Ee&&Se&&Te.push({brand:Ee,material:Se})}for(const Fe of F){const Ee=Jh(Fe.name);Ee.brand&&Ee.material&&Te.push({brand:Ee.brand,material:Ee.material})}for(const Fe of ae){const Ee=Jh(Fe.name),Se=Fe.filament_vendor?.trim()||Ee.brand,je=Ee.material;Se&&je&&Te.push({brand:Se,material:je})}return Te},[F,me,ae]),O=w.useMemo(()=>{const Te=new Map;for(const Fe of de){const Ee=Fe.brand.toLowerCase(),Se=Fe.material.toLowerCase();Te.has(Ee)||Te.set(Ee,new Set),Te.get(Ee).add(Se)}return Te},[de]),G=w.useMemo(()=>{const Te=new Map;for(const Fe of de){const Ee=Fe.brand.toLowerCase(),Se=Fe.material.toLowerCase();Te.has(Se)||Te.set(Se,new Set),Te.get(Se).add(Ee)}return Te},[de]),Q=w.useMemo(()=>{if(!u.material)return W;const Te=u.material.toLowerCase(),Fe=G.get(Te);return!Fe||Fe.size===0?W:W.filter(Ee=>Fe.has(Ee.toLowerCase()))},[W,u.material,G]),V=w.useMemo(()=>{if(!u.brand)return q;const Te=u.brand.toLowerCase(),Fe=O.get(Te);return!Fe||Fe.size===0?q:q.filter(Ee=>Fe.has(Ee.toLowerCase()))},[q,u.brand,O]),J=w.useMemo(()=>_le(u.slicer_filament,z),[u.slicer_filament,z]);w.useEffect(()=>{if(t){if(n)if(m({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),X(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const Te=new Set;for(const Fe of n.k_profiles)Fe.cali_idx!==null&&Fe.cali_idx!==void 0&&Te.add(`${Fe.printer_id}:${Fe.cali_idx}:${Fe.extruder??"null"}`);_e(Te)}else _e(new Set);else m(qL),X(""),_e(new Set),k(!1),N(1);f({}),v("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&D.length>0&&Y(new Set(D.map(Te=>String(Te.printer.id))))},[t,D]);const ie=(Te,Fe)=>{m(Ee=>({...Ee,[Te]:Fe})),Te==="weight_used"&&g(!0),p[Te]&&f(Ee=>({...Ee,[Te]:void 0}))},he=Te=>{K(Fe=>Nle(Te,Fe))},fe=lt({mutationFn:Te=>pe.createSpool(Te),onSuccess:async Te=>{be.size>0&&Te?.id&&await ye(Te.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([Te]),c(o("inventory.spoolCreated"),"success"),e()},onError:Te=>{c(Te.message,"error")}}),se=lt({mutationFn:({data:Te,qty:Fe})=>pe.bulkCreateSpools(Te,Fe),onSuccess:async Te=>{if(be.size>0)for(const Fe of Te)await ye(Fe.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(Te),c(o("inventory.spoolsCreated",{count:Te.length}),"success"),e()},onError:Te=>{c(Te.message,"error")}}),U=lt({mutationFn:Te=>pe.updateSpool(n.id,Te),onSuccess:async()=>{n?.id&&await ye(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:Te=>{c(Te.message,"error")}}),R=lt({mutationFn:()=>pe.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:Te=>{c(Te.message,"error")}}),{data:re}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),enabled:t&&d}),xe=n?re?.find(Te=>Te.spool_id===n.id):void 0,we=lt({mutationFn:()=>{if(!xe)throw new Error("No assignment");return pe.unassignSpool(xe.printer_id,xe.ams_id,xe.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Te=>{c(Te.message,"error")}}),ye=async Te=>{if(be.size===0){try{await pe.saveSpoolKProfiles(Te,[])}catch{}return}const Fe=[];for(const Ee of be){const[Se,je,qe]=Ee.split(":"),Re=parseInt(Se),Ye=parseInt(je),ce=qe==="null"?0:parseInt(qe),ze=D.find(Ne=>Ne.printer.id===Re);if(ze){const Ne=ze.calibrations.find(Ge=>Ge.cali_idx===Ye);Ne&&Fe.push({printer_id:Re,extruder:ce,nozzle_diameter:Ne.nozzle_diameter||"0.4",k_value:Ne.k_value,name:Ne.name||null,cali_idx:Ne.cali_idx,setting_id:Ne.setting_id||null})}}if(Fe.length>0)try{await pe.saveSpoolKProfiles(Te,Fe)}catch(Ee){console.error("Failed to save K-profiles:",Ee)}};if(w.useEffect(()=>{if(!t)return;const Te=Fe=>{Fe.key==="Escape"&&e()};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,e]),!t)return null;const Ae=()=>{const Te=ble(u,_);if(!Te.isValid){f(Te.errors),(Te.errors.slicer_filament||Te.errors.material||Te.errors.brand||Te.errors.subtype)&&v("filament");return}const Fe=J?.displayName||I||null,Ee={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Fe,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||b)&&(Ee.weight_used=u.weight_used),d?U.mutate(Ee):P>1?se.mutate({data:Ee,qty:P}):fe.mutate(Ee)},ve=fe.isPending||se.isPending||U.isPending||R.isPending||we.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{k(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Dw,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(npe,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:y==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx(Cle,{formData:u,updateField:ie,cloudAuthenticated:M,loadingCloudPresets:T,presetInputValue:I,setPresetInputValue:X,selectedPresetOption:J,filamentOptions:z,availableBrands:Q,availableMaterials:V,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(Ple,{formData:u,updateField:ie,recentColors:ue,onColorUsed:he,catalogColors:me})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(Tle,{formData:u,updateField:ie,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(znt,{spoolId:n.id})})]}):a.jsx(Ale,{formData:u,updateField:ie,printersWithCalibrations:D,selectedProfiles:be,setSelectedProfiles:_e,expandedPrinters:B,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>R.mutate(),disabled:ve||!n?.tag_uid,children:[a.jsx(Gu,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>we.mutate(),disabled:ve||!xe,children:[a.jsx(qh,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Ie,{onClick:Ae,disabled:ve,children:ve?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Bnt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Lt(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((M,A)=>A===P?{...M,visible:!M.visible}:M))},p=(P,N)=>{N<0||N>=o.length||l(M=>{const A=[...M],[T]=A.splice(P,1);return A.splice(N,0,T),A})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},y=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const M=u.current;M!==null&&M!==N&&(p(M,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},g=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},k=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(Dt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Rt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>f(M,N),onDragOver:M=>y(M,N),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(Eh,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:a.jsx(Yl,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:a.jsx(Fn,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Ie,{variant:"secondary",onClick:g,className:"mr-auto",children:[a.jsx(jo,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Ie,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Ie,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function iX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Mle="bambuddy-inventory-columns",$k=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Hnt(){try{const t=localStorage.getItem(Mle);if(t){const e=JSON.parse(t),n=new Set($k.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=$k.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return $k.map(t=>({...t}))}function qnt(t){try{localStorage.setItem(Mle,JSON.stringify(t))}catch{}}function xd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const $nt={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 p3(t,e="system"){if(!t)return"-";const n=Qn(t);return n?V3(n,e):"-"}const Vnt={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},$L={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?p3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:FT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=uS(n.ams_id,n.tray_id,s,i);return a.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:xd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?xd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n<r?(s=n-r,o=!0):(s=n-i,o=Math.abs(s)<=50);const l=s>0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g
  8346. Calculated: ${Math.round(i)}g
  8347. Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g
  8348. Calculated: ${Math.round(i)}g
  8349. Difference: ${l}g (mismatch!)`;return a.jsxs("div",{className:`flex items-center gap-1 text-sm font-medium ${o?"text-green-400":"text-yellow-400"}`,title:c,children:[a.jsxs("span",{children:[Math.round(n),"g"]}),o?a.jsx(Kr,{className:"w-3 h-3"}):a.jsxs(a.Fragment,{children:[a.jsx(Ln,{className:"w-3 h-3"}),e&&a.jsx("button",{type:"button",onClick:d=>{d.stopPropagation(),d.preventDefault(),e(t)},className:"p-1 hover:bg-bambu-green/20 rounded transition-colors text-bambu-green",title:"Sync: trust scale weight and reset tracking",children:a.jsx(vr,{className:"w-3.5 h-3.5"})})]})]})}},f3={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,i=!r&&n.ams_id>=128,s=n.ams_label?` (${n.ams_label})`:"";return`${n.printer_name||""} ${uS(n.ams_id,n.tray_id,i,r)}${s}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),stock:t=>t.slicer_filament?1:0,spool_name:t=>t.core_weight_catalog_id??0,cost_per_kg:t=>t.cost_per_kg??0,weight_check:t=>{if(t.last_scale_weight==null)return-1;const e=Math.max(0,t.label_weight-t.weight_used)+t.core_weight;return Math.abs(t.last_scale_weight-e)}},VL="bambuddy-inventory-sort";function Gnt(){try{const t=localStorage.getItem(VL);if(t)return JSON.parse(t)}catch{}return null}function Wnt(t){try{t?localStorage.setItem(VL,JSON.stringify(t)):localStorage.removeItem(VL)}catch{}}function Knt(){const{data:t}=et({queryKey:["spoolman-settings"],queryFn:pe.getSpoolmanSettings,staleTime:3e5});return t?.spoolman_enabled==="true"&&t?.spoolman_url?a.jsx("iframe",{src:`${t.spoolman_url.replace(/\/+$/,"")}/spool`,className:"h-full w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}):a.jsx(Ynt,{})}function Ynt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),[r,i]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[d,u]=w.useState("all"),[m,p]=w.useState(""),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState("all"),[k,P]=w.useState(""),[N,M]=w.useState("table"),[A,T]=w.useState(Gnt),[C,F]=w.useState(Hnt),[$,I]=w.useState(!1),[X,L]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[te,ae]=w.useState(new Set),[ee,me]=w.useState(0),[le,ue]=w.useState(()=>{try{const Pe=localStorage.getItem("bambuddy-inventory-pageSize");if(Pe){const Me=Number(Pe);if([15,30,50,100,-1].includes(Me))return Me}}catch{}return 15}),{data:K}=et({queryKey:["settings"],queryFn:pe.getSettings}),ne=K?.date_format||"system",{data:oe,isLoading:be}=et({queryKey:["inventory-spools"],queryFn:()=>pe.getSpools(!0),refetchInterval:3e4}),{data:_e}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),refetchInterval:3e4}),{data:B}=et({queryKey:["spool-catalog"],queryFn:()=>pe.getSpoolCatalog()}),Y=lt({mutationFn:Pe=>pe.deleteSpool(Pe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),D=lt({mutationFn:Pe=>pe.archiveSpool(Pe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),j=lt({mutationFn:Pe=>pe.restoreSpool(Pe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),z=async Pe=>{if(Pe.last_scale_weight!=null)try{await wa.updateSpoolWeight(Pe.id,Pe.last_scale_weight),e.invalidateQueries({queryKey:["inventory-spools"]});const Me=[Pe.brand,Pe.material,Pe.color_name].filter(Boolean).join(" ");n(`Synced "${Me}" to scale weight`,"success")}catch{n("Failed to sync weight","error")}},W=K?.low_stock_threshold??20,[q,de]=w.useState(!1),[O,G]=w.useState(W.toString());w.useEffect(()=>{q||G(W.toString())},[W,q]);const Q=lt({mutationFn:Pe=>pe.updateSettings({low_stock_threshold:Pe}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),n(t("common.saved"),"success"),de(!1)},onError:()=>{n(t("inventory.lowStockThresholdError"),"error")}}),V=w.useMemo(()=>{if(!oe)return null;let Pe=0,Me=0,Ve=0,tt=0;const ut={};for(const xt of oe){if(xt.archived_at)continue;tt++;const wt=Math.max(0,xt.label_weight-xt.weight_used);Pe+=wt,Me+=xt.weight_used,(xt.label_weight>0?wt/xt.label_weight*100:0)<W&&Ve++;const Xt=xt.material||"Unknown";ut[Xt]||(ut[Xt]={count:0,weight:0}),ut[Xt].count++,ut[Xt].weight+=wt}return{totalWeight:Pe,totalConsumed:Me,lowStock:Ve,byMaterial:ut,totalSpools:tt}},[oe,W]),J=_e?.length??0,ie=yo(K?.currency||"USD"),he=w.useMemo(()=>{const Pe={};for(const Me of _e||[])Pe[Me.spool_id]=Me;return Pe},[_e]),fe=w.useMemo(()=>{const Pe={};for(const Me of B||[])Pe[Me.id]=Me;return Pe},[B]),se=w.useMemo(()=>V?Object.entries(V.byMaterial).sort((Pe,Me)=>Me[1].weight-Pe[1].weight).slice(0,4):[],[V]),U=w.useMemo(()=>{let Pe=oe||[];if(l==="active"?Pe=Pe.filter(Me=>!Me.archived_at):Pe=Pe.filter(Me=>!!Me.archived_at),d==="used"?Pe=Pe.filter(Me=>Me.weight_used>0):d==="new"?Pe=Pe.filter(Me=>Me.weight_used===0):d==="lowstock"&&(Pe=Pe.filter(Me=>{const Ve=Math.max(0,Me.label_weight-Me.weight_used);return(Me.label_weight>0?Ve/Me.label_weight*100:0)<W})),m&&(Pe=Pe.filter(Me=>Me.material===m)),f&&(Pe=Pe.filter(Me=>Me.brand===f)),v){const Me=Number(v);Pe=Pe.filter(Ve=>Ve.core_weight_catalog_id===Me)}if(g==="stock"?Pe=Pe.filter(Me=>!Me.slicer_filament):g==="configured"&&(Pe=Pe.filter(Me=>!!Me.slicer_filament)),k){const Me=k.toLowerCase();Pe=Pe.filter(Ve=>Ve.brand?.toLowerCase().includes(Me)||Ve.material.toLowerCase().includes(Me)||Ve.color_name?.toLowerCase().includes(Me)||Ve.subtype?.toLowerCase().includes(Me)||Ve.note?.toLowerCase().includes(Me)||Ve.slicer_filament_name?.toLowerCase().includes(Me))}return Pe},[oe,l,d,m,f,v,g,k,W]),R=()=>me(0),re=[...new Set(oe?.map(Pe=>Pe.material)||[])].sort(),xe=[...new Set(oe?.map(Pe=>Pe.brand).filter(Boolean)||[])].sort(),we=[...new Set(oe?.map(Pe=>Pe.core_weight_catalog_id).filter(Pe=>Pe!=null)||[])].sort((Pe,Me)=>{const Ve=(fe[Pe]?.name||"").toLowerCase(),tt=(fe[Me]?.name||"").toLowerCase();return Ve.localeCompare(tt)}),ye=l!=="active"||d!=="all"||!!m||!!f||!!v||g!=="all"||!!k,Ae=Pe=>{F(Pe),qnt(Pe)},ve=w.useMemo(()=>C.filter(Pe=>Pe.visible).map(Pe=>Pe.id),[C]),Te=Pe=>{f3[Pe]&&(T(Me=>{let Ve;return Me?.column===Pe?Ve=Me.direction==="asc"?{column:Pe,direction:"desc"}:null:Ve={column:Pe,direction:"asc"},Wnt(Ve),Ve}),R())},Fe=w.useMemo(()=>{if(!A)return U;const Pe=f3[A.column];return Pe?[...U].sort((Ve,tt)=>{const ut=Pe(Ve,he),xt=Pe(tt,he);return ut<xt?A.direction==="asc"?-1:1:ut>xt?A.direction==="asc"?1:-1:0}):U},[U,A,he]),Ee=w.useMemo(()=>{if(!X)return Fe.map(tt=>({type:"single",spool:tt}));const Pe=new Map;for(const tt of Fe)if(!(tt.weight_used>0||he[tt.id])){const ut=iX(tt),xt=Pe.get(ut);xt?xt.push(tt):Pe.set(ut,[tt])}const Me=[],Ve=new Set;for(const tt of Fe){if(tt.weight_used>0||he[tt.id]){Me.push({type:"single",spool:tt});continue}const ut=iX(tt);if(Ve.has(ut))continue;Ve.add(ut);const xt=Pe.get(ut);xt.length===1?Me.push({type:"single",spool:xt[0]}):Me.push({type:"group",key:ut,spools:xt,representative:xt[0]})}return Me},[Fe,X,he]),Se=le===-1,je=Ee.length,qe=Se?je||1:le,Re=Math.max(1,Math.ceil(je/qe)),Ye=Se?0:Math.min(ee,Re-1),ce=Se?Ee:Ee.slice(Ye*qe,(Ye+1)*qe),ze=()=>{const Pe=!X;L(Pe),ae(new Set),R();try{localStorage.setItem("bambuddy-inventory-group",String(Pe))}catch{}},Ne=Pe=>{ae(Me=>{const Ve=new Set(Me);return Ve.has(Pe)?Ve.delete(Pe):Ve.add(Pe),Ve})},Ge=Pe=>{ue(Pe),me(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Pe))}catch{}},$e=()=>{c("active"),u("all"),p(""),y(""),b(""),_("all"),P(""),R()};return a.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Na,{className:"w-6 h-6 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),a.jsxs(Ie,{onClick:()=>i({spool:null}),children:[a.jsx(ur,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),V&&!be&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Na,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:xd(V.totalWeight,!0)}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[V.totalSpools," ",V.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(fO,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:xd(V.totalConsumed,!0)}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(ea,{className:"w-4 h-4 text-green-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:se.map(([Pe,Me])=>a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${$nt[Pe]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Pe," ",a.jsx("span",{className:"opacity-70",children:xd(Me.weight,!0)})]},Pe))})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Pr,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:J}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),a.jsx("div",{className:`text-xl font-bold ${V.lowStock>0?"text-yellow-400":"text-white"}`,children:V.lowStock}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1 flex items-center gap-2",children:q?a.jsxs("form",{onSubmit:Pe=>{Pe.preventDefault();const Me=parseFloat(O);!isNaN(Me)&&Me>=.1&&Me<=99.9?Q.mutate(Me):n(t("inventory.lowStockThresholdError"),"error")},className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"<"}),a.jsx("input",{type:"text",inputMode:"decimal",pattern:"^\\d{0,2}(\\.\\d?)?$",maxLength:4,value:O,onChange:Pe=>{const Me=Pe.target.value.replace(/[^\d.]/g,"");/^\d{0,2}(\.\d?)?$/.test(Me)&&G(Me)},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:Pe=>Pe.currentTarget.blur(),disabled:Q.isPending}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"%"}),a.jsx(Ie,{type:"submit",size:"sm",disabled:Q.isPending,children:t("common.save")}),a.jsx(Ie,{type:"button",size:"sm",variant:"ghost",onClick:()=>de(!1),disabled:Q.isPending,children:t("common.cancel")})]}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"text-bambu-gray",children:["< ",W,"%"]}),a.jsx("button",{className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("common.edit"),onClick:()=>{G(W.toString()),de(!0)},children:a.jsx(xh,{className:"w-4 h-4"})})]})})]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[a.jsxs("div",{className:"relative flex-1 max-w-md",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:k,onChange:Pe=>{P(Pe.target.value),R()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),k&&a.jsx("button",{onClick:()=>{P(""),R()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[N==="table"&&a.jsxs("button",{onClick:()=>I(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[a.jsx(ife,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),a.jsxs("button",{onClick:ze,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${X?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:t("inventory.groupSimilar"),children:[a.jsx(nge,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),a.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>M("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Wbe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),a.jsxs("button",{onClick:()=>M("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(jw,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("button",{onClick:()=>{c("active"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Na,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),a.jsxs("button",{onClick:()=>{c("archived"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{u("all"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${d==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsxs("button",{onClick:()=>{u("used"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${d==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),a.jsx("button",{onClick:()=>{u("new"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${d==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")}),a.jsxs("button",{onClick:()=>{u("lowstock"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${d==="lowstock"?"bg-yellow-500/20 text-yellow-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),t("inventory.lowStock")]})]}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{_("all"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsx("button",{onClick:()=>{_("stock"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),a.jsx("button",{onClick:()=>{_("configured"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("select",{value:m,onChange:Pe=>{p(Pe.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${m?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.material")}),re.map(Pe=>a.jsx("option",{value:Pe,children:Pe},Pe))]}),a.jsxs("select",{value:f,onChange:Pe=>{y(Pe.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${f?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.brand")}),xe.map(Pe=>a.jsx("option",{value:Pe,children:Pe},Pe))]}),we.length>0&&a.jsxs("select",{value:v,onChange:Pe=>{b(Pe.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${v?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.spoolName")}),we.map(Pe=>a.jsx("option",{value:Pe,children:fe[Pe]?.name||`#${Pe}`},Pe))]}),ye&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("button",{onClick:$e,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[a.jsx(Bt,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),a.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Fe.length," ",Fe.length!==1?t("inventory.spools"):t("inventory.spool"),X&&je<Fe.length&&` (${je} ${t("inventory.groupedRows")})`]})]}),be?a.jsx("div",{className:"flex justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):N==="cards"?ce.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:ce.map(Pe=>{if(Pe.type==="group"){const{key:xt,spools:wt,representative:Ht}=Pe,Xt=Ht.rgba?`#${Ht.rgba.substring(0,6)}`:"#808080",Kt=te.has(xt);return a.jsxs("div",{className:"col-span-full",children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer",onClick:()=>Ne(xt),children:[a.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:Xt},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:FT(Ht.color_name,Ht.rgba)||"-"})}),a.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray transition-transform ${Kt?"":"-rotate-90"}`}),a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[Ht.material,Ht.subtype?` ${Ht.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:Ht.brand||"-"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:xd(Ht.label_weight)}),a.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:t("inventory.groupedSpools",{count:wt.length})})]})]})]}),Kt&&a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4",children:wt.map(Ut=>{const en=Math.max(0,Ut.label_weight-Ut.weight_used),Ke=Ut.label_weight>0?en/Ut.label_weight*100:0,Ft=Ut.rgba?`#${Ut.rgba.substring(0,6)}`:"#808080";return a.jsx(sX,{spool:Ut,remaining:en,pct:Ke,colorStyle:Ft,onClick:()=>i({spool:Ut}),t},Ut.id)})})]},`group-${xt}`)}const Me=Pe.spool,Ve=Math.max(0,Me.label_weight-Me.weight_used),tt=Me.label_weight>0?Ve/Me.label_weight*100:0,ut=Me.rgba?`#${Me.rgba.substring(0,6)}`:"#808080";return a.jsx(sX,{spool:Me,remaining:Ve,pct:tt,colorStyle:ut,onClick:()=>i({spool:Me}),t},Me.id)})}),a.jsx(Xnt,{pageIndex:Ye,pageSize:le,totalRows:je,totalPages:Re,onPageChange:me,onPageSizeChange:Ge,t})]}):a.jsx(oX,{hasFilters:ye,onAddSpool:()=>i({spool:null}),t}):ce.length>0?a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[ve.map(Pe=>{const Me=!!f3[Pe],Ve=A?.column===Pe;return a.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Pe==="remaining"?"min-w-[150px]":""} ${Me?"cursor-pointer hover:text-bambu-green transition-colors":""} ${Ve?"text-bambu-green":"text-bambu-gray"}`,onClick:Me?()=>Te(Pe):void 0,children:a.jsxs("span",{className:"inline-flex items-center gap-1",children:[Vnt[Pe]?.(t)??Pe,Me&&(Ve?A.direction==="asc"?a.jsx(Lf,{className:"w-3 h-3"}):a.jsx(bx,{className:"w-3 h-3"}):a.jsx(lO,{className:"w-3 h-3 opacity-30"}))]})},Pe)}),a.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),a.jsx("tbody",{children:ce.map(Pe=>{if(Pe.type==="group"){const{key:ut,spools:xt,representative:wt}=Pe,Ht=te.has(ut),Xt=Math.max(0,wt.label_weight-wt.weight_used),Kt=wt.label_weight>0?Xt/wt.label_weight*100:0;return a.jsx(Qnt,{spools:xt,representative:wt,remaining:Xt,pct:Kt,isExpanded:Ht,onToggle:()=>Ne(ut),onEdit:Ut=>i({spool:Ut}),onArchive:Ut=>o({type:"archive",spoolId:Ut}),onDelete:Ut=>o({type:"delete",spoolId:Ut}),visibleColumns:ve,assignmentMap:he,catalogMap:fe,currencySymbol:ie,dateFormat:ne,t,onSyncWeight:z},`group-${ut}`)}const Me=Pe.spool,Ve=Math.max(0,Me.label_weight-Me.weight_used),tt=Me.label_weight>0?Ve/Me.label_weight*100:0;return a.jsx(jle,{spool:Me,remaining:Ve,pct:tt,onEdit:()=>i({spool:Me}),onRestore:()=>j.mutate(Me.id),onArchive:()=>o({type:"archive",spoolId:Me.id}),onDelete:()=>o({type:"delete",spoolId:Me.id}),visibleColumns:ve,assignmentMap:he,catalogMap:fe,currencySymbol:ie,dateFormat:ne,t,onSyncWeight:z},Me.id)})})]})}),a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:Se?`${je} ${t(je!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[t("inventory.showing")," ",Ye*qe+1," ",t("inventory.to")," ",Math.min((Ye+1)*qe,je)," ",t("inventory.of")," ",je," ",t("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),a.jsxs("select",{value:le,onChange:Pe=>Ge(Number(Pe.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(Pe=>a.jsx("option",{value:Pe,children:Pe},Pe)),a.jsx("option",{value:-1,children:t("inventory.all")})]}),!Se&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>me(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:a.jsx(dO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>me(Pe=>Math.max(0,Pe-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:a.jsx(ol,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",Ye+1," ",t("inventory.of")," ",Re]}),a.jsx("button",{onClick:()=>me(Pe=>Math.min(Re-1,Pe+1)),disabled:Ye>=Re-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>me(Re-1),disabled:Ye>=Re-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:a.jsx(uO,{className:"w-4 h-4"})})]})]})]})]}):a.jsx(oX,{hasFilters:ye,onAddSpool:()=>i({spool:null}),t}),r!==null&&a.jsx(Unt,{isOpen:!0,onClose:()=>i(null),spool:r.spool,currencySymbol:ie}),s&&a.jsx(kn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?Y.mutate(s.spoolId):D.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),a.jsx(Bnt,{isOpen:$,onClose:()=>I(!1),columns:C,defaultColumns:$k,onSave:Ae})]})}function Xnt({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),a.jsxs("select",{value:e,onChange:d=>s(Number(d.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(d=>a.jsx("option",{value:d,children:d},d)),a.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(dO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(ol,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),a.jsx("button",{onClick:()=>i(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(uO,{className:"w-4 h-4"})})]})]})]})}function sX({spool:t,remaining:e,pct:n,colorStyle:r,onClick:i,t:s}){return a.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:i,children:[a.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:FT(t.color_name,t.rgba)||"-"})}),a.jsxs("div",{className:"p-4 space-y-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),a.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[a.jsx("span",{children:s("inventory.remaining")}),a.jsxs("span",{children:[Math.round(n),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${n>50?"bg-bambu-green":n>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(n,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.labelWeight"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:xd(t.label_weight)})]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?xd(t.weight_used):"-"})]})]}),t.note&&a.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:t.note,children:t.note})]})]})}function jle({spool:t,remaining:e,pct:n,onEdit:r,onRestore:i,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,catalogMap:d,currencySymbol:u,dateFormat:m,t:p,onSyncWeight:f}){return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:r,children:[l.map(y=>a.jsx("td",{className:"py-3 px-4",children:$L[y]?.({spool:t,remaining:e,pct:n,assignmentMap:c,catalogMap:d,currencySymbol:u,dateFormat:m,t:p,onSyncWeight:f})},y)),a.jsx("td",{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:y=>y.stopPropagation(),children:[a.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:p("common.edit"),children:a.jsx(xh,{className:"w-4 h-4"})}),t.archived_at?a.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:p("inventory.restore"),children:a.jsx(jo,{className:"w-4 h-4"})}):a.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:p("inventory.archive"),children:a.jsx(Qs,{className:"w-4 h-4"})}),a.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:p("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]})})]})}function Qnt({spools:t,representative:e,remaining:n,pct:r,isExpanded:i,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:d,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v}){return a.jsxs(a.Fragment,{children:[a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5",onClick:s,children:[d.map((b,g)=>a.jsx("td",{className:"py-3 px-4",children:g===0?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"":"-rotate-90"}`}),$L[b]?.({spool:e,remaining:n,pct:r,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})]}):b==="id"?a.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:y("inventory.groupedSpools",{count:t.length})}):$L[b]?.({spool:e,remaining:n,pct:r,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})},b)),a.jsx("td",{className:"py-3 px-4",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(b=>`#${b.id}`).join(", ")})})]}),i&&t.map(b=>{const g=Math.max(0,b.label_weight-b.weight_used),_=b.label_weight>0?g/b.label_weight*100:0;return a.jsx(jle,{spool:b,remaining:g,pct:_,onEdit:()=>o(b),onRestore:()=>{},onArchive:()=>l(b.id),onDelete:()=>c(b.id),visibleColumns:d,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v},b.id)})]})}function oX({hasFilters:t,onAddSpool:e,t:n}){return a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[a.jsxs("div",{className:"relative mb-6",children:[a.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),a.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[a.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),a.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?a.jsx(Sr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:a.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),a.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:a.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),a.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&a.jsxs(Ie,{onClick:e,children:[a.jsx(Na,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const lX=["DEBUG","INFO","WARNING","ERROR"],g3={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},Znt={DEBUG:xx,INFO:Ks,WARNING:Ln,ERROR:qa};function Jnt(){const t=mn(),[e,n]=w.useState(!0),[r,i]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[d,u]=w.useState(!1),[m,p]=w.useState(!1),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["application-logs",l,s],queryFn:()=>nx.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:m?2e3:!1,enabled:d});w.useEffect(()=>{d||p(!1)},[d]);const g=lt({mutationFn:()=>nx.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&f.current&&y?.entries&&(f.current.scrollTop=f.current.scrollHeight)},[y?.entries,e]);const _=A=>{i(T=>{const C=new Set(T);return C.has(A)?C.delete(A):C.add(A),C})},k=A=>{const T=A.split(" ");return T.length>=2?T[1]:A},P=w.useMemo(()=>y?.entries??[],[y?.entries]),N=w.useMemo(()=>[...P].reverse(),[P]),M=({level:A})=>{const T=Znt[A]||Ks;return a.jsx(T,{className:`w-3.5 h-3.5 ${g3[A]||"text-gray-400"}`})};return a.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>u(!d),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${m?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(xx,{className:"w-5 h-5"})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:m?`Live streaming - ${y?.filtered_count??0} entries`:"View and filter application logs"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[m&&a.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[a.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),d?a.jsx(Yl,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(Fn,{className:"w-5 h-5 text-bambu-gray"})]})]}),d&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m?a.jsxs("button",{onClick: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:[a.jsx(eo,{className:"w-4 h-4"}),"Stop"]}):a.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:[a.jsx(Ds,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>g.mutate(),disabled:g.isPending||P.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[a.jsx(un,{className:"w-4 h-4"}),"Clear"]}),a.jsx("button",{onClick:()=>b(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:a.jsx(vr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:e,onChange:A=>n(A.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[y?.filtered_count??0,"/",y?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Sr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange: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&&a.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),lX.map((A,T)=>a.jsx("button",{onClick:()=>c(A),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${T===lX.length-1?"rounded-r":""} ${l===A?`${g3[A]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:A},A))]})]})]}),a.jsx("div",{ref:f,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:P.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:"No log entries found"}),a.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:N.map((A,T)=>{const C=r.has(T),F=A.message.includes(`
  8350. `);return a.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${C?"bg-bambu-dark-secondary/30":""}`,onClick:()=>F&&_(T),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:k(A.timestamp)}),a.jsx("span",{className:"shrink-0",children:a.jsx(M,{level:A.level})}),a.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:A.logger_name,children:["[",A.logger_name,"]"]}),a.jsx("span",{className:`flex-1 ${g3[A.level]||"text-white/80"} ${!C&&F?"truncate":""}`,children:C?a.jsx("pre",{className:"whitespace-pre-wrap break-all",children:A.message}):A.message.split(`
  8351. `)[0]}),F&&a.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:C?a.jsx(Yl,{className:"w-3.5 h-3.5"}):a.jsx(Fn,{className:"w-3.5 h-3.5"})})]})},T)})})}),a.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:m?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):a.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function ert(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 ga({icon:t,label:e,value:n,subValue:r,color:i="text-bambu-green"}){return a.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function cX({percent:t,color:e="bg-bambu-green"}){return a.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function eh({title:t,icon:e,children:n}){return a.jsxs(Dt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx(e,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function trt(){const{t}=Lt(),e=mn(),[n,r]=w.useState(null),[i,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:d,refetch:u,isFetching:m}=et({queryKey:["systemInfo"],queryFn:pe.getSystemInfo,refetchInterval:3e4}),{data:p}=et({queryKey:["debugLogging"],queryFn:nx.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:f}=et({queryKey:["settings"],queryFn:pe.getSettings}),{data:y}=et({queryKey:["library-stats"],queryFn:pe.getLibraryStats}),v=f?.time_format||"system",b=async()=>{l(!0);try{const P=await nx.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],P)}catch(P){console.error("Failed to toggle debug logging:",P)}finally{l(!1)}},g=async()=>{r(null),s(!0);try{await nx.downloadSupportBundle()}catch(P){r(P instanceof Error?P.message:"Failed to download support bundle")}finally{s(!1)}};if(d)return a.jsx("div",{className:"flex items-center justify-center h-64",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return a.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",k=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return a.jsxs("div",{className:"p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),a.jsxs("button",{onClick:()=>u(),disabled:m,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[a.jsx(vr,{className:`w-4 h-4 ${m?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),a.jsx(eh,{title:t("system.application","Application"),icon:Vp,children:a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(ga,{icon:Vp,label:t("system.version","Version"),value:`v${c.app.version}`}),a.jsx(ga,{icon:rr,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),a.jsx(ga,{icon:Vp,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),a.jsx(eh,{title:t("support.title","Support & Troubleshooting"),icon:lge,children:a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(xx,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),p?.enabled&&p.duration_seconds!==null&&a.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),a.jsxs("button",{onClick: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&&a.jsx(ct,{className:"w-4 h-4 animate-spin"}),p?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:a.jsx(va,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),a.jsxs("button",{onClick:g,disabled:i||!p?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:p?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[i&&a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!p?.enabled&&a.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:a.jsxs("p",{className:"text-sm text-bambu-gray",children:[a.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),a.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),a.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),a.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),a.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),a.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),a.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),a.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),a.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),a.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),a.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),a.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),a.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),a.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),a.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),a.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),a.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]}),a.jsxs("li",{children:["• ",t("support.notItem7","IP addresses")]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], serial numbers with [SERIAL], and IP addresses with [IP].")})]}),a.jsx(Jnt,{})]})}),a.jsxs(eh,{title:t("system.database","Database"),icon:Ul,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[a.jsx(ga,{icon:Ul,label:t("system.dbEngine","Database Engine"),value:c.database.engine||"SQLite"}),a.jsx(ga,{icon:Ul,label:t("system.dbVersion","Version"),value:c.database.version||"unknown"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[a.jsx(ga,{icon:Qs,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),a.jsx(ga,{icon:Cc,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),a.jsx(ga,{icon:$a,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),a.jsx(ga,{icon:ct,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(ga,{icon:Pr,label:t("system.printers","Printers"),value:c.database.printers}),a.jsx(ga,{icon:Dw,label:t("system.filaments","Filaments"),value:c.database.filaments}),a.jsx(ga,{icon:js,label:t("system.projects","Projects"),value:c.database.projects}),a.jsx(ga,{icon:ql,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[a.jsx(ga,{icon:rr,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),a.jsx(ga,{icon:Qs,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),a.jsxs(eh,{title:t("system.connectedPrinters","Connected Printers"),icon:Pr,children:[a.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[a.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),a.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?a.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(P=>a.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),a.jsx("span",{className:"font-medium text-white",children:P.name})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[a.jsx("span",{children:P.model}),a.jsx("span",{className:`px-2 py-0.5 rounded ${P.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":P.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:P.state})]})]},P.id))}):a.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),a.jsx(eh,{title:t("system.storage","Storage"),icon:ty,children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),a.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),a.jsx(cX,{percent:c.storage.disk_percent_used,color:_}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(ga,{icon:Qs,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),a.jsx(ga,{icon:Ul,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),y&&a.jsx(ga,{icon:Fc,label:t("system.fileManagerStorage","File Manager"),value:ert(y.total_size_bytes),subValue:`${y.total_files} files, ${y.total_folders} folders`})]})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(eh,{title:t("system.memory","Memory"),icon:Uge,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),a.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),a.jsx(cX,{percent:c.memory.percent_used,color:k}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),a.jsx(eh,{title:t("system.cpu","CPU"),icon:T_,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(ga,{icon:T_,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),a.jsx(ga,{icon:T_,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),a.jsx(eh,{title:t("system.systemDetails","System Details"),icon:Vp,children:a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(ga,{icon:Vp,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),a.jsx(ga,{icon:T_,label:t("system.architecture","Architecture"),value:c.system.architecture}),a.jsx(ga,{icon:Vp,label:t("system.python","Python"),value:c.system.python_version}),a.jsx(ga,{icon:rr,label:t("system.bootTime","Boot Time"),value:Bf(c.system.boot_time,v)})]})})]})}function nrt(){const t=Eo(),{t:e}=Lt(),{login:n}=_r(),{showToast:r}=xn(),{mode:i}=cg(),[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!1),[m,p]=w.useState(""),{data:f}=et({queryKey:["advancedAuthStatus"],queryFn:()=>pe.getAdvancedAuthStatus()}),y=lt({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=lt({mutationFn:_=>pe.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),u(!1),p("")},onError:_=>{r(_.message,"error")}}),b=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}y.mutate()},g=_=>{if(_.preventDefault(),!m){r("Please enter your email address","error");return}v.mutate(m)};return a.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[a.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:i==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:b,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:f?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),a.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:f?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),a.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:y.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:y.isPending?e("login.signingIn"):e("login.signIn")})}),f?.advanced_auth_enabled&&a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",onClick:()=>u(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),d&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>u(!1),children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(vx,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{u(!1),p("")},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsx(Rt,{children:f?.advanced_auth_enabled?a.jsxs("form",{onSubmit:g,className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),a.jsx("input",{id:"forgot-email",type:"email",required:!0,value:m,onChange:_=>p(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.emailPlaceholder")||"your.email@example.com"})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{u(!1),p("")},children:e("login.cancel")||"Cancel"}),a.jsx(Ie,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),a.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[a.jsx("li",{children:e("login.resetStep1")}),a.jsx("li",{children:e("login.resetStep2")}),a.jsx("li",{children:e("login.resetStep3")}),a.jsx("li",{children:e("login.resetStep4")})]})]}),a.jsx(Ie,{variant:"secondary",className:"w-full",onClick:()=>u(!1),children:e("login.gotIt")})]})})]})})]})}function rrt(){const t=Eo(),{t:e}=Lt(),{showToast:n}=xn(),{mode:r}=cg(),{refreshAuth:i}=_r(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[d,u]=w.useState(""),[m,p]=w.useState(""),f=lt({mutationFn:()=>pe.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?d:void 0}),onSuccess:async v=>{await i(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),y=v=>{if(v.preventDefault(),s&&(l||d)){if(!l||!d){n(e("setup.toast.enterBothCredentials"),"error");return}if(d!==m){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(d.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}f.mutate()};return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:a.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:y,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),a.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&a.jsxs("div",{className:"space-y-4 mt-4",children:[a.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),a.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.jsx("input",{id:"admin-password",type:"password",value:d,onChange:v=>u(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),d&&a.jsxs("div",{children:[a.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),a.jsx("input",{id:"confirm-password",type:"password",value:m,onChange:v=>p(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:f.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:f.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function art(){const{t}=Lt(),{user:e}=_r(),{showToast:n}=xn(),r=mn(),i=Eo(),[s,o]=w.useState(!0),[l,c]=w.useState(!0),[d,u]=w.useState(!0),[m,p]=w.useState(!0),[f,y]=w.useState(!1),{data:v,isLoading:b}=et({queryKey:["advancedAuthStatus"],queryFn:pe.getAdvancedAuthStatus,staleTime:300*1e3}),{data:g,isLoading:_}=et({queryKey:["settings"],queryFn:pe.getSettings,staleTime:300*1e3}),{data:k,isLoading:P}=et({queryKey:["user-email-preferences"],queryFn:()=>pe.getUserEmailPreferences()});w.useEffect(()=>{(v&&!v.advanced_auth_enabled||g&&!g.user_notifications_enabled)&&i("/settings",{replace:!0})},[v,g,i]),w.useEffect(()=>{k&&(o(k.notify_print_start),c(k.notify_print_complete),u(k.notify_print_failed),p(k.notify_print_stopped),y(!1))},[k]);const N=lt({mutationFn:()=>pe.updateUserEmailPreferences({notify_print_start:s,notify_print_complete:l,notify_print_failed:d,notify_print_stopped:m}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-email-preferences"]}),y(!1),n(t("notifications.userEmail.saveSuccess"),"success")},onError:A=>{n(A.message||t("notifications.userEmail.saveError"),"error")}}),M=(A,T)=>{A(!T),y(!0)};return P||b||_?a.jsx("div",{className:"flex items-center justify-center h-64",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"p-4 md:p-6 max-w-2xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsx(Ah,{className:"w-7 h-7 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("notifications.userEmail.title")})]}),a.jsx(Dt,{className:"mb-6 border-blue-500/30 bg-blue-500/5",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(vx,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:t("notifications.userEmail.emailNotifications")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.emailNotificationsDesc")}),e?.email?a.jsxs("p",{className:"text-sm text-blue-400 mt-2",children:[t("notifications.userEmail.sendingTo"),": ",a.jsx("strong",{children:e.email})]}):a.jsx("p",{className:"text-sm text-yellow-400 mt-2",children:t("notifications.userEmail.noEmailWarning")})]})]})})}),a.jsxs(Dt,{className:"mb-6",children:[a.jsxs(Dn,{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("notifications.userEmail.printJobNotifications")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.printJobNotificationsDesc")})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${s?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cc,{className:`w-5 h-5 ${s?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStarts")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStartsDesc")})]})]}),a.jsx("button",{onClick:()=>M(o,s),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${s?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":s,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cc,{className:`w-5 h-5 ${l?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobFinishes")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobFinishesDesc")})]})]}),a.jsx("button",{onClick:()=>M(c,l),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":l,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${d?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cc,{className:`w-5 h-5 ${d?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printErrors")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printErrorsDesc")})]})]}),a.jsx("button",{onClick:()=>M(u,d),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${d?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":d,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${d?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${m?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cc,{className:`w-5 h-5 ${m?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStops")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStopsDesc")})]})]}),a.jsx("button",{onClick:()=>M(p,m),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${m?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":m,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${m?"translate-x-6":"translate-x-1"}`})})]})]})]}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Ie,{onClick:()=>N.mutate(),disabled:!f||N.isPending||!e?.email,children:N.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),t("common.save")]})})})]})}function irt(){const t=w.useRef(null),e=w.useRef(null),n=mn(),[r,i]=w.useState(!1),s=w.useRef(new Map),{showToast:o}=xn(),{t:l}=Lt(),c=w.useRef(new Set),d=w.useRef(null),u=w.useRef(new Map),m=w.useRef(null),p=w.useRef([]),f=w.useRef(!1),y=w.useRef(()=>{}),v=w.useCallback(()=>{if(f.current||p.current.length===0)return;f.current=!0;const N=()=>{const M=p.current.shift();M?requestAnimationFrame(()=>{y.current(M),p.current.length>0?setTimeout(N,16):f.current=!1}):f.current=!1};N()},[]),b=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const M=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,A=new WebSocket(M);let T=null;A.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),T=window.setInterval(()=>{A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"ping"}))},3e4)},A.onmessage=C=>{try{const F=JSON.parse(C.data);F.type==="printer_status"&&F.printer_id!==void 0&&F.data?y.current(F):(p.current.push(F),v())}catch{}},A.onclose=C=>{console.log("[WebSocket] Closed",C.code,C.reason),T&&(clearInterval(T),T=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{b()},3e3)},A.onerror=C=>{console.error("[WebSocket] Error",C),A.close()},t.current=A},[v]),g=w.useCallback((N,M)=>{const A=u.current.get(N)||{};u.current.set(N,{...A,...M}),m.current||(m.current=window.setTimeout(()=>{const T=new Map(u.current);u.current.clear(),m.current=null,requestAnimationFrame(()=>{T.forEach((C,F)=>{n.setQueryData(["printerStatus",F],$=>{const I={...$,...C};return I.wifi_signal==null&&$?.wifi_signal!=null&&(I.wifi_signal=$.wifi_signal),I})})})},100))},[n]),_=w.useCallback(N=>{c.current.add(N),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{const M=Array.from(c.current);c.current.clear(),d.current=null;let A=0;M.forEach(T=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[T]})})},A),A+=500})},3e3)},[n]),k=w.useCallback(N=>{switch(N.type){case"printer_status":N.printer_id!==void 0&&N.data&&g(N.printer_id,N.data);break;case"print_start":N.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",N.printer_id]});break;case"missing_spool_assignment":{if(N.printer_id===void 0||!Array.isArray(N.missing_slots))break;const M=N.missing_slots.map(F=>F&&typeof F.slot=="string"?F.slot:"Unknown").filter(F=>F.length>0);if(M.length===0){s.current.delete(N.printer_id);break}const A=M.join("|");if(s.current.get(N.printer_id)===A)break;s.current.set(N.printer_id,A);const T=N.printer_name||`Printer ${N.printer_id}`,C=l("printers.toast.missingSpoolAssignment",{printer:T,slots:M.join(", ")});o(C,"warning");break}case"print_complete":_("archives"),_("archiveStats");break;case"archive_created":_("archives"),_("archiveStats");break;case"archive_updated":_("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:N.printer_id,printer_name:N.printer_name,message:N.message}}));break;case"inventory_changed":_("inventory-spools");break;case"spool_assignment_changed":_("spool-assignments"),_("slotPresets");break;case"spool_auto_assigned":_("inventory-spools"),_("spool-assignments");break;case"spool_usage_logged":_("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:N.printer_id,ams_id:N.ams_id,tray_id:N.tray_id,tag_uid:N.tag_uid,tray_uuid:N.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:N.data||{}}));break;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:N}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:N})),_("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:N}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:N}));break;case"spoolbuddy_tag_written":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-written",{detail:N})),_("inventory-spools");break;case"spoolbuddy_tag_write_failed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-write-failed",{detail:N}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:N})),_("spoolbuddy-devices"),_("spoolbuddy-update-check");break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:N})),_("spoolbuddy-devices");break;case"spoolbuddy_update":_("spoolbuddy-devices"),_("spoolbuddy-update-check");break}},[n,_,g,o,l]);w.useEffect(()=>{y.current=k},[k]),w.useEffect(()=>(b(),()=>{e.current&&clearTimeout(e.current),d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),t.current&&t.current.close()}),[b]);const P=w.useCallback(N=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(N))},[]);return{isConnected:r,sendMessage:P}}function srt(){const{authEnabled:t}=_r(),e=mn(),n=w.useRef(!1),{data:r}=et({queryKey:["camera-stream-token"],queryFn:()=>pe.getCameraStreamToken(),enabled:t,staleTime:3e3*1e3,refetchInterval:3e3*1e3});w.useEffect(()=>(p6(r?.token??null),()=>p6(null)),[r?.token]),w.useEffect(()=>{if(!t)return;const i=s=>{const o=s.target;if(!(o instanceof HTMLImageElement||o instanceof HTMLVideoElement))return;const l=o.src||"",c=Mxe();!c||!l.includes(`token=${encodeURIComponent(c)}`)||n.current||(n.current=!0,e.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{n.current=!1},5e3))};return document.addEventListener("error",i,!0),()=>document.removeEventListener("error",i,!0)},[t,e])}function ort({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:r}=Lt(),[i,s]=w.useState(new Date),{data:o=[]}=et({queryKey:["printers"],queryFn:()=>pe.getPrinters()}),l=ep({queries:o.map(u=>({queryKey:["printerStatus",u.id],queryFn:()=>pe.getPrinterStatus(u.id),refetchInterval:1e4}))}),c=w.useMemo(()=>o.filter((u,m)=>l[m]?.data?.connected),[o,l]);w.useEffect(()=>{const u=c.some(m=>m.id===t);(!t||!u)&&c.length>0&&e(c[0].id)},[c,t,e]);const{data:d}=et({queryKey:["settings"],queryFn:pe.getSettings});return w.useEffect(()=>{const u=setInterval(()=>s(new Date),1e3);return()=>clearInterval(u)},[]),a.jsxs("div",{className:"h-12 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-3 gap-4 shrink-0",children:[a.jsx("div",{className:"flex items-center shrink-0",children:a.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",width:113,height:28,className:"h-7 w-auto"})}),a.jsx("div",{className:"flex-1 flex justify-center",children:a.jsx("select",{value:t??"",onChange:u=>e(Number(u.target.value)),className:"bg-bambu-dark text-white text-base px-4 py-2 rounded border border-bambu-dark-tertiary focus:outline-none focus:border-bambu-green min-w-[180px]",children:c.length===0?a.jsx("option",{value:"",children:r("spoolbuddy.status.noPrinters","No printers online")}):c.map(u=>a.jsx("option",{value:u.id,children:u.name},u.id))})}),a.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[a.jsx("div",{className:"flex items-center",title:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline"),children:n?a.jsx("div",{className:"flex items-end gap-0.5 h-4",children:[1,2,3,4].map(u=>a.jsx("div",{className:`w-1 rounded-sm ${u<=4?"bg-white":"bg-bambu-dark-tertiary"}`,style:{height:`${u*4}px`}},u))}):a.jsx(Ku,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${n?"bg-bambu-green shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-bambu-gray"}`}),a.jsx("span",{className:"text-sm text-white/50",children:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline")})]}),a.jsx("span",{className:"text-white/50 text-base font-mono min-w-[50px] text-right",children:DQ(i,d?.time_format||"system")})]})]})}const lrt=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})})},{to:"/spoolbuddy/ams",labelKey:"spoolbuddy.nav.ams",fallback:"AMS",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})},{to:"/spoolbuddy/write-tag",labelKey:"spoolbuddy.nav.writeTag",fallback:"Write",icon:a.jsxs("svg",{className:"w-6 h-6",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})},{to:"/spoolbuddy/inventory",labelKey:"spoolbuddy.nav.inventory",fallback:"Inventory",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})},{to:"/spoolbuddy/settings",labelKey:"spoolbuddy.nav.settings",fallback:"Settings",icon:a.jsxs("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function crt(){const{t}=Lt();return a.jsx("nav",{className:"h-14 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-stretch shrink-0",children:lrt.map(e=>a.jsxs(Gb,{to:e.to,end:e.to==="/spoolbuddy",className:({isActive:n})=>`flex-1 flex flex-col items-center justify-center gap-1 transition-colors ${n?"text-bambu-green bg-bambu-dark":"text-white/50 hover:text-white/70 hover:bg-bambu-dark-tertiary"}`,children:[e.icon,a.jsx("span",{className:"text-xs font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}function drt({alert:t}){const{t:e}=Lt(),n=t?t.type==="error"?"bg-red-500":t.type==="warning"?"bg-amber-500":"bg-bambu-green":"bg-bambu-green",r=t?t.type==="error"?"border-red-500":t.type==="warning"?"border-amber-500":"border-bambu-dark-tertiary":"border-bambu-dark-tertiary";return a.jsxs("div",{className:`h-9 bg-bambu-dark-secondary border-t-2 ${r} flex items-center px-3 gap-3 shrink-0`,children:[a.jsx("div",{className:`w-3.5 h-3.5 rounded-full ${n}`}),a.jsx("div",{className:"flex-1 text-sm text-white/50 truncate",children:t?a.jsx("span",{children:t.message}):a.jsx("span",{className:"text-bambu-green",children:e("spoolbuddy.status.systemReady","System Ready")})})]})}function urt({isOpen:t,onClose:e,deviceId:n,deviceOnline:r}){const{t:i}=Lt(),[s,o]=w.useState(null),[l,c]=w.useState(!1),[d,u]=w.useState(new Map),{data:m=[]}=et({queryKey:["printers"],queryFn:()=>pe.getPrinters(),enabled:t}),{data:p=[]}=et({queryKey:["smart-plugs"],queryFn:()=>pe.getSmartPlugs(),enabled:t}),f=m.map(_=>{const k=p.find(N=>N.printer_id===_.id&&N.plug_type!=="mqtt"&&N.enabled);if(!k)return null;const P=d.get(k.id);return{plug:k,printer:_,status:P?{state:P.state,reachable:!0,device_name:null,energy:null}:null,loading:P?.loading??!1}}).filter(Boolean);w.useEffect(()=>{if(!t||p.length===0)return;p.filter(k=>k.printer_id!==null&&k.plug_type!=="mqtt"&&k.enabled).forEach(async k=>{try{const P=await pe.getSmartPlugStatus(k.id);u(N=>{const M=new Map(N);return M.set(k.id,{loading:!1,state:P.state}),M})}catch{u(P=>{const N=new Map(P);return N.set(k.id,{loading:!1,state:null}),N})}})},[t,p]),w.useEffect(()=>{t||(o(null),c(!1))},[t]);const y=w.useCallback(async _=>{u(k=>{const P=new Map(k),N=P.get(_.id);return P.set(_.id,{loading:!0,state:N?.state??null}),P});try{await pe.controlSmartPlug(_.id,"toggle");const k=await pe.getSmartPlugStatus(_.id);u(P=>{const N=new Map(P);return N.set(_.id,{loading:!1,state:k.state}),N})}catch{u(k=>{const P=new Map(k),N=P.get(_.id);return P.set(_.id,{loading:!1,state:N?.state??null}),P})}},[]),v=w.useCallback(async _=>{if(n){c(!0);try{await wa.systemCommand(n,_),setTimeout(()=>e(),500)}catch{c(!1)}}},[n,e]),b=w.useCallback(()=>{s&&(s.type==="system"?v(s.command):y(s.plug),o(null))},[s,v,y]);if(!t)return null;const g=_=>_==="ON"||_==="on";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40 bg-black/50",onPointerDown:e}),a.jsxs("div",{className:"fixed top-0 left-0 right-0 z-50 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-b-2xl shadow-2xl animate-slide-down",children:[a.jsx("div",{className:"flex justify-center pt-2 pb-1",children:a.jsx("div",{className:"w-10 h-1 rounded-full bg-zinc-600"})}),a.jsxs("div",{className:"px-4 pb-4 max-h-[80vh] overflow-y-auto",children:[f.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.printerPower","Printer Power")}),a.jsx("div",{className:"space-y-1",children:f.map(({plug:_,printer:k,loading:P})=>{const N=d.get(_.id),M=g(N?.state??null);return a.jsxs("button",{onClick:()=>o({type:"plug",plug:_,printer:k,currentState:N?.state??null}),disabled:P,className:"w-full flex items-center gap-2 px-3 py-1.5 rounded-lg bg-zinc-800/60 hover:bg-zinc-700/60 transition-colors min-h-[36px]",children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${M?"bg-green-500":"bg-zinc-600"}`}),P&&a.jsx(ct,{className:"w-3 h-3 animate-spin text-zinc-400 shrink-0"}),a.jsx("span",{className:"flex-1 text-sm text-zinc-200 text-left truncate",children:k.name}),a.jsx("span",{className:`text-xs font-medium ${M?"text-green-400":"text-zinc-500"}`,children:N?.state??"—"})]},_.id)})})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.systemControls","System")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsx(gk,{icon:a.jsx(q3,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartDaemon","Restart Daemon"),onClick:()=>o({type:"system",command:"restart_daemon"}),disabled:!n||!r||l}),a.jsx(gk,{icon:a.jsx(xQ,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartBrowser","Restart Browser"),onClick:()=>o({type:"system",command:"restart_browser"}),disabled:!n||!r||l}),a.jsx(gk,{icon:a.jsx(q3,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.reboot","Reboot"),onClick:()=>o({type:"system",command:"reboot"}),disabled:!n||!r||l,variant:"warning"}),a.jsx(gk,{icon:a.jsx(Rw,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.shutdown","Shutdown"),onClick:()=>o({type:"system",command:"shutdown"}),disabled:!n||!r||l,variant:"danger"})]})]}),a.jsx("div",{className:"flex justify-center mt-3",children:a.jsxs("div",{className:"flex items-center gap-1 text-xs text-zinc-600",children:[a.jsx(Fn,{className:"w-3 h-3"}),a.jsx("span",{children:i("spoolbuddy.quickMenu.swipeToClose","Swipe down to close")})]})})]})]}),s&&a.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/60",children:a.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-5 mx-4 max-w-sm w-full border border-zinc-700",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-2",children:i("spoolbuddy.quickMenu.confirmTitle","Confirm")}),a.jsx("p",{className:"text-sm text-zinc-400 mb-5",children:s.type==="plug"?g(s.currentState)?i("spoolbuddy.quickMenu.confirmPlugOff","Turn off {{name}}?",{name:s.printer.name}):i("spoolbuddy.quickMenu.confirmPlugOn","Turn on {{name}}?",{name:s.printer.name}):s.command==="shutdown"?i("spoolbuddy.quickMenu.confirmShutdown","Are you sure you want to shut down the SpoolBuddy? You will need physical access to turn it back on."):s.command==="reboot"?i("spoolbuddy.quickMenu.confirmReboot","Are you sure you want to reboot the SpoolBuddy?"):s.command==="restart_daemon"?i("spoolbuddy.quickMenu.confirmRestartDaemon","Restart the SpoolBuddy daemon? NFC and scale will be temporarily unavailable."):i("spoolbuddy.quickMenu.confirmRestartBrowser","Restart the kiosk browser? The display will briefly go blank.")}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:()=>o(null),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:i("common.cancel","Cancel")}),a.jsx("button",{onClick: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"?g(s.currentState)?"bg-red-600 hover:bg-red-700":"bg-green-600 hover:bg-green-700":s.command==="shutdown"?"bg-red-600 hover:bg-red-700":s.command==="reboot"?"bg-amber-600 hover:bg-amber-700":"bg-blue-600 hover:bg-blue-700"} disabled:opacity-50`,children:l?a.jsx(ct,{className:"w-4 h-4 animate-spin mx-auto"}):s.type==="plug"?g(s.currentState)?i("spoolbuddy.quickMenu.turnOff","Turn Off"):i("spoolbuddy.quickMenu.turnOn","Turn On"):i("spoolbuddy.quickMenu.confirm","Confirm")})]})]})})]})}function gk({icon:t,label:e,onClick:n,disabled:r,variant:i="default"}){const s={default:"bg-zinc-800/60 hover:bg-zinc-700/60 text-zinc-300",warning:"bg-amber-900/30 hover:bg-amber-900/50 text-amber-400",danger:"bg-red-900/30 hover:bg-red-900/50 text-red-400"};return a.jsxs("button",{onClick:n,disabled:r,className:`flex items-center gap-2.5 p-3 rounded-xl transition-colors min-h-[48px] disabled:opacity-40 ${s[i]}`,children:[t,a.jsx("span",{className:"text-sm font-medium",children:e})]})}const mrt={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,deviceOnline:!1,deviceId:null};function hrt(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.weight,weightStable:e.stable,rawAdc:e.rawAdc,deviceId:e.deviceId,deviceOnline:!0};case"TAG_MATCHED":return{...t,matchedSpool:e.spool,unknownTagUid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0,deviceId:e.deviceId};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null,weightStable:!1,rawAdc:null};default:return t}}function prt(){const[t,e]=w.useReducer(hrt,mrt),n=w.useCallback(u=>{const m=u.detail;e({type:"WEIGHT_UPDATE",weight:m.weight_grams??m.data?.weight_grams,stable:m.stable??m.data?.stable??!1,rawAdc:m.raw_adc??m.data?.raw_adc??null,deviceId:m.device_id??m.data?.device_id??""})},[]),r=w.useCallback(u=>{const m=u.detail,p=m.spool??m.data?.spool;p&&e({type:"TAG_MATCHED",spool:{id:p.id,tag_uid:m.tag_uid??m.data?.tag_uid??"",material:p.material??"",subtype:p.subtype??null,color_name:p.color_name??null,rgba:p.rgba??null,brand:p.brand??null,label_weight:p.label_weight??0,core_weight:p.core_weight??0,weight_used:p.weight_used??0},deviceId:m.device_id??m.data?.device_id??""})},[]),i=w.useCallback(u=>{const m=u.detail;e({type:"UNKNOWN_TAG",tagUid:m.tag_uid??m.data?.tag_uid??"",deviceId:m.device_id??m.data?.device_id??""})},[]),s=w.useCallback(u=>{const m=u.detail;e({type:"TAG_REMOVED",deviceId:m.device_id??m.data?.device_id??""})},[]),o=w.useCallback(u=>{const m=u.detail;e({type:"DEVICE_ONLINE",deviceId:m.device_id??m.data?.device_id??""})},[]),l=w.useCallback(u=>{const m=u.detail;e({type:"DEVICE_OFFLINE",deviceId:m.device_id??m.data?.device_id??""})},[]);w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",i),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-online",o),window.addEventListener("spoolbuddy-offline",l),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",i),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,r,i,s,o,l]);const c=t.matchedSpool?Math.max(0,t.matchedSpool.label_weight-t.matchedSpool.weight_used):null,d=t.weight!==null&&t.matchedSpool?Math.max(0,t.weight-t.matchedSpool.core_weight):null;return{...t,remainingWeight:c,netWeight:d}}var Vk={exports:{}};var frt=Vk.exports,dX;function grt(){return dX||(dX=1,(function(t,e){(function(n,r){t.exports=r(og())})(frt,(function(n){return(function(){var r={981:function(){typeof Element>"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function(l){if("Element"in l){var c="classList",d="prototype",u=l.Element[d],m=Object,p=String[d].trim||function(){return this.replace(/^\s+|\s+$/g,"")},f=Array[d].indexOf||function(P){for(var N=0,M=this.length;N<M;N++)if(N in this&&this[N]===P)return N;return-1},y=function(P,N){this.name=P,this.code=DOMException[P],this.message=N},v=function(P,N){if(N==="")throw new y("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(N))throw new y("INVALID_CHARACTER_ERR","The token must not contain space characters.");return f.call(P,N)},b=function(P){for(var N=p.call(P.getAttribute("class")||""),M=N?N.split(/\s+/):[],A=0,T=M.length;A<T;A++)this.push(M[A]);this._updateClassName=function(){P.setAttribute("class",this.toString())}},g=b[d]=[],_=function(){return new b(this)};if(y[d]=Error[d],g.item=function(P){return this[P]||null},g.contains=function(P){return~v(this,P+"")},g.add=function(){var P,N=arguments,M=0,A=N.length,T=!1;do~v(this,P=N[M]+"")||(this.push(P),T=!0);while(++M<A);T&&this._updateClassName()},g.remove=function(){var P,N,M=arguments,A=0,T=M.length,C=!1;do for(N=v(this,P=M[A]+"");~N;)this.splice(N,1),C=!0,N=v(this,P);while(++A<T);C&&this._updateClassName()},g.toggle=function(P,N){var M=this.contains(P),A=M?N!==!0&&"remove":N!==!1&&"add";return A&&this[A](P),N===!0||N===!1?N:!M},g.replace=function(P,N){var M=v(P+"");~M&&(this.splice(M,1,N),this._updateClassName())},g.toString=function(){return this.join(" ")},m.defineProperty){var k={get:_,enumerable:!0,configurable:!0};try{m.defineProperty(u,c,k)}catch(P){P.number!==void 0&&P.number!==-2146823252||(k.enumerable=!1,m.defineProperty(u,c,k))}}else m[d].__defineGetter__&&u.__defineGetter__(c,_)}})(self),(function(){var l=document.createElement("_");if(l.classList.add("c1","c2"),!l.classList.contains("c2")){var c=function(u){var m=DOMTokenList.prototype[u];DOMTokenList.prototype[u]=function(p){var f,y=arguments.length;for(f=0;f<y;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(B,Y,D){var j=D(4901),z=D(6823),W=TypeError;B.exports=function(q){if(j(q))return q;throw new W(z(q)+" is not a function")}},5548:function(B,Y,D){var j=D(3517),z=D(6823),W=TypeError;B.exports=function(q){if(j(q))return q;throw new W(z(q)+" is not a constructor")}},3506:function(B,Y,D){var j=D(3925),z=String,W=TypeError;B.exports=function(q){if(j(q))return q;throw new W("Can't set "+z(q)+" as a prototype")}},6469:function(B,Y,D){var j=D(8227),z=D(2360),W=D(4913).f,q=j("unscopables"),de=Array.prototype;de[q]===void 0&&W(de,q,{configurable:!0,value:z(null)}),B.exports=function(O){de[q][O]=!0}},7829:function(B,Y,D){var j=D(8183).charAt;B.exports=function(z,W,q){return W+(q?j(z,W).length:1)}},8551:function(B,Y,D){var j=D(34),z=String,W=TypeError;B.exports=function(q){if(j(q))return q;throw new W(z(q)+" is not an object")}},235:function(B,Y,D){var j=D(9213).forEach,z=D(4598)("forEach");B.exports=z?[].forEach:function(W){return j(this,W,arguments.length>1?arguments[1]:void 0)}},7916:function(B,Y,D){var j=D(6080),z=D(9565),W=D(8981),q=D(6319),de=D(4209),O=D(3517),G=D(6198),Q=D(4659),V=D(4527),J=D(81),ie=D(851),he=Array;B.exports=function(fe){var se=W(fe),U=O(this),R=arguments.length,re=R>1?arguments[1]:void 0,xe=re!==void 0;xe&&(re=j(re,R>2?arguments[2]:void 0));var we,ye,Ae,ve,Te,Fe,Ee=ie(se),Se=0;if(!Ee||this===he&&de(Ee))for(we=G(se),ye=U?new this(we):he(we);we>Se;Se++)Fe=xe?re(se[Se],Se):se[Se],Q(ye,Se,Fe);else for(ye=U?new this:[],Te=(ve=J(se,Ee)).next;!(Ae=z(Te,ve)).done;Se++)Fe=xe?q(ve,re,[Ae.value,Se],!0):Ae.value,Q(ye,Se,Fe);return V(ye,Se),ye}},9617:function(B,Y,D){var j=D(5397),z=D(5610),W=D(6198),q=function(de){return function(O,G,Q){var V=j(O),J=W(V);if(J===0)return!de&&-1;var ie,he=z(Q,J);if(de&&G!=G){for(;J>he;)if((ie=V[he++])!=ie)return!0}else for(;J>he;he++)if((de||he in V)&&V[he]===G)return de||he||0;return!de&&-1}};B.exports={includes:q(!0),indexOf:q(!1)}},9213:function(B,Y,D){var j=D(6080),z=D(7055),W=D(8981),q=D(6198),de=D(1469),O=D(4659),G=function(Q){var V=Q===1,J=Q===2,ie=Q===3,he=Q===4,fe=Q===6,se=Q===7,U=Q===5||fe;return function(R,re,xe){for(var we,ye,Ae=W(R),ve=z(Ae),Te=q(ve),Fe=j(re,xe),Ee=0,Se=0,je=V?de(R,Te):J||se?de(R,0):void 0;Te>Ee;Ee++)if((U||Ee in ve)&&(ye=Fe(we=ve[Ee],Ee,Ae),Q))if(V)O(je,Ee,ye);else if(ye)switch(Q){case 3:return!0;case 5:return we;case 6:return Ee;case 2:O(je,Se++,we)}else switch(Q){case 4:return!1;case 7:O(je,Se++,we)}return fe?-1:ie||he?he:je}};B.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(B,Y,D){var j=D(9039),z=D(8227),W=D(9519),q=z("species");B.exports=function(de){return W>=51||!j((function(){var O=[];return(O.constructor={})[q]=function(){return{foo:1}},O[de](Boolean).foo!==1}))}},4598:function(B,Y,D){var j=D(9039);B.exports=function(z,W){var q=[][z];return!!q&&j((function(){q.call(null,W||function(){return 1},1)}))}},926:function(B,Y,D){var j=D(9306),z=D(8981),W=D(7055),q=D(6198),de=TypeError,O="Reduce of empty array with no initial value",G=function(Q){return function(V,J,ie,he){var fe=z(V),se=W(fe),U=q(fe);if(j(J),U===0&&ie<2)throw new de(O);var R=Q?U-1:0,re=Q?-1:1;if(ie<2)for(;;){if(R in se){he=se[R],R+=re;break}if(R+=re,Q?R<0:U<=R)throw new de(O)}for(;Q?R>=0:U>R;R+=re)R in se&&(he=J(he,se[R],R,fe));return he}};B.exports={left:G(!1),right:G(!0)}},4527:function(B,Y,D){var j=D(3724),z=D(4376),W=TypeError,q=Object.getOwnPropertyDescriptor,de=j&&!(function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(O){return O instanceof TypeError}})();B.exports=de?function(O,G){if(z(O)&&!q(O,"length").writable)throw new W("Cannot set read only .length");return O.length=G}:function(O,G){return O.length=G}},7680:function(B,Y,D){var j=D(9504);B.exports=j([].slice)},4488:function(B,Y,D){var j=D(7680),z=Math.floor,W=function(q,de){var O=q.length;if(O<8)for(var G,Q,V=1;V<O;){for(Q=V,G=q[V];Q&&de(q[Q-1],G)>0;)q[Q]=q[--Q];Q!==V++&&(q[Q]=G)}else for(var J=z(O/2),ie=W(j(q,0,J),de),he=W(j(q,J),de),fe=ie.length,se=he.length,U=0,R=0;U<fe||R<se;)q[U+R]=U<fe&&R<se?de(ie[U],he[R])<=0?ie[U++]:he[R++]:U<fe?ie[U++]:he[R++];return q};B.exports=W},7433:function(B,Y,D){var j=D(4376),z=D(3517),W=D(34),q=D(8227)("species"),de=Array;B.exports=function(O){var G;return j(O)&&(G=O.constructor,(z(G)&&(G===de||j(G.prototype))||W(G)&&(G=G[q])===null)&&(G=void 0)),G===void 0?de:G}},1469:function(B,Y,D){var j=D(7433);B.exports=function(z,W){return new(j(z))(W===0?0:W)}},6319:function(B,Y,D){var j=D(8551),z=D(9539);B.exports=function(W,q,de,O){try{return O?q(j(de)[0],de[1]):q(de)}catch(G){z(W,"throw",G)}}},4428:function(B,Y,D){var j=D(8227)("iterator"),z=!1;try{var W=0,q={next:function(){return{done:!!W++}},return:function(){z=!0}};q[j]=function(){return this},Array.from(q,(function(){throw 2}))}catch{}B.exports=function(de,O){try{if(!O&&!z)return!1}catch{return!1}var G=!1;try{var Q={};Q[j]=function(){return{next:function(){return{done:G=!0}}}},de(Q)}catch{}return G}},2195:function(B,Y,D){var j=D(9504),z=j({}.toString),W=j("".slice);B.exports=function(q){return W(z(q),8,-1)}},6955:function(B,Y,D){var j=D(2140),z=D(4901),W=D(2195),q=D(8227)("toStringTag"),de=Object,O=W((function(){return arguments})())==="Arguments";B.exports=j?W:function(G){var Q,V,J;return G===void 0?"Undefined":G===null?"Null":typeof(V=(function(ie,he){try{return ie[he]}catch{}})(Q=de(G),q))=="string"?V:O?W(Q):(J=W(Q))==="Object"&&z(Q.callee)?"Arguments":J}},7740:function(B,Y,D){var j=D(9297),z=D(5031),W=D(7347),q=D(4913);B.exports=function(de,O,G){for(var Q=z(O),V=q.f,J=W.f,ie=0;ie<Q.length;ie++){var he=Q[ie];j(de,he)||G&&j(G,he)||V(de,he,J(O,he))}}},1436:function(B,Y,D){var j=D(8227)("match");B.exports=function(z){var W=/./;try{"/./"[z](W)}catch{try{return W[j]=!1,"/./"[z](W)}catch{}}return!1}},2211:function(B,Y,D){var j=D(9039);B.exports=!j((function(){function z(){}return z.prototype.constructor=null,Object.getPrototypeOf(new z)!==z.prototype}))},2529:function(B){B.exports=function(Y,D){return{value:Y,done:D}}},6699:function(B,Y,D){var j=D(3724),z=D(4913),W=D(6980);B.exports=j?function(q,de,O){return z.f(q,de,W(1,O))}:function(q,de,O){return q[de]=O,q}},6980:function(B){B.exports=function(Y,D){return{enumerable:!(1&Y),configurable:!(2&Y),writable:!(4&Y),value:D}}},4659:function(B,Y,D){var j=D(3724),z=D(4913),W=D(6980);B.exports=function(q,de,O){j?z.f(q,de,W(0,O)):q[de]=O}},3640:function(B,Y,D){var j=D(8551),z=D(4270),W=TypeError;B.exports=function(q){if(j(this),q==="string"||q==="default")q="string";else if(q!=="number")throw new W("Incorrect hint");return z(this,q)}},2106:function(B,Y,D){var j=D(283),z=D(4913);B.exports=function(W,q,de){return de.get&&j(de.get,q,{getter:!0}),de.set&&j(de.set,q,{setter:!0}),z.f(W,q,de)}},6840:function(B,Y,D){var j=D(4901),z=D(4913),W=D(283),q=D(9433);B.exports=function(de,O,G,Q){Q||(Q={});var V=Q.enumerable,J=Q.name!==void 0?Q.name:O;if(j(G)&&W(G,J,Q),Q.global)V?de[O]=G:q(O,G);else{try{Q.unsafe?de[O]&&(V=!0):delete de[O]}catch{}V?de[O]=G:z.f(de,O,{value:G,enumerable:!1,configurable:!Q.nonConfigurable,writable:!Q.nonWritable})}return de}},9433:function(B,Y,D){var j=D(4576),z=Object.defineProperty;B.exports=function(W,q){try{z(j,W,{value:q,configurable:!0,writable:!0})}catch{j[W]=q}return q}},4606:function(B,Y,D){var j=D(6823),z=TypeError;B.exports=function(W,q){if(!delete W[q])throw new z("Cannot delete property "+j(q)+" of "+j(W))}},3724:function(B,Y,D){var j=D(9039);B.exports=!j((function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}))},4055:function(B,Y,D){var j=D(4576),z=D(34),W=j.document,q=z(W)&&z(W.createElement);B.exports=function(de){return q?W.createElement(de):{}}},6837:function(B){var Y=TypeError;B.exports=function(D){if(D>9007199254740991)throw Y("Maximum allowed index exceeded");return D}},7400:function(B){B.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(B,Y,D){var j=D(4055)("span").classList,z=j&&j.constructor&&j.constructor.prototype;B.exports=z===Object.prototype?void 0:z},8727:function(B){B.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3709:function(B,Y,D){var j=D(2839).match(/firefox\/(\d+)/i);B.exports=!!j&&+j[1]},3763:function(B,Y,D){var j=D(2839);B.exports=/MSIE|Trident/.test(j)},6193:function(B,Y,D){var j=D(4215);B.exports=j==="NODE"},2839:function(B,Y,D){var j=D(4576).navigator,z=j&&j.userAgent;B.exports=z?String(z):""},9519:function(B,Y,D){var j,z,W=D(4576),q=D(2839),de=W.process,O=W.Deno,G=de&&de.versions||O&&O.version,Q=G&&G.v8;Q&&(z=(j=Q.split("."))[0]>0&&j[0]<4?1:+(j[0]+j[1])),!z&&q&&(!(j=q.match(/Edge\/(\d+)/))||j[1]>=74)&&(j=q.match(/Chrome\/(\d+)/))&&(z=+j[1]),B.exports=z},3607:function(B,Y,D){var j=D(2839).match(/AppleWebKit\/(\d+)\./);B.exports=!!j&&+j[1]},4215:function(B,Y,D){var j=D(4576),z=D(2839),W=D(2195),q=function(de){return z.slice(0,de.length)===de};B.exports=q("Bun/")?"BUN":q("Cloudflare-Workers")?"CLOUDFLARE":q("Deno/")?"DENO":q("Node.js/")?"NODE":j.Bun&&typeof Bun.version=="string"?"BUN":j.Deno&&typeof Deno.version=="object"?"DENO":W(j.process)==="process"?"NODE":j.window&&j.document?"BROWSER":"REST"},6518:function(B,Y,D){var j=D(4576),z=D(7347).f,W=D(6699),q=D(6840),de=D(9433),O=D(7740),G=D(2796);B.exports=function(Q,V){var J,ie,he,fe,se,U=Q.target,R=Q.global,re=Q.stat;if(J=R?j:re?j[U]||de(U,{}):j[U]&&j[U].prototype)for(ie in V){if(fe=V[ie],he=Q.dontCallGetSet?(se=z(J,ie))&&se.value:J[ie],!G(R?ie:U+(re?".":"#")+ie,Q.forced)&&he!==void 0){if(typeof fe==typeof he)continue;O(fe,he)}(Q.sham||he&&he.sham)&&W(fe,"sham",!0),q(J,ie,fe,Q)}}},9039:function(B){B.exports=function(Y){try{return!!Y()}catch{return!0}}},9228:function(B,Y,D){D(7495);var j=D(9565),z=D(6840),W=D(7323),q=D(9039),de=D(8227),O=D(6699),G=de("species"),Q=RegExp.prototype;B.exports=function(V,J,ie,he){var fe=de(V),se=!q((function(){var xe={};return xe[fe]=function(){return 7},""[V](xe)!==7})),U=se&&!q((function(){var xe=!1,we=/a/;if(V==="split"){var ye={};ye[G]=function(){return we},(we={constructor:ye,flags:""})[fe]=/./[fe]}return we.exec=function(){return xe=!0,null},we[fe](""),!xe}));if(!se||!U||ie){var R=/./[fe],re=J(fe,""[V],(function(xe,we,ye,Ae,ve){var Te=we.exec;return Te===W||Te===Q.exec?se&&!ve?{done:!0,value:j(R,we,ye,Ae)}:{done:!0,value:j(xe,ye,we,Ae)}:{done:!1}}));z(String.prototype,V,re[0]),z(Q,fe,re[1])}he&&O(Q[fe],"sham",!0)}},8745:function(B,Y,D){var j=D(616),z=Function.prototype,W=z.apply,q=z.call;B.exports=typeof Reflect=="object"&&Reflect.apply||(j?q.bind(W):function(){return q.apply(W,arguments)})},6080:function(B,Y,D){var j=D(7476),z=D(9306),W=D(616),q=j(j.bind);B.exports=function(de,O){return z(de),O===void 0?de:W?q(de,O):function(){return de.apply(O,arguments)}}},616:function(B,Y,D){var j=D(9039);B.exports=!j((function(){var z=(function(){}).bind();return typeof z!="function"||z.hasOwnProperty("prototype")}))},566:function(B,Y,D){var j=D(9504),z=D(9306),W=D(34),q=D(9297),de=D(7680),O=D(616),G=Function,Q=j([].concat),V=j([].join),J={};B.exports=O?G.bind:function(ie){var he=z(this),fe=he.prototype,se=de(arguments,1),U=function(){var R=Q(se,de(arguments));return this instanceof U?(function(re,xe,we){if(!q(J,xe)){for(var ye=[],Ae=0;Ae<xe;Ae++)ye[Ae]="a["+Ae+"]";J[xe]=G("C,a","return new C("+V(ye,",")+")")}return J[xe](re,we)})(he,R.length,R):he.apply(ie,R)};return W(fe)&&(U.prototype=fe),U}},9565:function(B,Y,D){var j=D(616),z=Function.prototype.call;B.exports=j?z.bind(z):function(){return z.apply(z,arguments)}},350:function(B,Y,D){var j=D(3724),z=D(9297),W=Function.prototype,q=j&&Object.getOwnPropertyDescriptor,de=z(W,"name"),O=de&&(function(){}).name==="something",G=de&&(!j||j&&q(W,"name").configurable);B.exports={EXISTS:de,PROPER:O,CONFIGURABLE:G}},6706:function(B,Y,D){var j=D(9504),z=D(9306);B.exports=function(W,q,de){try{return j(z(Object.getOwnPropertyDescriptor(W,q)[de]))}catch{}}},7476:function(B,Y,D){var j=D(2195),z=D(9504);B.exports=function(W){if(j(W)==="Function")return z(W)}},9504:function(B,Y,D){var j=D(616),z=Function.prototype,W=z.call,q=j&&z.bind.bind(W,W);B.exports=j?q:function(de){return function(){return W.apply(de,arguments)}}},7751:function(B,Y,D){var j=D(4576),z=D(4901);B.exports=function(W,q){return arguments.length<2?(de=j[W],z(de)?de:void 0):j[W]&&j[W][q];var de}},851:function(B,Y,D){var j=D(6955),z=D(5966),W=D(4117),q=D(6269),de=D(8227)("iterator");B.exports=function(O){if(!W(O))return z(O,de)||z(O,"@@iterator")||q[j(O)]}},81:function(B,Y,D){var j=D(9565),z=D(9306),W=D(8551),q=D(6823),de=D(851),O=TypeError;B.exports=function(G,Q){var V=arguments.length<2?de(G):Q;if(z(V))return W(j(V,G));throw new O(q(G)+" is not iterable")}},5966:function(B,Y,D){var j=D(9306),z=D(4117);B.exports=function(W,q){var de=W[q];return z(de)?void 0:j(de)}},2478:function(B,Y,D){var j=D(9504),z=D(8981),W=Math.floor,q=j("".charAt),de=j("".replace),O=j("".slice),G=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Q=/\$([$&'`]|\d{1,2})/g;B.exports=function(V,J,ie,he,fe,se){var U=ie+V.length,R=he.length,re=Q;return fe!==void 0&&(fe=z(fe),re=G),de(se,re,(function(xe,we){var ye;switch(q(we,0)){case"$":return"$";case"&":return V;case"`":return O(J,0,ie);case"'":return O(J,U);case"<":ye=fe[O(we,1,-1)];break;default:var Ae=+we;if(Ae===0)return xe;if(Ae>R){var ve=W(Ae/10);return ve===0?xe:ve<=R?he[ve-1]===void 0?q(we,1):he[ve-1]+q(we,1):xe}ye=he[Ae-1]}return ye===void 0?"":ye}))}},4576:function(B,Y,D){var j=function(z){return z&&z.Math===Math&&z};B.exports=j(typeof globalThis=="object"&&globalThis)||j(typeof window=="object"&&window)||j(typeof self=="object"&&self)||j(typeof D.g=="object"&&D.g)||j(typeof this=="object"&&this)||(function(){return this})()||Function("return this")()},9297:function(B,Y,D){var j=D(9504),z=D(8981),W=j({}.hasOwnProperty);B.exports=Object.hasOwn||function(q,de){return W(z(q),de)}},421:function(B){B.exports={}},397:function(B,Y,D){var j=D(7751);B.exports=j("document","documentElement")},5917:function(B,Y,D){var j=D(3724),z=D(9039),W=D(4055);B.exports=!j&&!z((function(){return Object.defineProperty(W("div"),"a",{get:function(){return 7}}).a!==7}))},7055:function(B,Y,D){var j=D(9504),z=D(9039),W=D(2195),q=Object,de=j("".split);B.exports=z((function(){return!q("z").propertyIsEnumerable(0)}))?function(O){return W(O)==="String"?de(O,""):q(O)}:q},3167:function(B,Y,D){var j=D(4901),z=D(34),W=D(2967);B.exports=function(q,de,O){var G,Q;return W&&j(G=de.constructor)&&G!==O&&z(Q=G.prototype)&&Q!==O.prototype&&W(q,Q),q}},3706:function(B,Y,D){var j=D(9504),z=D(4901),W=D(7629),q=j(Function.toString);z(W.inspectSource)||(W.inspectSource=function(de){return q(de)}),B.exports=W.inspectSource},1181:function(B,Y,D){var j,z,W,q=D(8622),de=D(4576),O=D(34),G=D(6699),Q=D(9297),V=D(7629),J=D(6119),ie=D(421),he="Object already initialized",fe=de.TypeError,se=de.WeakMap;if(q||V.state){var U=V.state||(V.state=new se);U.get=U.get,U.has=U.has,U.set=U.set,j=function(re,xe){if(U.has(re))throw new fe(he);return xe.facade=re,U.set(re,xe),xe},z=function(re){return U.get(re)||{}},W=function(re){return U.has(re)}}else{var R=J("state");ie[R]=!0,j=function(re,xe){if(Q(re,R))throw new fe(he);return xe.facade=re,G(re,R,xe),xe},z=function(re){return Q(re,R)?re[R]:{}},W=function(re){return Q(re,R)}}B.exports={set:j,get:z,has:W,enforce:function(re){return W(re)?z(re):j(re,{})},getterFor:function(re){return function(xe){var we;if(!O(xe)||(we=z(xe)).type!==re)throw new fe("Incompatible receiver, "+re+" required");return we}}}},4209:function(B,Y,D){var j=D(8227),z=D(6269),W=j("iterator"),q=Array.prototype;B.exports=function(de){return de!==void 0&&(z.Array===de||q[W]===de)}},4376:function(B,Y,D){var j=D(2195);B.exports=Array.isArray||function(z){return j(z)==="Array"}},4901:function(B){var Y=typeof document=="object"&&document.all;B.exports=Y===void 0&&Y!==void 0?function(D){return typeof D=="function"||D===Y}:function(D){return typeof D=="function"}},3517:function(B,Y,D){var j=D(9504),z=D(9039),W=D(4901),q=D(6955),de=D(7751),O=D(3706),G=function(){},Q=de("Reflect","construct"),V=/^\s*(?:class|function)\b/,J=j(V.exec),ie=!V.test(G),he=function(se){if(!W(se))return!1;try{return Q(G,[],se),!0}catch{return!1}},fe=function(se){if(!W(se))return!1;switch(q(se)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ie||!!J(V,O(se))}catch{return!0}};fe.sham=!0,B.exports=!Q||z((function(){var se;return he(he.call)||!he(Object)||!he((function(){se=!0}))||se}))?fe:he},2796:function(B,Y,D){var j=D(9039),z=D(4901),W=/#|\.prototype\./,q=function(V,J){var ie=O[de(V)];return ie===Q||ie!==G&&(z(J)?j(J):!!J)},de=q.normalize=function(V){return String(V).replace(W,".").toLowerCase()},O=q.data={},G=q.NATIVE="N",Q=q.POLYFILL="P";B.exports=q},2087:function(B,Y,D){var j=D(34),z=Math.floor;B.exports=Number.isInteger||function(W){return!j(W)&&isFinite(W)&&z(W)===W}},4117:function(B){B.exports=function(Y){return Y==null}},34:function(B,Y,D){var j=D(4901);B.exports=function(z){return typeof z=="object"?z!==null:j(z)}},3925:function(B,Y,D){var j=D(34);B.exports=function(z){return j(z)||z===null}},6395:function(B){B.exports=!1},5810:function(B,Y,D){var j=D(34),z=D(1181).get;B.exports=function(W){if(!j(W))return!1;var q=z(W);return!!q&&q.type==="RawJSON"}},788:function(B,Y,D){var j=D(34),z=D(2195),W=D(8227)("match");B.exports=function(q){var de;return j(q)&&((de=q[W])!==void 0?!!de:z(q)==="RegExp")}},757:function(B,Y,D){var j=D(7751),z=D(4901),W=D(1625),q=D(7040),de=Object;B.exports=q?function(O){return typeof O=="symbol"}:function(O){var G=j("Symbol");return z(G)&&W(G.prototype,de(O))}},9539:function(B,Y,D){var j=D(9565),z=D(8551),W=D(5966);B.exports=function(q,de,O){var G,Q;z(q);try{if(!(G=W(q,"return"))){if(de==="throw")throw O;return O}G=j(G,q)}catch(V){Q=!0,G=V}if(de==="throw")throw O;if(Q)throw G;return z(G),O}},3994:function(B,Y,D){var j=D(7657).IteratorPrototype,z=D(2360),W=D(6980),q=D(687),de=D(6269),O=function(){return this};B.exports=function(G,Q,V,J){var ie=Q+" Iterator";return G.prototype=z(j,{next:W(+!J,V)}),q(G,ie,!1,!0),de[ie]=O,G}},1088:function(B,Y,D){var j=D(6518),z=D(9565),W=D(6395),q=D(350),de=D(4901),O=D(3994),G=D(2787),Q=D(2967),V=D(687),J=D(6699),ie=D(6840),he=D(8227),fe=D(6269),se=D(7657),U=q.PROPER,R=q.CONFIGURABLE,re=se.IteratorPrototype,xe=se.BUGGY_SAFARI_ITERATORS,we=he("iterator"),ye="keys",Ae="values",ve="entries",Te=function(){return this};B.exports=function(Fe,Ee,Se,je,qe,Re,Ye){O(Se,Ee,je);var ce,ze,Ne,Ge=function(xt){if(xt===qe&&tt)return tt;if(!xe&&xt&&xt in Me)return Me[xt];switch(xt){case ye:case Ae:case ve:return function(){return new Se(this,xt)}}return function(){return new Se(this)}},$e=Ee+" Iterator",Pe=!1,Me=Fe.prototype,Ve=Me[we]||Me["@@iterator"]||qe&&Me[qe],tt=!xe&&Ve||Ge(qe),ut=Ee==="Array"&&Me.entries||Ve;if(ut&&(ce=G(ut.call(new Fe)))!==Object.prototype&&ce.next&&(W||G(ce)===re||(Q?Q(ce,re):de(ce[we])||ie(ce,we,Te)),V(ce,$e,!0,!0),W&&(fe[$e]=Te)),U&&qe===Ae&&Ve&&Ve.name!==Ae&&(!W&&R?J(Me,"name",Ae):(Pe=!0,tt=function(){return z(Ve,this)})),qe)if(ze={values:Ge(Ae),keys:Re?tt:Ge(ye),entries:Ge(ve)},Ye)for(Ne in ze)(xe||Pe||!(Ne in Me))&&ie(Me,Ne,ze[Ne]);else j({target:Ee,proto:!0,forced:xe||Pe},ze);return W&&!Ye||Me[we]===tt||ie(Me,we,tt,{name:qe}),fe[Ee]=tt,ze}},7657:function(B,Y,D){var j,z,W,q=D(9039),de=D(4901),O=D(34),G=D(2360),Q=D(2787),V=D(6840),J=D(8227),ie=D(6395),he=J("iterator"),fe=!1;[].keys&&("next"in(W=[].keys())?(z=Q(Q(W)))!==Object.prototype&&(j=z):fe=!0),!O(j)||q((function(){var se={};return j[he].call(se)!==se}))?j={}:ie&&(j=G(j)),de(j[he])||V(j,he,(function(){return this})),B.exports={IteratorPrototype:j,BUGGY_SAFARI_ITERATORS:fe}},6269:function(B){B.exports={}},6198:function(B,Y,D){var j=D(8014);B.exports=function(z){return j(z.length)}},283:function(B,Y,D){var j=D(9504),z=D(9039),W=D(4901),q=D(9297),de=D(3724),O=D(350).CONFIGURABLE,G=D(3706),Q=D(1181),V=Q.enforce,J=Q.get,ie=String,he=Object.defineProperty,fe=j("".slice),se=j("".replace),U=j([].join),R=de&&!z((function(){return he((function(){}),"length",{value:8}).length!==8})),re=String(String).split("String"),xe=B.exports=function(we,ye,Ae){fe(ie(ye),0,7)==="Symbol("&&(ye="["+se(ie(ye),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),Ae&&Ae.getter&&(ye="get "+ye),Ae&&Ae.setter&&(ye="set "+ye),(!q(we,"name")||O&&we.name!==ye)&&(de?he(we,"name",{value:ye,configurable:!0}):we.name=ye),R&&Ae&&q(Ae,"arity")&&we.length!==Ae.arity&&he(we,"length",{value:Ae.arity});try{Ae&&q(Ae,"constructor")&&Ae.constructor?de&&he(we,"prototype",{writable:!1}):we.prototype&&(we.prototype=void 0)}catch{}var ve=V(we);return q(ve,"source")||(ve.source=U(re,typeof ye=="string"?ye:"")),we};Function.prototype.toString=xe((function(){return W(this)&&J(this).source||G(this)}),"toString")},741:function(B){var Y=Math.ceil,D=Math.floor;B.exports=Math.trunc||function(j){var z=+j;return(z>0?D:Y)(z)}},7819:function(B,Y,D){var j=D(9039);B.exports=!j((function(){var z="9007199254740993",W=JSON.rawJSON(z);return!JSON.isRawJSON(W)||JSON.stringify(W)!==z}))},5749:function(B,Y,D){var j=D(788),z=TypeError;B.exports=function(W){if(j(W))throw new z("The method doesn't accept regular expressions");return W}},4213:function(B,Y,D){var j=D(3724),z=D(9504),W=D(9565),q=D(9039),de=D(1072),O=D(3717),G=D(8773),Q=D(8981),V=D(7055),J=Object.assign,ie=Object.defineProperty,he=z([].concat);B.exports=!J||q((function(){if(j&&J({b:1},J(ie({},"a",{enumerable:!0,get:function(){ie(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var fe={},se={},U=Symbol("assign detection"),R="abcdefghijklmnopqrst";return fe[U]=7,R.split("").forEach((function(re){se[re]=re})),J({},fe)[U]!==7||de(J({},se)).join("")!==R}))?function(fe,se){for(var U=Q(fe),R=arguments.length,re=1,xe=O.f,we=G.f;R>re;)for(var ye,Ae=V(arguments[re++]),ve=xe?he(de(Ae),xe(Ae)):de(Ae),Te=ve.length,Fe=0;Te>Fe;)ye=ve[Fe++],j&&!W(we,Ae,ye)||(U[ye]=Ae[ye]);return U}:J},2360:function(B,Y,D){var j,z=D(8551),W=D(6801),q=D(8727),de=D(421),O=D(397),G=D(4055),Q=D(6119),V="prototype",J="script",ie=Q("IE_PROTO"),he=function(){},fe=function(R){return"<"+J+">"+R+"</"+J+">"},se=function(R){R.write(fe("")),R.close();var re=R.parentWindow.Object;return R=null,re},U=function(){try{j=new ActiveXObject("htmlfile")}catch{}var R,re,xe;U=typeof document<"u"?document.domain&&j?se(j):(re=G("iframe"),xe="java"+J+":",re.style.display="none",O.appendChild(re),re.src=String(xe),(R=re.contentWindow.document).open(),R.write(fe("document.F=Object")),R.close(),R.F):se(j);for(var we=q.length;we--;)delete U[V][q[we]];return U()};de[ie]=!0,B.exports=Object.create||function(R,re){var xe;return R!==null?(he[V]=z(R),xe=new he,he[V]=null,xe[ie]=R):xe=U(),re===void 0?xe:W.f(xe,re)}},6801:function(B,Y,D){var j=D(3724),z=D(8686),W=D(4913),q=D(8551),de=D(5397),O=D(1072);Y.f=j&&!z?Object.defineProperties:function(G,Q){q(G);for(var V,J=de(Q),ie=O(Q),he=ie.length,fe=0;he>fe;)W.f(G,V=ie[fe++],J[V]);return G}},4913:function(B,Y,D){var j=D(3724),z=D(5917),W=D(8686),q=D(8551),de=D(6969),O=TypeError,G=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,V="enumerable",J="configurable",ie="writable";Y.f=j?W?function(he,fe,se){if(q(he),fe=de(fe),q(se),typeof he=="function"&&fe==="prototype"&&"value"in se&&ie in se&&!se[ie]){var U=Q(he,fe);U&&U[ie]&&(he[fe]=se.value,se={configurable:J in se?se[J]:U[J],enumerable:V in se?se[V]:U[V],writable:!1})}return G(he,fe,se)}:G:function(he,fe,se){if(q(he),fe=de(fe),q(se),z)try{return G(he,fe,se)}catch{}if("get"in se||"set"in se)throw new O("Accessors not supported");return"value"in se&&(he[fe]=se.value),he}},7347:function(B,Y,D){var j=D(3724),z=D(9565),W=D(8773),q=D(6980),de=D(5397),O=D(6969),G=D(9297),Q=D(5917),V=Object.getOwnPropertyDescriptor;Y.f=j?V:function(J,ie){if(J=de(J),ie=O(ie),Q)try{return V(J,ie)}catch{}if(G(J,ie))return q(!z(W.f,J,ie),J[ie])}},298:function(B,Y,D){var j=D(2195),z=D(5397),W=D(8480).f,q=D(7680),de=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];B.exports.f=function(O){return de&&j(O)==="Window"?(function(G){try{return W(G)}catch{return q(de)}})(O):W(z(O))}},8480:function(B,Y,D){var j=D(1828),z=D(8727).concat("length","prototype");Y.f=Object.getOwnPropertyNames||function(W){return j(W,z)}},3717:function(B,Y){Y.f=Object.getOwnPropertySymbols},2787:function(B,Y,D){var j=D(9297),z=D(4901),W=D(8981),q=D(6119),de=D(2211),O=q("IE_PROTO"),G=Object,Q=G.prototype;B.exports=de?G.getPrototypeOf:function(V){var J=W(V);if(j(J,O))return J[O];var ie=J.constructor;return z(ie)&&J instanceof ie?ie.prototype:J instanceof G?Q:null}},1625:function(B,Y,D){var j=D(9504);B.exports=j({}.isPrototypeOf)},1828:function(B,Y,D){var j=D(9504),z=D(9297),W=D(5397),q=D(9617).indexOf,de=D(421),O=j([].push);B.exports=function(G,Q){var V,J=W(G),ie=0,he=[];for(V in J)!z(de,V)&&z(J,V)&&O(he,V);for(;Q.length>ie;)z(J,V=Q[ie++])&&(~q(he,V)||O(he,V));return he}},1072:function(B,Y,D){var j=D(1828),z=D(8727);B.exports=Object.keys||function(W){return j(W,z)}},8773:function(B,Y){var D={}.propertyIsEnumerable,j=Object.getOwnPropertyDescriptor,z=j&&!D.call({1:2},1);Y.f=z?function(W){var q=j(this,W);return!!q&&q.enumerable}:D},2551:function(B,Y,D){var j=D(6395),z=D(4576),W=D(9039),q=D(3607);B.exports=j||!W((function(){if(!(q&&q<535)){var de=Math.random();__defineSetter__.call(null,de,(function(){})),delete z[de]}}))},2967:function(B,Y,D){var j=D(6706),z=D(34),W=D(7750),q=D(3506);B.exports=Object.setPrototypeOf||("__proto__"in{}?(function(){var de,O=!1,G={};try{(de=j(Object.prototype,"__proto__","set"))(G,[]),O=G instanceof Array}catch{}return function(Q,V){return W(Q),q(V),z(Q)&&(O?de(Q,V):Q.__proto__=V),Q}})():void 0)},3179:function(B,Y,D){var j=D(2140),z=D(6955);B.exports=j?{}.toString:function(){return"[object "+z(this)+"]"}},4270:function(B,Y,D){var j=D(9565),z=D(4901),W=D(34),q=TypeError;B.exports=function(de,O){var G,Q;if(O==="string"&&z(G=de.toString)&&!W(Q=j(G,de))||z(G=de.valueOf)&&!W(Q=j(G,de))||O!=="string"&&z(G=de.toString)&&!W(Q=j(G,de)))return Q;throw new q("Can't convert object to primitive value")}},5031:function(B,Y,D){var j=D(7751),z=D(9504),W=D(8480),q=D(3717),de=D(8551),O=z([].concat);B.exports=j("Reflect","ownKeys")||function(G){var Q=W.f(de(G)),V=q.f;return V?O(Q,V(G)):Q}},8235:function(B,Y,D){var j=D(9504),z=D(9297),W=SyntaxError,q=parseInt,de=String.fromCharCode,O=j("".charAt),G=j("".slice),Q=j(/./.exec),V={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
  8352. `,"\\r":"\r","\\t":" "},J=/^[\da-f]{4}$/i,ie=/^[\u0000-\u001F]$/;B.exports=function(he,fe){for(var se=!0,U="";fe<he.length;){var R=O(he,fe);if(R==="\\"){var re=G(he,fe,fe+2);if(z(V,re))U+=V[re],fe+=2;else{if(re!=="\\u")throw new W('Unknown escape sequence: "'+re+'"');var xe=G(he,fe+=2,fe+4);if(!Q(J,xe))throw new W("Bad Unicode escape at: "+fe);U+=de(q(xe,16)),fe+=4}}else{if(R==='"'){se=!1,fe++;break}if(Q(ie,R))throw new W("Bad control character in string literal at: "+fe);U+=R,fe++}}if(se)throw new W("Unterminated string at: "+fe);return{value:U,end:fe}}},9167:function(B,Y,D){var j=D(4576);B.exports=j},1056:function(B,Y,D){var j=D(4913).f;B.exports=function(z,W,q){q in z||j(z,q,{configurable:!0,get:function(){return W[q]},set:function(de){W[q]=de}})}},6682:function(B,Y,D){var j=D(9565),z=D(8551),W=D(4901),q=D(2195),de=D(7323),O=TypeError;B.exports=function(G,Q){var V=G.exec;if(W(V)){var J=j(V,G,Q);return J!==null&&z(J),J}if(q(G)==="RegExp")return j(de,G,Q);throw new O("RegExp#exec called on incompatible receiver")}},7323:function(B,Y,D){var j,z,W=D(9565),q=D(9504),de=D(655),O=D(7979),G=D(8429),Q=D(5745),V=D(2360),J=D(1181).get,ie=D(3635),he=D(8814),fe=Q("native-string-replace",String.prototype.replace),se=RegExp.prototype.exec,U=se,R=q("".charAt),re=q("".indexOf),xe=q("".replace),we=q("".slice),ye=(z=/b*/g,W(se,j=/a/,"a"),W(se,z,"a"),j.lastIndex!==0||z.lastIndex!==0),Ae=G.BROKEN_CARET,ve=/()??/.exec("")[1]!==void 0;(ye||ve||Ae||ie||he)&&(U=function(Te){var Fe,Ee,Se,je,qe,Re,Ye,ce=this,ze=J(ce),Ne=de(Te),Ge=ze.raw;if(Ge)return Ge.lastIndex=ce.lastIndex,Fe=W(U,Ge,Ne),ce.lastIndex=Ge.lastIndex,Fe;var $e=ze.groups,Pe=Ae&&ce.sticky,Me=W(O,ce),Ve=ce.source,tt=0,ut=Ne;if(Pe&&(Me=xe(Me,"y",""),re(Me,"g")===-1&&(Me+="g"),ut=we(Ne,ce.lastIndex),ce.lastIndex>0&&(!ce.multiline||ce.multiline&&R(Ne,ce.lastIndex-1)!==`
  8353. `)&&(Ve="(?: "+Ve+")",ut=" "+ut,tt++),Ee=new RegExp("^(?:"+Ve+")",Me)),ve&&(Ee=new RegExp("^"+Ve+"$(?!\\s)",Me)),ye&&(Se=ce.lastIndex),je=W(se,Pe?Ee:ce,ut),Pe?je?(je.input=we(je.input,tt),je[0]=we(je[0],tt),je.index=ce.lastIndex,ce.lastIndex+=je[0].length):ce.lastIndex=0:ye&&je&&(ce.lastIndex=ce.global?je.index+je[0].length:Se),ve&&je&&je.length>1&&W(fe,je[0],Ee,(function(){for(qe=1;qe<arguments.length-2;qe++)arguments[qe]===void 0&&(je[qe]=void 0)})),je&&$e)for(je.groups=Re=V(null),qe=0;qe<$e.length;qe++)Re[(Ye=$e[qe])[0]]=je[Ye[1]];return je}),B.exports=U},5213:function(B,Y,D){var j=D(4576),z=D(9039),W=j.RegExp,q=!z((function(){var de=!0;try{W(".","d")}catch{de=!1}var O={},G="",Q=de?"dgimsy":"gimsy",V=function(he,fe){Object.defineProperty(O,he,{get:function(){return G+=fe,!0}})},J={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var ie in de&&(J.hasIndices="d"),J)V(ie,J[ie]);return Object.getOwnPropertyDescriptor(W.prototype,"flags").get.call(O)!==Q||G!==Q}));B.exports={correct:q}},7979:function(B,Y,D){var j=D(8551);B.exports=function(){var z=j(this),W="";return z.hasIndices&&(W+="d"),z.global&&(W+="g"),z.ignoreCase&&(W+="i"),z.multiline&&(W+="m"),z.dotAll&&(W+="s"),z.unicode&&(W+="u"),z.unicodeSets&&(W+="v"),z.sticky&&(W+="y"),W}},1034:function(B,Y,D){var j=D(9565),z=D(9297),W=D(1625),q=D(5213),de=D(7979),O=RegExp.prototype;B.exports=q.correct?function(G){return G.flags}:function(G){return q.correct||!W(O,G)||z(G,"flags")?G.flags:j(de,G)}},8429:function(B,Y,D){var j=D(9039),z=D(4576).RegExp,W=j((function(){var O=z("a","y");return O.lastIndex=2,O.exec("abcd")!==null})),q=W||j((function(){return!z("a","y").sticky})),de=W||j((function(){var O=z("^r","gy");return O.lastIndex=2,O.exec("str")!==null}));B.exports={BROKEN_CARET:de,MISSED_STICKY:q,UNSUPPORTED_Y:W}},3635:function(B,Y,D){var j=D(9039),z=D(4576).RegExp;B.exports=j((function(){var W=z(".","s");return!(W.dotAll&&W.test(`
  8354. `)&&W.flags==="s")}))},8814:function(B,Y,D){var j=D(9039),z=D(4576).RegExp;B.exports=j((function(){var W=z("(?<a>b)","g");return W.exec("b").groups.a!=="b"||"b".replace(W,"$<a>c")!=="bc"}))},7750:function(B,Y,D){var j=D(4117),z=TypeError;B.exports=function(W){if(j(W))throw new z("Can't call method on "+W);return W}},7633:function(B,Y,D){var j=D(7751),z=D(2106),W=D(8227),q=D(3724),de=W("species");B.exports=function(O){var G=j(O);q&&G&&!G[de]&&z(G,de,{configurable:!0,get:function(){return this}})}},687:function(B,Y,D){var j=D(4913).f,z=D(9297),W=D(8227)("toStringTag");B.exports=function(q,de,O){q&&!O&&(q=q.prototype),q&&!z(q,W)&&j(q,W,{configurable:!0,value:de})}},6119:function(B,Y,D){var j=D(5745),z=D(3392),W=j("keys");B.exports=function(q){return W[q]||(W[q]=z(q))}},7629:function(B,Y,D){var j=D(6395),z=D(4576),W=D(9433),q="__core-js_shared__",de=B.exports=z[q]||W(q,{});(de.versions||(de.versions=[])).push({version:"3.48.0",mode:j?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"})},5745:function(B,Y,D){var j=D(7629);B.exports=function(z,W){return j[z]||(j[z]=W||{})}},2293:function(B,Y,D){var j=D(8551),z=D(5548),W=D(4117),q=D(8227)("species");B.exports=function(de,O){var G,Q=j(de).constructor;return Q===void 0||W(G=j(Q)[q])?O:z(G)}},8183:function(B,Y,D){var j=D(9504),z=D(1291),W=D(655),q=D(7750),de=j("".charAt),O=j("".charCodeAt),G=j("".slice),Q=function(V){return function(J,ie){var he,fe,se=W(q(J)),U=z(ie),R=se.length;return U<0||U>=R?V?"":void 0:(he=O(se,U))<55296||he>56319||U+1===R||(fe=O(se,U+1))<56320||fe>57343?V?de(se,U):he:V?G(se,U,U+2):fe-56320+(he-55296<<10)+65536}};B.exports={codeAt:Q(!1),charAt:Q(!0)}},706:function(B,Y,D){var j=D(350).PROPER,z=D(9039),W=D(7452);B.exports=function(q){return z((function(){return!!W[q]()||"​…᠎"[q]()!=="​…᠎"||j&&W[q].name!==q}))}},3802:function(B,Y,D){var j=D(9504),z=D(7750),W=D(655),q=D(7452),de=j("".replace),O=RegExp("^["+q+"]+"),G=RegExp("(^|[^"+q+"])["+q+"]+$"),Q=function(V){return function(J){var ie=W(z(J));return 1&V&&(ie=de(ie,O,"")),2&V&&(ie=de(ie,G,"$1")),ie}};B.exports={start:Q(1),end:Q(2),trim:Q(3)}},4495:function(B,Y,D){var j=D(9519),z=D(9039),W=D(4576).String;B.exports=!!Object.getOwnPropertySymbols&&!z((function(){var q=Symbol("symbol detection");return!W(q)||!(Object(q)instanceof Symbol)||!Symbol.sham&&j&&j<41}))},8242:function(B,Y,D){var j=D(9565),z=D(7751),W=D(8227),q=D(6840);B.exports=function(){var de=z("Symbol"),O=de&&de.prototype,G=O&&O.valueOf,Q=W("toPrimitive");O&&!O[Q]&&q(O,Q,(function(V){return j(G,this)}),{arity:1})}},1296:function(B,Y,D){var j=D(4495);B.exports=j&&!!Symbol.for&&!!Symbol.keyFor},1240:function(B,Y,D){var j=D(9504);B.exports=j(1.1.valueOf)},5610:function(B,Y,D){var j=D(1291),z=Math.max,W=Math.min;B.exports=function(q,de){var O=j(q);return O<0?z(O+de,0):W(O,de)}},5397:function(B,Y,D){var j=D(7055),z=D(7750);B.exports=function(W){return j(z(W))}},1291:function(B,Y,D){var j=D(741);B.exports=function(z){var W=+z;return W!=W||W===0?0:j(W)}},8014:function(B,Y,D){var j=D(1291),z=Math.min;B.exports=function(W){var q=j(W);return q>0?z(q,9007199254740991):0}},8981:function(B,Y,D){var j=D(7750),z=Object;B.exports=function(W){return z(j(W))}},2777:function(B,Y,D){var j=D(9565),z=D(34),W=D(757),q=D(5966),de=D(4270),O=D(8227),G=TypeError,Q=O("toPrimitive");B.exports=function(V,J){if(!z(V)||W(V))return V;var ie,he=q(V,Q);if(he){if(J===void 0&&(J="default"),ie=j(he,V,J),!z(ie)||W(ie))return ie;throw new G("Can't convert object to primitive value")}return J===void 0&&(J="number"),de(V,J)}},6969:function(B,Y,D){var j=D(2777),z=D(757);B.exports=function(W){var q=j(W,"string");return z(q)?q:q+""}},2140:function(B,Y,D){var j={};j[D(8227)("toStringTag")]="z",B.exports=String(j)==="[object z]"},655:function(B,Y,D){var j=D(6955),z=String;B.exports=function(W){if(j(W)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return z(W)}},6823:function(B){var Y=String;B.exports=function(D){try{return Y(D)}catch{return"Object"}}},3392:function(B,Y,D){var j=D(9504),z=0,W=Math.random(),q=j(1.1.toString);B.exports=function(de){return"Symbol("+(de===void 0?"":de)+")_"+q(++z+W,36)}},7040:function(B,Y,D){var j=D(4495);B.exports=j&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},8686:function(B,Y,D){var j=D(3724),z=D(9039);B.exports=j&&z((function(){return Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype!==42}))},8622:function(B,Y,D){var j=D(4576),z=D(4901),W=j.WeakMap;B.exports=z(W)&&/native code/.test(String(W))},511:function(B,Y,D){var j=D(9167),z=D(9297),W=D(1951),q=D(4913).f;B.exports=function(de){var O=j.Symbol||(j.Symbol={});z(O,de)||q(O,de,{value:W.f(de)})}},1951:function(B,Y,D){var j=D(8227);Y.f=j},8227:function(B,Y,D){var j=D(4576),z=D(5745),W=D(9297),q=D(3392),de=D(4495),O=D(7040),G=j.Symbol,Q=z("wks"),V=O?G.for||G:G&&G.withoutSetter||q;B.exports=function(J){return W(Q,J)||(Q[J]=de&&W(G,J)?G[J]:V("Symbol."+J)),Q[J]}},7452:function(B){B.exports=`
  8355. \v\f\r                 \u2028\u2029\uFEFF`},8706:function(B,Y,D){var j=D(6518),z=D(9039),W=D(4376),q=D(34),de=D(8981),O=D(6198),G=D(6837),Q=D(4659),V=D(4527),J=D(1469),ie=D(597),he=D(8227),fe=D(9519),se=he("isConcatSpreadable"),U=fe>=51||!z((function(){var re=[];return re[se]=!1,re.concat()[0]!==re})),R=function(re){if(!q(re))return!1;var xe=re[se];return xe!==void 0?!!xe:W(re)};j({target:"Array",proto:!0,arity:1,forced:!U||!ie("concat")},{concat:function(re){var xe,we,ye,Ae,ve,Te=de(this),Fe=J(Te,0),Ee=0;for(xe=-1,ye=arguments.length;xe<ye;xe++)if(R(ve=xe===-1?Te:arguments[xe]))for(Ae=O(ve),G(Ee+Ae),we=0;we<Ae;we++,Ee++)we in ve&&Q(Fe,Ee,ve[we]);else G(Ee+1),Q(Fe,Ee++,ve);return V(Fe,Ee),Fe}})},2008:function(B,Y,D){var j=D(6518),z=D(9213).filter;j({target:"Array",proto:!0,forced:!D(597)("filter")},{filter:function(W){return z(this,W,arguments.length>1?arguments[1]:void 0)}})},3418:function(B,Y,D){var j=D(6518),z=D(7916);j({target:"Array",stat:!0,forced:!D(4428)((function(W){Array.from(W)}))},{from:z})},4423:function(B,Y,D){var j=D(6518),z=D(9617).includes,W=D(9039),q=D(6469);j({target:"Array",proto:!0,forced:W((function(){return!Array(1).includes()}))},{includes:function(de){return z(this,de,arguments.length>1?arguments[1]:void 0)}}),q("includes")},5276:function(B,Y,D){var j=D(6518),z=D(7476),W=D(9617).indexOf,q=D(4598),de=z([].indexOf),O=!!de&&1/de([1],1,-0)<0;j({target:"Array",proto:!0,forced:O||!q("indexOf")},{indexOf:function(G){var Q=arguments.length>1?arguments[1]:void 0;return O?de(this,G,Q)||0:W(this,G,Q)}})},3792:function(B,Y,D){var j=D(5397),z=D(6469),W=D(6269),q=D(1181),de=D(4913).f,O=D(1088),G=D(2529),Q=D(6395),V=D(3724),J="Array Iterator",ie=q.set,he=q.getterFor(J);B.exports=O(Array,"Array",(function(se,U){ie(this,{type:J,target:j(se),index:0,kind:U})}),(function(){var se=he(this),U=se.target,R=se.index++;if(!U||R>=U.length)return se.target=null,G(void 0,!0);switch(se.kind){case"keys":return G(R,!1);case"values":return G(U[R],!1)}return G([R,U[R]],!1)}),"values");var fe=W.Arguments=W.Array;if(z("keys"),z("values"),z("entries"),!Q&&V&&fe.name!=="values")try{de(fe,"name",{value:"values"})}catch{}},8598:function(B,Y,D){var j=D(6518),z=D(9504),W=D(7055),q=D(5397),de=D(4598),O=z([].join);j({target:"Array",proto:!0,forced:W!==Object||!de("join",",")},{join:function(G){return O(q(this),G===void 0?",":G)}})},2062:function(B,Y,D){var j=D(6518),z=D(9213).map;j({target:"Array",proto:!0,forced:!D(597)("map")},{map:function(W){return z(this,W,arguments.length>1?arguments[1]:void 0)}})},2712:function(B,Y,D){var j=D(6518),z=D(926).left,W=D(4598),q=D(9519);j({target:"Array",proto:!0,forced:!D(6193)&&q>79&&q<83||!W("reduce")},{reduce:function(de){var O=arguments.length;return z(this,de,O,O>1?arguments[1]:void 0)}})},4782:function(B,Y,D){var j=D(6518),z=D(4376),W=D(3517),q=D(34),de=D(5610),O=D(6198),G=D(5397),Q=D(4659),V=D(4527),J=D(8227),ie=D(597),he=D(7680),fe=ie("slice"),se=J("species"),U=Array,R=Math.max;j({target:"Array",proto:!0,forced:!fe},{slice:function(re,xe){var we,ye,Ae,ve=G(this),Te=O(ve),Fe=de(re,Te),Ee=de(xe===void 0?Te:xe,Te);if(z(ve)&&(we=ve.constructor,(W(we)&&(we===U||z(we.prototype))||q(we)&&(we=we[se])===null)&&(we=void 0),we===U||we===void 0))return he(ve,Fe,Ee);for(ye=new(we===void 0?U:we)(R(Ee-Fe,0)),Ae=0;Fe<Ee;Fe++,Ae++)Fe in ve&&Q(ye,Ae,ve[Fe]);return V(ye,Ae),ye}})},6910:function(B,Y,D){var j=D(6518),z=D(9504),W=D(9306),q=D(8981),de=D(6198),O=D(4606),G=D(655),Q=D(9039),V=D(4488),J=D(4598),ie=D(3709),he=D(3763),fe=D(9519),se=D(3607),U=[],R=z(U.sort),re=z(U.push),xe=Q((function(){U.sort(void 0)})),we=Q((function(){U.sort(null)})),ye=J("sort"),Ae=!Q((function(){if(fe)return fe<70;if(!(ie&&ie>3)){if(he)return!0;if(se)return se<603;var ve,Te,Fe,Ee,Se="";for(ve=65;ve<76;ve++){switch(Te=String.fromCharCode(ve),ve){case 66:case 69:case 70:case 72:Fe=3;break;case 68:case 71:Fe=4;break;default:Fe=2}for(Ee=0;Ee<47;Ee++)U.push({k:Te+Ee,v:Fe})}for(U.sort((function(je,qe){return qe.v-je.v})),Ee=0;Ee<U.length;Ee++)Te=U[Ee].k.charAt(0),Se.charAt(Se.length-1)!==Te&&(Se+=Te);return Se!=="DGBEFHACIJK"}}));j({target:"Array",proto:!0,forced:xe||!we||!ye||!Ae},{sort:function(ve){ve!==void 0&&W(ve);var Te=q(this);if(Ae)return ve===void 0?R(Te):R(Te,ve);var Fe,Ee,Se=[],je=de(Te);for(Ee=0;Ee<je;Ee++)Ee in Te&&re(Se,Te[Ee]);for(V(Se,(function(qe){return function(Re,Ye){return Ye===void 0?-1:Re===void 0?1:qe!==void 0?+qe(Re,Ye)||0:G(Re)>G(Ye)?1:-1}})(ve)),Fe=de(Se),Ee=0;Ee<Fe;)Te[Ee]=Se[Ee++];for(;Ee<je;)O(Te,Ee++);return Te}})},4554:function(B,Y,D){var j=D(6518),z=D(8981),W=D(5610),q=D(1291),de=D(6198),O=D(4527),G=D(6837),Q=D(1469),V=D(4659),J=D(4606),ie=D(597)("splice"),he=Math.max,fe=Math.min;j({target:"Array",proto:!0,forced:!ie},{splice:function(se,U){var R,re,xe,we,ye,Ae,ve=z(this),Te=de(ve),Fe=W(se,Te),Ee=arguments.length;for(Ee===0?R=re=0:Ee===1?(R=0,re=Te-Fe):(R=Ee-2,re=fe(he(q(U),0),Te-Fe)),G(Te+R-re),xe=Q(ve,re),we=0;we<re;we++)(ye=Fe+we)in ve&&V(xe,we,ve[ye]);if(O(xe,re),R<re){for(we=Fe;we<Te-re;we++)Ae=we+R,(ye=we+re)in ve?ve[Ae]=ve[ye]:J(ve,Ae);for(we=Te;we>Te-re+R;we--)J(ve,we-1)}else if(R>re)for(we=Te-re;we>Fe;we--)Ae=we+R-1,(ye=we+re-1)in ve?ve[Ae]=ve[ye]:J(ve,Ae);for(we=0;we<R;we++)ve[we+Fe]=arguments[we+2];return O(ve,Te-re+R),xe}})},739:function(B,Y,D){var j=D(6518),z=D(9039),W=D(8981),q=D(2777);j({target:"Date",proto:!0,arity:1,forced:z((function(){return new Date(NaN).toJSON()!==null||Date.prototype.toJSON.call({toISOString:function(){return 1}})!==1}))},{toJSON:function(de){var O=W(this),G=q(O,"number");return typeof G!="number"||isFinite(G)?O.toISOString():null}})},9572:function(B,Y,D){var j=D(9297),z=D(6840),W=D(3640),q=D(8227)("toPrimitive"),de=Date.prototype;j(de,q)||z(de,q,W)},2010:function(B,Y,D){var j=D(3724),z=D(350).EXISTS,W=D(9504),q=D(2106),de=Function.prototype,O=W(de.toString),G=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,Q=W(G.exec);j&&!z&&q(de,"name",{configurable:!0,get:function(){try{return Q(G,O(this))[1]}catch{return""}}})},3110:function(B,Y,D){var j=D(6518),z=D(7751),W=D(8745),q=D(9565),de=D(9504),O=D(9039),G=D(4376),Q=D(4901),V=D(5810),J=D(757),ie=D(2195),he=D(655),fe=D(7680),se=D(8235),U=D(3392),R=D(4495),re=D(7819),xe=String,we=z("JSON","stringify"),ye=de(/./.exec),Ae=de("".charAt),ve=de("".charCodeAt),Te=de("".replace),Fe=de("".slice),Ee=de([].push),Se=de(1.1.toString),je=/[\uD800-\uDFFF]/g,qe=/^[\uD800-\uDBFF]$/,Re=/^[\uDC00-\uDFFF]$/,Ye=U(),ce=Ye.length,ze=!R||O((function(){var Me=z("Symbol")("stringify detection");return we([Me])!=="[null]"||we({a:Me})!=="{}"||we(Object(Me))!=="{}"})),Ne=O((function(){return we("\uDF06\uD834")!=='"\\udf06\\ud834"'||we("\uDEAD")!=='"\\udead"'})),Ge=ze?function(Me,Ve){var tt=fe(arguments),ut=Pe(Ve);if(Q(ut)||Me!==void 0&&!J(Me))return tt[1]=function(xt,wt){if(Q(ut)&&(wt=q(ut,this,xe(xt),wt)),!J(wt))return wt},W(we,null,tt)}:we,$e=function(Me,Ve,tt){var ut=Ae(tt,Ve-1),xt=Ae(tt,Ve+1);return ye(qe,Me)&&!ye(Re,xt)||ye(Re,Me)&&!ye(qe,ut)?"\\u"+Se(ve(Me,0),16):Me},Pe=function(Me){if(Q(Me))return Me;if(G(Me)){for(var Ve=Me.length,tt=[],ut=0;ut<Ve;ut++){var xt=Me[ut];typeof xt=="string"?Ee(tt,xt):typeof xt!="number"&&ie(xt)!=="Number"&&ie(xt)!=="String"||Ee(tt,he(xt))}var wt=tt.length,Ht=!0;return function(Xt,Kt){if(Ht)return Ht=!1,Kt;if(G(this))return Kt;for(var Ut=0;Ut<wt;Ut++)if(tt[Ut]===Xt)return Kt}}};we&&j({target:"JSON",stat:!0,arity:3,forced:ze||Ne||!re},{stringify:function(Me,Ve,tt){var ut=Pe(Ve),xt=[],wt=Ge(Me,(function(Ft,Nt){var ht=Q(ut)?q(ut,this,xe(Ft),Nt):Nt;return!re&&V(ht)?Ye+(Ee(xt,ht.rawJSON)-1):ht}),tt);if(typeof wt!="string"||(Ne&&(wt=Te(wt,je,$e)),re))return wt;for(var Ht="",Xt=wt.length,Kt=0;Kt<Xt;Kt++){var Ut=Ae(wt,Kt);if(Ut==='"'){var en=se(wt,++Kt).end-1,Ke=Fe(wt,Kt,en);Ht+=Fe(Ke,0,ce)===Ye?xt[Fe(Ke,ce)]:'"'+Ke+'"',Kt=en}else Ht+=Ut}return Ht}})},2892:function(B,Y,D){var j=D(6518),z=D(6395),W=D(3724),q=D(4576),de=D(9167),O=D(9504),G=D(2796),Q=D(9297),V=D(3167),J=D(1625),ie=D(757),he=D(2777),fe=D(9039),se=D(8480).f,U=D(7347).f,R=D(4913).f,re=D(1240),xe=D(3802).trim,we="Number",ye=q[we],Ae=de[we],ve=ye.prototype,Te=q.TypeError,Fe=O("".slice),Ee=O("".charCodeAt),Se=function(Ye){var ce,ze,Ne,Ge,$e,Pe,Me,Ve,tt=he(Ye,"number");if(ie(tt))throw new Te("Cannot convert a Symbol value to a number");if(typeof tt=="string"&&tt.length>2){if(tt=xe(tt),(ce=Ee(tt,0))===43||ce===45){if((ze=Ee(tt,2))===88||ze===120)return NaN}else if(ce===48){switch(Ee(tt,1)){case 66:case 98:Ne=2,Ge=49;break;case 79:case 111:Ne=8,Ge=55;break;default:return+tt}for(Pe=($e=Fe(tt,2)).length,Me=0;Me<Pe;Me++)if((Ve=Ee($e,Me))<48||Ve>Ge)return NaN;return parseInt($e,Ne)}}return+tt},je=G(we,!ye(" 0o1")||!ye("0b1")||ye("+0x1")),qe=function(Ye){var ce,ze=arguments.length<1?0:ye((function(Ne){var Ge=he(Ne,"number");return typeof Ge=="bigint"?Ge:Se(Ge)})(Ye));return J(ve,ce=this)&&fe((function(){re(ce)}))?V(Object(ze),this,qe):ze};qe.prototype=ve,je&&!z&&(ve.constructor=qe),j({global:!0,constructor:!0,wrap:!0,forced:je},{Number:qe});var Re=function(Ye,ce){for(var ze,Ne=W?se(ce):"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(","),Ge=0;Ne.length>Ge;Ge++)Q(ce,ze=Ne[Ge])&&!Q(Ye,ze)&&R(Ye,ze,U(ce,ze))};z&&Ae&&Re(de[we],Ae),(je||z)&&Re(de[we],ye)},2637:function(B,Y,D){D(6518)({target:"Number",stat:!0},{isInteger:D(2087)})},9085:function(B,Y,D){var j=D(6518),z=D(4213);j({target:"Object",stat:!0,arity:2,forced:Object.assign!==z},{assign:z})},7427:function(B,Y,D){var j=D(6518),z=D(3724),W=D(2551),q=D(9306),de=D(8981),O=D(4913);z&&j({target:"Object",proto:!0,forced:W},{__defineGetter__:function(G,Q){O.f(de(this),G,{get:q(Q),enumerable:!0,configurable:!0})}})},3851:function(B,Y,D){var j=D(6518),z=D(9039),W=D(5397),q=D(7347).f,de=D(3724);j({target:"Object",stat:!0,forced:!de||z((function(){q(1)})),sham:!de},{getOwnPropertyDescriptor:function(O,G){return q(W(O),G)}})},1278:function(B,Y,D){var j=D(6518),z=D(3724),W=D(5031),q=D(5397),de=D(7347),O=D(4659);j({target:"Object",stat:!0,sham:!z},{getOwnPropertyDescriptors:function(G){for(var Q,V,J=q(G),ie=de.f,he=W(J),fe={},se=0;he.length>se;)(V=ie(J,Q=he[se++]))!==void 0&&O(fe,Q,V);return fe}})},1480:function(B,Y,D){var j=D(6518),z=D(9039),W=D(298).f;j({target:"Object",stat:!0,forced:z((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:W})},9773:function(B,Y,D){var j=D(6518),z=D(4495),W=D(9039),q=D(3717),de=D(8981);j({target:"Object",stat:!0,forced:!z||W((function(){q.f(1)}))},{getOwnPropertySymbols:function(O){var G=q.f;return G?G(de(O)):[]}})},9432:function(B,Y,D){var j=D(6518),z=D(8981),W=D(1072);j({target:"Object",stat:!0,forced:D(9039)((function(){W(1)}))},{keys:function(q){return W(z(q))}})},6099:function(B,Y,D){var j=D(2140),z=D(6840),W=D(3179);j||z(Object.prototype,"toString",W,{unsafe:!0})},825:function(B,Y,D){var j=D(6518),z=D(7751),W=D(8745),q=D(566),de=D(5548),O=D(8551),G=D(34),Q=D(2360),V=D(9039),J=z("Reflect","construct"),ie=Object.prototype,he=[].push,fe=V((function(){function R(){}return!(J((function(){}),[],R)instanceof R)})),se=!V((function(){J((function(){}))})),U=fe||se;j({target:"Reflect",stat:!0,forced:U,sham:U},{construct:function(R,re){de(R),O(re);var xe=arguments.length<3?R:de(arguments[2]);if(se&&!fe)return J(R,re,xe);if(R===xe){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 we=[null];return W(he,we,re),new(W(q,R,we))}var ye=xe.prototype,Ae=Q(G(ye)?ye:ie),ve=W(R,Ae,re);return G(ve)?ve:Ae}})},4864:function(B,Y,D){var j=D(3724),z=D(4576),W=D(9504),q=D(2796),de=D(3167),O=D(6699),G=D(2360),Q=D(8480).f,V=D(1625),J=D(788),ie=D(655),he=D(1034),fe=D(8429),se=D(1056),U=D(6840),R=D(9039),re=D(9297),xe=D(1181).enforce,we=D(7633),ye=D(8227),Ae=D(3635),ve=D(8814),Te=ye("match"),Fe=z.RegExp,Ee=Fe.prototype,Se=z.SyntaxError,je=W(Ee.exec),qe=W("".charAt),Re=W("".replace),Ye=W("".indexOf),ce=W("".slice),ze=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Ne=/a/g,Ge=/a/g,$e=new Fe(Ne)!==Ne,Pe=fe.MISSED_STICKY,Me=fe.UNSUPPORTED_Y;if(q("RegExp",j&&(!$e||Pe||Ae||ve||R((function(){return Ge[Te]=!1,Fe(Ne)!==Ne||Fe(Ge)===Ge||String(Fe(Ne,"i"))!=="/a/i"}))))){for(var Ve=function(xt,wt){var Ht,Xt,Kt,Ut,en,Ke,Ft=V(Ee,this),Nt=J(xt),ht=wt===void 0,Mt=[],Qt=xt;if(!Ft&&Nt&&ht&&xt.constructor===Ve)return xt;if((Nt||V(Ee,xt))&&(xt=xt.source,ht&&(wt=he(Qt))),xt=xt===void 0?"":ie(xt),wt=wt===void 0?"":ie(wt),Qt=xt,Ae&&"dotAll"in Ne&&(Xt=!!wt&&Ye(wt,"s")>-1)&&(wt=Re(wt,/s/g,"")),Ht=wt,Pe&&"sticky"in Ne&&(Kt=!!wt&&Ye(wt,"y")>-1)&&Me&&(wt=Re(wt,/y/g,"")),ve&&(Ut=(function(Wt){for(var Ue,dt=Wt.length,pt=0,De="",Le=[],at=G(null),Ce=!1,We=!1,Xe=0,Qe="";pt<dt;pt++){if((Ue=qe(Wt,pt))==="\\")Ue+=qe(Wt,++pt);else if(Ue==="]")Ce=!1;else if(!Ce)switch(!0){case Ue==="[":Ce=!0;break;case Ue==="(":if(De+=Ue,ce(Wt,pt+1,pt+3)==="?:")continue;je(ze,ce(Wt,pt+1))&&(pt+=2,We=!0),Xe++;continue;case(Ue===">"&&We):if(Qe===""||re(at,Qe))throw new Se("Invalid capture group name");at[Qe]=!0,Le[Le.length]=[Qe,Xe],We=!1,Qe="";continue}We?Qe+=Ue:De+=Ue}return[De,Le]})(xt),xt=Ut[0],Mt=Ut[1]),en=de(Fe(xt,wt),Ft?this:Ee,Ve),(Xt||Kt||Mt.length)&&(Ke=xe(en),Xt&&(Ke.dotAll=!0,Ke.raw=Ve((function(Wt){for(var Ue,dt=Wt.length,pt=0,De="",Le=!1;pt<dt;pt++)(Ue=qe(Wt,pt))!=="\\"?Le||Ue!=="."?(Ue==="["?Le=!0:Ue==="]"&&(Le=!1),De+=Ue):De+="[\\s\\S]":De+=Ue+qe(Wt,++pt);return De})(xt),Ht)),Kt&&(Ke.sticky=!0),Mt.length&&(Ke.groups=Mt)),xt!==Qt)try{O(en,"source",Qt===""?"(?:)":Qt)}catch{}return en},tt=Q(Fe),ut=0;tt.length>ut;)se(Ve,Fe,tt[ut++]);Ee.constructor=Ve,Ve.prototype=Ee,U(z,"RegExp",Ve,{constructor:!0})}we("RegExp")},7495:function(B,Y,D){var j=D(6518),z=D(7323);j({target:"RegExp",proto:!0,forced:/./.exec!==z},{exec:z})},8781:function(B,Y,D){var j=D(350).PROPER,z=D(6840),W=D(8551),q=D(655),de=D(9039),O=D(1034),G="toString",Q=RegExp.prototype,V=Q[G],J=de((function(){return V.call({source:"a",flags:"b"})!=="/a/b"})),ie=j&&V.name!==G;(J||ie)&&z(Q,G,(function(){var he=W(this);return"/"+q(he.source)+"/"+q(O(he))}),{unsafe:!0})},1699:function(B,Y,D){var j=D(6518),z=D(9504),W=D(5749),q=D(7750),de=D(655),O=D(1436),G=z("".indexOf);j({target:"String",proto:!0,forced:!O("includes")},{includes:function(Q){return!!~G(de(q(this)),de(W(Q)),arguments.length>1?arguments[1]:void 0)}})},7764:function(B,Y,D){var j=D(8183).charAt,z=D(655),W=D(1181),q=D(1088),de=D(2529),O="String Iterator",G=W.set,Q=W.getterFor(O);q(String,"String",(function(V){G(this,{type:O,string:z(V),index:0})}),(function(){var V,J=Q(this),ie=J.string,he=J.index;return he>=ie.length?de(void 0,!0):(V=j(ie,he),J.index+=V.length,de(V,!1))}))},8543:function(B,Y,D){var j=D(6518),z=D(9565),W=D(7476),q=D(3994),de=D(2529),O=D(7750),G=D(8014),Q=D(655),V=D(8551),J=D(34),ie=D(2195),he=D(788),fe=D(1034),se=D(5966),U=D(6840),R=D(9039),re=D(8227),xe=D(2293),we=D(7829),ye=D(6682),Ae=D(1181),ve=D(6395),Te=re("matchAll"),Fe="RegExp String",Ee=Fe+" Iterator",Se=Ae.set,je=Ae.getterFor(Ee),qe=RegExp.prototype,Re=TypeError,Ye=W("".indexOf),ce=W("".matchAll),ze=!!ce&&!R((function(){ce("a",/./)})),Ne=q((function($e,Pe,Me,Ve){Se(this,{type:Ee,regexp:$e,string:Pe,global:Me,unicode:Ve,done:!1})}),Fe,(function(){var $e=je(this);if($e.done)return de(void 0,!0);var Pe=$e.regexp,Me=$e.string,Ve=ye(Pe,Me);return Ve===null?($e.done=!0,de(void 0,!0)):$e.global?(Q(Ve[0])===""&&(Pe.lastIndex=we(Me,G(Pe.lastIndex),$e.unicode)),de(Ve,!1)):($e.done=!0,de(Ve,!1))})),Ge=function($e){var Pe,Me,Ve,tt=V(this),ut=Q($e),xt=xe(tt,RegExp),wt=Q(fe(tt));return Pe=new xt(xt===RegExp?tt.source:tt,wt),Me=!!~Ye(wt,"g"),Ve=!!~Ye(wt,"u"),Pe.lastIndex=G(tt.lastIndex),new Ne(Pe,ut,Me,Ve)};j({target:"String",proto:!0,forced:ze},{matchAll:function($e){var Pe,Me,Ve,tt,ut=O(this);if(J($e)){if(he($e)&&(Pe=Q(O(fe($e))),!~Ye(Pe,"g")))throw new Re("`.matchAll` does not allow non-global regexes");if(ze)return ce(ut,$e);if((Ve=se($e,Te))===void 0&&ve&&ie($e)==="RegExp"&&(Ve=Ge),Ve)return z(Ve,$e,ut)}else if(ze)return ce(ut,$e);return Me=Q(ut),tt=new RegExp($e,"g"),ve?z(Ge,tt,Me):tt[Te](Me)}}),ve||Te in qe||U(qe,Te,Ge)},1761:function(B,Y,D){var j=D(9565),z=D(9504),W=D(9228),q=D(8551),de=D(34),O=D(8014),G=D(655),Q=D(7750),V=D(5966),J=D(7829),ie=D(1034),he=D(6682),fe=z("".indexOf);W("match",(function(se,U,R){return[function(re){var xe=Q(this),we=de(re)?V(re,se):void 0;return we?j(we,re,xe):new RegExp(re)[se](G(xe))},function(re){var xe=q(this),we=G(re),ye=R(U,xe,we);if(ye.done)return ye.value;var Ae=G(ie(xe));if(fe(Ae,"g")===-1)return he(xe,we);var ve=fe(Ae,"u")!==-1;xe.lastIndex=0;for(var Te,Fe=[],Ee=0;(Te=he(xe,we))!==null;){var Se=G(Te[0]);Fe[Ee]=Se,Se===""&&(xe.lastIndex=J(we,O(xe.lastIndex),ve)),Ee++}return Ee===0?null:Fe}]}))},5440:function(B,Y,D){var j=D(8745),z=D(9565),W=D(9504),q=D(9228),de=D(9039),O=D(8551),G=D(4901),Q=D(34),V=D(1291),J=D(8014),ie=D(655),he=D(7750),fe=D(7829),se=D(5966),U=D(2478),R=D(1034),re=D(6682),xe=D(8227)("replace"),we=Math.max,ye=Math.min,Ae=W([].concat),ve=W([].push),Te=W("".indexOf),Fe=W("".slice),Ee="a".replace(/./,"$0")==="$0",Se=!!/./[xe]&&/./[xe]("a","$0")==="";q("replace",(function(je,qe,Re){var Ye=Se?"$":"$0";return[function(ce,ze){var Ne=he(this),Ge=Q(ce)?se(ce,xe):void 0;return Ge?z(Ge,ce,Ne,ze):z(qe,ie(Ne),ce,ze)},function(ce,ze){var Ne=O(this),Ge=ie(ce);if(typeof ze=="string"&&Te(ze,Ye)===-1&&Te(ze,"$<")===-1){var $e=Re(qe,Ne,Ge,ze);if($e.done)return $e.value}var Pe=G(ze);Pe||(ze=ie(ze));var Me,Ve=ie(R(Ne)),tt=Te(Ve,"g")!==-1;tt&&(Me=Te(Ve,"u")!==-1,Ne.lastIndex=0);for(var ut,xt=[];(ut=re(Ne,Ge))!==null&&(ve(xt,ut),tt);)ie(ut[0])===""&&(Ne.lastIndex=fe(Ge,J(Ne.lastIndex),Me));for(var wt,Ht="",Xt=0,Kt=0;Kt<xt.length;Kt++){for(var Ut,en=ie((ut=xt[Kt])[0]),Ke=we(ye(V(ut.index),Ge.length),0),Ft=[],Nt=1;Nt<ut.length;Nt++)ve(Ft,(wt=ut[Nt])===void 0?wt:String(wt));var ht=ut.groups;if(Pe){var Mt=Ae([en],Ft,Ke,Ge);ht!==void 0&&ve(Mt,ht),Ut=ie(j(ze,void 0,Mt))}else Ut=U(en,Ge,Ke,Ft,ht,ze);Ke>=Xt&&(Ht+=Fe(Ge,Xt,Ke)+Ut,Xt=Ke+en.length)}return Ht+Fe(Ge,Xt)}]}),!!de((function(){var je=/./;return je.exec=function(){var qe=[];return qe.groups={a:"7"},qe},"".replace(je,"$<a>")!=="7"}))||!Ee||Se)},744:function(B,Y,D){var j=D(9565),z=D(9504),W=D(9228),q=D(8551),de=D(34),O=D(7750),G=D(2293),Q=D(7829),V=D(8014),J=D(655),ie=D(5966),he=D(6682),fe=D(8429),se=D(9039),U=fe.UNSUPPORTED_Y,R=Math.min,re=z([].push),xe=z("".slice),we=!se((function(){var Ae=/(?:)/,ve=Ae.exec;Ae.exec=function(){return ve.apply(this,arguments)};var Te="ab".split(Ae);return Te.length!==2||Te[0]!=="a"||Te[1]!=="b"})),ye="abbc".split(/(b)*/)[1]==="c"||"test".split(/(?:)/,-1).length!==4||"ab".split(/(?:ab)*/).length!==2||".".split(/(.?)(.?)/).length!==4||".".split(/()()/).length>1||"".split(/.?/).length;W("split",(function(Ae,ve,Te){var Fe="0".split(void 0,0).length?function(Ee,Se){return Ee===void 0&&Se===0?[]:j(ve,this,Ee,Se)}:ve;return[function(Ee,Se){var je=O(this),qe=de(Ee)?ie(Ee,Ae):void 0;return qe?j(qe,Ee,je,Se):j(Fe,J(je),Ee,Se)},function(Ee,Se){var je=q(this),qe=J(Ee);if(!ye){var Re=Te(Fe,je,qe,Se,Fe!==ve);if(Re.done)return Re.value}var Ye=G(je,RegExp),ce=je.unicode,ze=(je.ignoreCase?"i":"")+(je.multiline?"m":"")+(je.unicode?"u":"")+(U?"g":"y"),Ne=new Ye(U?"^(?:"+je.source+")":je,ze),Ge=Se===void 0?4294967295:Se>>>0;if(Ge===0)return[];if(qe.length===0)return he(Ne,qe)===null?[qe]:[];for(var $e=0,Pe=0,Me=[];Pe<qe.length;){Ne.lastIndex=U?0:Pe;var Ve,tt=he(Ne,U?xe(qe,Pe):qe);if(tt===null||(Ve=R(V(Ne.lastIndex+(U?Pe:0)),qe.length))===$e)Pe=Q(qe,Pe,ce);else{if(re(Me,xe(qe,$e,Pe)),Me.length===Ge)return Me;for(var ut=1;ut<=tt.length-1;ut++)if(re(Me,tt[ut]),Me.length===Ge)return Me;Pe=$e=Ve}}return re(Me,xe(qe,$e)),Me}]}),ye||!we,U)},2762:function(B,Y,D){var j=D(6518),z=D(3802).trim;j({target:"String",proto:!0,forced:D(706)("trim")},{trim:function(){return z(this)}})},6761:function(B,Y,D){var j=D(6518),z=D(4576),W=D(9565),q=D(9504),de=D(6395),O=D(3724),G=D(4495),Q=D(9039),V=D(9297),J=D(1625),ie=D(8551),he=D(5397),fe=D(6969),se=D(655),U=D(6980),R=D(2360),re=D(1072),xe=D(8480),we=D(298),ye=D(3717),Ae=D(7347),ve=D(4913),Te=D(6801),Fe=D(8773),Ee=D(6840),Se=D(2106),je=D(5745),qe=D(6119),Re=D(421),Ye=D(3392),ce=D(8227),ze=D(1951),Ne=D(511),Ge=D(8242),$e=D(687),Pe=D(1181),Me=D(9213).forEach,Ve=qe("hidden"),tt="Symbol",ut="prototype",xt=Pe.set,wt=Pe.getterFor(tt),Ht=Object[ut],Xt=z.Symbol,Kt=Xt&&Xt[ut],Ut=z.RangeError,en=z.TypeError,Ke=z.QObject,Ft=Ae.f,Nt=ve.f,ht=we.f,Mt=Fe.f,Qt=q([].push),Wt=je("symbols"),Ue=je("op-symbols"),dt=je("wks"),pt=!Ke||!Ke[ut]||!Ke[ut].findChild,De=function(bt,Pt,vt){var He=Ft(Ht,Pt);He&&delete Ht[Pt],Nt(bt,Pt,vt),He&&bt!==Ht&&Nt(Ht,Pt,He)},Le=O&&Q((function(){return R(Nt({},"a",{get:function(){return Nt(this,"a",{value:7}).a}})).a!==7}))?De:Nt,at=function(bt,Pt){var vt=Wt[bt]=R(Kt);return xt(vt,{type:tt,tag:bt,description:Pt}),O||(vt.description=Pt),vt},Ce=function(bt,Pt,vt){bt===Ht&&Ce(Ue,Pt,vt),ie(bt);var He=fe(Pt);return ie(vt),V(Wt,He)?(vt.enumerable?(V(bt,Ve)&&bt[Ve][He]&&(bt[Ve][He]=!1),vt=R(vt,{enumerable:U(0,!1)})):(V(bt,Ve)||Nt(bt,Ve,U(1,R(null))),bt[Ve][He]=!0),Le(bt,He,vt)):Nt(bt,He,vt)},We=function(bt,Pt){ie(bt);var vt=he(Pt),He=re(vt).concat(rt(vt));return Me(He,(function(St){O&&!W(Xe,vt,St)||Ce(bt,St,vt[St])})),bt},Xe=function(bt){var Pt=fe(bt),vt=W(Mt,this,Pt);return!(this===Ht&&V(Wt,Pt)&&!V(Ue,Pt))&&(!(vt||!V(this,Pt)||!V(Wt,Pt)||V(this,Ve)&&this[Ve][Pt])||vt)},Qe=function(bt,Pt){var vt=he(bt),He=fe(Pt);if(vt!==Ht||!V(Wt,He)||V(Ue,He)){var St=Ft(vt,He);return!St||!V(Wt,He)||V(vt,Ve)&&vt[Ve][He]||(St.enumerable=!0),St}},Ze=function(bt){var Pt=ht(he(bt)),vt=[];return Me(Pt,(function(He){V(Wt,He)||V(Re,He)||Qt(vt,He)})),vt},rt=function(bt){var Pt=bt===Ht,vt=ht(Pt?Ue:he(bt)),He=[];return Me(vt,(function(St){!V(Wt,St)||Pt&&!V(Ht,St)||Qt(He,Wt[St])})),He};G||(Xt=function(){if(J(Kt,this))throw new en("Symbol is not a constructor");var bt=arguments.length&&arguments[0]!==void 0?se(arguments[0]):void 0,Pt=Ye(bt),vt=function(He){var St=this===void 0?z:this;St===Ht&&W(vt,Ue,He),V(St,Ve)&&V(St[Ve],Pt)&&(St[Ve][Pt]=!1);var Ct=U(1,He);try{Le(St,Pt,Ct)}catch(Zt){if(!(Zt instanceof Ut))throw Zt;De(St,Pt,Ct)}};return O&&pt&&Le(Ht,Pt,{configurable:!0,set:vt}),at(Pt,bt)},Ee(Kt=Xt[ut],"toString",(function(){return wt(this).tag})),Ee(Xt,"withoutSetter",(function(bt){return at(Ye(bt),bt)})),Fe.f=Xe,ve.f=Ce,Te.f=We,Ae.f=Qe,xe.f=we.f=Ze,ye.f=rt,ze.f=function(bt){return at(ce(bt),bt)},O&&(Se(Kt,"description",{configurable:!0,get:function(){return wt(this).description}}),de||Ee(Ht,"propertyIsEnumerable",Xe,{unsafe:!0}))),j({global:!0,constructor:!0,wrap:!0,forced:!G,sham:!G},{Symbol:Xt}),Me(re(dt),(function(bt){Ne(bt)})),j({target:tt,stat:!0,forced:!G},{useSetter:function(){pt=!0},useSimple:function(){pt=!1}}),j({target:"Object",stat:!0,forced:!G,sham:!O},{create:function(bt,Pt){return Pt===void 0?R(bt):We(R(bt),Pt)},defineProperty:Ce,defineProperties:We,getOwnPropertyDescriptor:Qe}),j({target:"Object",stat:!0,forced:!G},{getOwnPropertyNames:Ze}),Ge(),$e(Xt,tt),Re[Ve]=!0},9463:function(B,Y,D){var j=D(6518),z=D(3724),W=D(4576),q=D(9504),de=D(9297),O=D(4901),G=D(1625),Q=D(655),V=D(2106),J=D(7740),ie=W.Symbol,he=ie&&ie.prototype;if(z&&O(ie)&&(!("description"in he)||ie().description!==void 0)){var fe={},se=function(){var Ae=arguments.length<1||arguments[0]===void 0?void 0:Q(arguments[0]),ve=G(he,this)?new ie(Ae):Ae===void 0?ie():ie(Ae);return Ae===""&&(fe[ve]=!0),ve};J(se,ie),se.prototype=he,he.constructor=se;var U=String(ie("description detection"))==="Symbol(description detection)",R=q(he.valueOf),re=q(he.toString),xe=/^Symbol\((.*)\)[^)]+$/,we=q("".replace),ye=q("".slice);V(he,"description",{configurable:!0,get:function(){var Ae=R(this);if(de(fe,Ae))return"";var ve=re(Ae),Te=U?ye(ve,7,-1):we(ve,xe,"$1");return Te===""?void 0:Te}}),j({global:!0,constructor:!0,forced:!0},{Symbol:se})}},1510:function(B,Y,D){var j=D(6518),z=D(7751),W=D(9297),q=D(655),de=D(5745),O=D(1296),G=de("string-to-symbol-registry"),Q=de("symbol-to-string-registry");j({target:"Symbol",stat:!0,forced:!O},{for:function(V){var J=q(V);if(W(G,J))return G[J];var ie=z("Symbol")(J);return G[J]=ie,Q[ie]=J,ie}})},2259:function(B,Y,D){D(511)("iterator")},2675:function(B,Y,D){D(6761),D(1510),D(7812),D(3110),D(9773)},7812:function(B,Y,D){var j=D(6518),z=D(9297),W=D(757),q=D(6823),de=D(5745),O=D(1296),G=de("symbol-to-string-registry");j({target:"Symbol",stat:!0,forced:!O},{keyFor:function(Q){if(!W(Q))throw new TypeError(q(Q)+" is not a symbol");if(z(G,Q))return G[Q]}})},5700:function(B,Y,D){var j=D(511),z=D(8242);j("toPrimitive"),z()},8344:function(B,Y,D){D(8543)},3500:function(B,Y,D){var j=D(4576),z=D(7400),W=D(9296),q=D(235),de=D(6699),O=function(Q){if(Q&&Q.forEach!==q)try{de(Q,"forEach",q)}catch{Q.forEach=q}};for(var G in z)z[G]&&O(j[G]&&j[G].prototype);O(W)},2953:function(B,Y,D){var j=D(4576),z=D(7400),W=D(9296),q=D(3792),de=D(6699),O=D(687),G=D(8227)("iterator"),Q=q.values,V=function(ie,he){if(ie){if(ie[G]!==Q)try{de(ie,G,Q)}catch{ie[G]=Q}if(O(ie,he,!0),z[he]){for(var fe in q)if(ie[fe]!==q[fe])try{de(ie,fe,q[fe])}catch{ie[fe]=q[fe]}}}};for(var J in z)V(j[J]&&j[J].prototype,J);V(W,"DOMTokenList")}},d={};function u(B){var Y=d[B];if(Y!==void 0)return Y.exports;var D=d[B]={exports:{}};return c[B].call(D.exports,D,D.exports,u),D.exports}u.d=function(B,Y){for(var D in Y)u.o(Y,D)&&!u.o(B,D)&&Object.defineProperty(B,D,{enumerable:!0,get:Y[D]})},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(B,Y){return Object.prototype.hasOwnProperty.call(B,Y)},u.r=function(B){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(B,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(B,"__esModule",{value:!0})};var m={};function p(B){return(function(Y){if(Array.isArray(Y))return y(Y)})(B)||(function(Y){if(typeof Symbol<"u"&&Y[Symbol.iterator]!=null||Y["@@iterator"]!=null)return Array.from(Y)})(B)||f(B)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
  8356. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function f(B,Y){if(B){if(typeof B=="string")return y(B,Y);var D={}.toString.call(B).slice(8,-1);return D==="Object"&&B.constructor&&(D=B.constructor.name),D==="Map"||D==="Set"?Array.from(B):D==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(D)?y(B,Y):void 0}}function y(B,Y){(Y==null||Y>B.length)&&(Y=B.length);for(var D=0,j=Array(Y);D<Y;D++)j[D]=B[D];return j}function v(B){return v=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},v(B)}function b(B,Y){for(var D=0;D<Y.length;D++){var j=Y[D];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty(B,_(j.key),j)}}function g(B,Y,D){return(Y=_(Y))in B?Object.defineProperty(B,Y,{value:D,enumerable:!0,configurable:!0,writable:!0}):B[Y]=D,B}function _(B){var Y=(function(D,j){if(v(D)!="object"||!D)return D;var z=D[Symbol.toPrimitive];if(z!==void 0){var W=z.call(D,j);if(v(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(D)})(B,"string");return v(Y)=="symbol"?Y:Y+""}u.r(m),u.d(m,{SimpleKeyboard:function(){return be},default:function(){return _e}}),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(B){if("Element"in B){var Y="classList",D="prototype",j=B.Element[D],z=Object,W=String[D].trim||function(){return this.replace(/^\s+|\s+$/g,"")},q=Array[D].indexOf||function(ie){for(var he=0,fe=this.length;he<fe;he++)if(he in this&&this[he]===ie)return he;return-1},de=function(ie,he){this.name=ie,this.code=DOMException[ie],this.message=he},O=function(ie,he){if(he==="")throw new de("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(he))throw new de("INVALID_CHARACTER_ERR","The token must not contain space characters.");return q.call(ie,he)},G=function(ie){for(var he=W.call(ie.getAttribute("class")||""),fe=he?he.split(/\s+/):[],se=0,U=fe.length;se<U;se++)this.push(fe[se]);this._updateClassName=function(){ie.setAttribute("class",this.toString())}},Q=G[D]=[],V=function(){return new G(this)};if(de[D]=Error[D],Q.item=function(ie){return this[ie]||null},Q.contains=function(ie){return~O(this,ie+"")},Q.add=function(){var ie,he=arguments,fe=0,se=he.length,U=!1;do~O(this,ie=he[fe]+"")||(this.push(ie),U=!0);while(++fe<se);U&&this._updateClassName()},Q.remove=function(){var ie,he,fe=arguments,se=0,U=fe.length,R=!1;do for(he=O(this,ie=fe[se]+"");~he;)this.splice(he,1),R=!0,he=O(this,ie);while(++se<U);R&&this._updateClassName()},Q.toggle=function(ie,he){var fe=this.contains(ie),se=fe?he!==!0&&"remove":he!==!1&&"add";return se&&this[se](ie),he===!0||he===!1?he:!fe},Q.replace=function(ie,he){var fe=O(ie+"");~fe&&(this.splice(fe,1,he),this._updateClassName())},Q.toString=function(){return this.join(" ")},z.defineProperty){var J={get:V,enumerable:!0,configurable:!0};try{z.defineProperty(j,Y,J)}catch(ie){ie.number!==void 0&&ie.number!==-2146823252||(J.enumerable=!1,z.defineProperty(j,Y,J))}}else z[D].__defineGetter__&&j.__defineGetter__(Y,V)}})(self),(function(){var B=document.createElement("_");if(B.classList.add("c1","c2"),!B.classList.contains("c2")){var Y=function(j){var z=DOMTokenList.prototype[j];DOMTokenList.prototype[j]=function(W){var q,de=arguments.length;for(q=0;q<de;q++)W=arguments[q],z.call(this,W)}};Y("add"),Y("remove")}if(B.classList.toggle("c3",!1),B.classList.contains("c3")){var D=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(j,z){return 1 in arguments&&!this.contains(j)==!z?z:D.call(this,j)}}"replace"in document.createElement("_").classList||(DOMTokenList.prototype.replace=function(j,z){var W=this.toString().split(" "),q=W.indexOf(j+"");~q&&(W=W.slice(q),this.remove.apply(this,W),this.add(z),this.add.apply(this,W.slice(1)))}),B=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 B=function j(z){var W=z.getOptions,q=z.getCaretPosition,de=z.getCaretPositionEnd,O=z.dispatch;(function(G,Q){if(!(G instanceof Q))throw new TypeError("Cannot call a class as a function")})(this,j),g(this,"getOptions",void 0),g(this,"getCaretPosition",void 0),g(this,"getCaretPositionEnd",void 0),g(this,"dispatch",void 0),g(this,"maxLengthReached",void 0),g(this,"isStandardButton",(function(G){return G&&!(G[0]==="{"&&G[G.length-1]==="}")})),this.getOptions=W,this.getCaretPosition=q,this.getCaretPositionEnd=de,this.dispatch=O,j.bindMethods(j,this)},Y=[{key:"getButtonType",value:function(j){return j.includes("{")&&j.includes("}")&&j!=="{//}"?"functionBtn":"standardBtn"}},{key:"getButtonClass",value:function(j){var z=this.getButtonType(j),W=j.replace("{","").replace("}",""),q="";return z!=="standardBtn"&&(q=" hg-button-".concat(W)),"hg-".concat(z).concat(q)}},{key:"getDefaultDiplay",value:function(){return{"{bksp}":"backspace","{backspace}":"backspace","{enter}":"< enter","{shift}":"shift","{shiftleft}":"shift","{shiftright}":"shift","{alt}":"alt","{s}":"shift","{tab}":"tab","{lock}":"caps","{capslock}":"caps","{accept}":"Submit","{space}":" ","{//}":" ","{esc}":"esc","{escape}":"esc","{f1}":"f1","{f2}":"f2","{f3}":"f3","{f4}":"f4","{f5}":"f5","{f6}":"f6","{f7}":"f7","{f8}":"f8","{f9}":"f9","{f10}":"f10","{f11}":"f11","{f12}":"f12","{numpaddivide}":"/","{numlock}":"lock","{arrowup}":"↑","{arrowleft}":"←","{arrowdown}":"↓","{arrowright}":"→","{prtscr}":"print","{scrolllock}":"scroll","{pause}":"pause","{insert}":"ins","{home}":"home","{pageup}":"up","{delete}":"del","{forwarddelete}":"del","{end}":"end","{pagedown}":"down","{numpadmultiply}":"*","{numpadsubtract}":"-","{numpadadd}":"+","{numpadenter}":"enter","{period}":".","{numpaddecimal}":".","{numpad0}":"0","{numpad1}":"1","{numpad2}":"2","{numpad3}":"3","{numpad4}":"4","{numpad5}":"5","{numpad6}":"6","{numpad7}":"7","{numpad8}":"8","{numpad9}":"9"}}},{key:"getButtonDisplayName",value:function(j,z){return(z=arguments.length>2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),z):z||this.getDefaultDiplay())[j]||j}},{key:"getUpdatedInput",value:function(j,z,W){var q=arguments.length>3&&arguments[3]!==void 0?arguments[3]:W,de=arguments.length>4&&arguments[4]!==void 0&&arguments[4],O=this.getOptions(),G=[W,q,de],Q=z;return(j==="{bksp}"||j==="{backspace}")&&Q.length>0?Q=this.removeAt.apply(this,[Q].concat(G)):(j==="{delete}"||j==="{forwarddelete}")&&Q.length>0?Q=this.removeForwardsAt.apply(this,[Q].concat(G)):j==="{space}"?Q=this.addStringAt.apply(this,[Q," "].concat(G)):j!=="{tab}"||typeof O.tabCharOnTab=="boolean"&&O.tabCharOnTab===!1?j!=="{enter}"&&j!=="{numpadenter}"||!O.newLineOnEnter?j.includes("numpad")&&Number.isInteger(Number(j[j.length-2]))?Q=this.addStringAt.apply(this,[Q,j[j.length-2]].concat(G)):j==="{numpaddivide}"?Q=this.addStringAt.apply(this,[Q,"/"].concat(G)):j==="{numpadmultiply}"?Q=this.addStringAt.apply(this,[Q,"*"].concat(G)):j==="{numpadsubtract}"?Q=this.addStringAt.apply(this,[Q,"-"].concat(G)):j==="{numpadadd}"?Q=this.addStringAt.apply(this,[Q,"+"].concat(G)):j==="{numpaddecimal}"?Q=this.addStringAt.apply(this,[Q,"."].concat(G)):j==="{"||j==="}"?Q=this.addStringAt.apply(this,[Q,j].concat(G)):j.includes("{")||j.includes("}")||(Q=this.addStringAt.apply(this,[Q,j].concat(G))):Q=this.addStringAt.apply(this,[Q,`
  8357. `].concat(G)):Q=this.addStringAt.apply(this,[Q," "].concat(G)),O.debug&&console.log("Input will be: "+Q),Q}},{key:"updateCaretPos",value:function(j){var z=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.updateCaretPosAction(j,z);this.dispatch((function(q){q.setCaretPosition(W)}))}},{key:"updateCaretPosAction",value:function(j){var z=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.getOptions(),q=this.getCaretPosition();return q!=null&&(z?q>0&&(q-=j):q+=j),W.debug&&console.log("Caret at:",q),q}},{key:"addStringAt",value:function(j,z){var W,q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,de=arguments.length>3&&arguments[3]!==void 0?arguments[3]:j.length,O=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return q||q===0?(W=[j.slice(0,q),z,j.slice(de)].join(""),this.isMaxLengthReached()||O&&this.updateCaretPos(z.length)):W=j+z,W}},{key:"removeAt",value:function(j){var z,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j.length,q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,de=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(W===0&&q===0)return j;if(W===q){var O=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;W&&W>=0?j.substring(W-2,W).match(O)?(z=j.substr(0,W-2)+j.substr(W),de&&this.updateCaretPos(2,!0)):(z=j.substr(0,W-1)+j.substr(W),de&&this.updateCaretPos(1,!0)):j.slice(-2).match(O)?(z=j.slice(0,-2),de&&this.updateCaretPos(2,!0)):(z=j.slice(0,-1),de&&this.updateCaretPos(1,!0))}else z=j.slice(0,W)+j.slice(q),de&&this.dispatch((function(G){G.setCaretPosition(W)}));return z}},{key:"removeForwardsAt",value:function(j){var z,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j.length,q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,de=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return j!=null&&j.length&&W!==null?(W===q?z=j.substring(W,W+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?j.substr(0,W)+j.substr(W+2):j.substr(0,W)+j.substr(W+1):(z=j.slice(0,W)+j.slice(q),de&&this.dispatch((function(O){O.setCaretPosition(W)}))),z):j}},{key:"handleMaxLength",value:function(j,z){var W=this.getOptions(),q=W.maxLength,de=j[W.inputName||"default"],O=z.length-1>=q;if(z.length<=de.length)return!1;if(Number.isInteger(q))return W.debug&&console.log("maxLength (num) reached:",O),O?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(v(q)==="object"){var G=z.length-1>=q[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(j){return j?j.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(z,W){return W.length?z+W[0].toUpperCase()+W.slice(1):z})):""}},{key:"chunkArray",value:function(j,z){return p(Array(Math.ceil(j.length/z))).map((function(W,q){return j.slice(z*q,z+z*q)}))}},{key:"escapeRegex",value:function(j){return j.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}},{key:"getRtlOffset",value:function(j,z){var W=j,q=z.indexOf("‫");return q<j&&q!=-1&&W--,z.indexOf("‬")<j&&q!=-1&&W--,W<0?0:W}},{key:"isConstructor",value:function(j){try{Reflect.construct(String,[],j)}catch{return!1}return!0}}],D=[{key:"bindMethods",value:function(j,z){var W,q=(function(O,G){var Q=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!Q){if(Array.isArray(O)||(Q=f(O))||G){Q&&(O=Q);var V=0,J=function(){};return{s:J,n:function(){return V>=O.length?{done:!0}:{done:!1,value:O[V++]}},e:function(se){throw se},f:J}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
  8358. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var ie,he=!0,fe=!1;return{s:function(){Q=Q.call(O)},n:function(){var se=Q.next();return he=se.done,se},e:function(se){fe=!0,ie=se},f:function(){try{he||Q.return==null||Q.return()}finally{if(fe)throw ie}}}})(Object.getOwnPropertyNames(j.prototype));try{for(q.s();!(W=q.n()).done;){var de=W.value;de==="constructor"||de==="bindMethods"||(z[de]=z[de].bind(z))}}catch(O){q.e(O)}finally{q.f()}}}],Y&&b(B.prototype,Y),D&&b(B,D),Object.defineProperty(B,"prototype",{writable:!1}),B;var B,Y,D})();g(k,"noop",(function(){}));var P=k;function N(B){return N=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},N(B)}function M(B,Y){for(var D=0;D<Y.length;D++){var j=Y[D];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty(B,T(j.key),j)}}function A(B,Y,D){return(Y=T(Y))in B?Object.defineProperty(B,Y,{value:D,enumerable:!0,configurable:!0,writable:!0}):B[Y]=D,B}function T(B){var Y=(function(D,j){if(N(D)!="object"||!D)return D;var z=D[Symbol.toPrimitive];if(z!==void 0){var W=z.call(D,j);if(N(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(D)})(B,"string");return N(Y)=="symbol"?Y:Y+""}var C=(function(){return B=function j(z){var W=this,q=z.dispatch,de=z.getOptions;(function(O,G){if(!(O instanceof G))throw new TypeError("Cannot call a class as a function")})(this,j),A(this,"getOptions",void 0),A(this,"dispatch",void 0),A(this,"isModifierKey",(function(O){return O.altKey||O.ctrlKey||O.shiftKey||["Tab","CapsLock","Esc","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(O.code||O.key||W.keyCodeToKey(O?.keyCode))})),this.dispatch=q,this.getOptions=de,P.bindMethods(j,this)},Y=[{key:"handleHighlightKeyDown",value:function(j){var z=this.getOptions();z.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(j)&&(j.preventDefault(),j.stopImmediatePropagation());var W=this.getSimpleKeyboardLayoutKey(j);this.dispatch((function(q){var de,O,G=q.getButtonElement(W),Q=q.getButtonElement("{".concat(W,"}"));if(G)de=G,O=W;else{if(!Q)return;de=Q,O="{".concat(W,"}")}var V,J,ie,he,fe=function(U){U.style.background=z.physicalKeyboardHighlightBgColor||"#dadce4",U.style.color=z.physicalKeyboardHighlightTextColor||"black"};if(de)if(Array.isArray(de)){if(de.forEach((function(U){return fe(U)})),z.physicalKeyboardHighlightPress)if(z.physicalKeyboardHighlightPressUsePointerEvents)(V=de[0])===null||V===void 0||(J=V.onpointerdown)===null||J===void 0||J.call(V,j);else if(z.physicalKeyboardHighlightPressUseClick){var se;(se=de[0])===null||se===void 0||se.click()}else q.handleButtonClicked(O,j)}else fe(de),z.physicalKeyboardHighlightPress&&(z.physicalKeyboardHighlightPressUsePointerEvents?(ie=de)===null||ie===void 0||(he=ie.onpointerdown)===null||he===void 0||he.call(ie,j):z.physicalKeyboardHighlightPressUseClick?de.click():q.handleButtonClicked(O,j))}))}},{key:"handleHighlightKeyUp",value:function(j){var z=this.getOptions();z.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(j)&&(j.preventDefault(),j.stopImmediatePropagation());var W=this.getSimpleKeyboardLayoutKey(j);this.dispatch((function(q){var de,O,G,Q=q.getButtonElement(W)||q.getButtonElement("{".concat(W,"}")),V=function(J){J.removeAttribute&&J.removeAttribute("style")};Q&&(Array.isArray(Q)?(Q.forEach((function(J){return V(J)})),z.physicalKeyboardHighlightPressUsePointerEvents&&((de=Q[0])===null||de===void 0||(O=de.onpointerup)===null||O===void 0||O.call(de,j))):(V(Q),z.physicalKeyboardHighlightPressUsePointerEvents&&(Q==null||(G=Q.onpointerup)===null||G===void 0||G.call(Q,j))))}))}},{key:"getSimpleKeyboardLayoutKey",value:function(j){var z,W="",q=j.code||j.key||this.keyCodeToKey(j?.keyCode);return(W=q!=null&&q.includes("Numpad")||q!=null&&q.includes("Shift")||q!=null&&q.includes("Space")||q!=null&&q.includes("Backspace")||q!=null&&q.includes("Control")||q!=null&&q.includes("Alt")||q!=null&&q.includes("Meta")?j.code||"":j.key||this.keyCodeToKey(j?.keyCode)||"").length>1?(z=W)===null||z===void 0?void 0:z.toLowerCase():W}},{key:"keyCodeToKey",value:function(j){return{8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"A",66:"B",67:"C",68:"D",69:"E",70:"F",71:"G",72:"H",73:"I",74:"J",75:"K",76:"L",77:"M",78:"N",79:"O",80:"P",81:"Q",82:"R",83:"S",84:"T",85:"U",86:"V",87:"W",88:"X",89:"Y",90:"Z",91:"Meta",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}[j]||""}}],Y&&M(B.prototype,Y),D&&M(B,D),Object.defineProperty(B,"prototype",{writable:!1}),B;var B,Y,D})();function F(B){return F=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},F(B)}function $(B,Y){for(var D=0;D<Y.length;D++){var j=Y[D];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty(B,X(j.key),j)}}function I(B,Y,D){return(Y=X(Y))in B?Object.defineProperty(B,Y,{value:D,enumerable:!0,configurable:!0,writable:!0}):B[Y]=D,B}function X(B){var Y=(function(D,j){if(F(D)!="object"||!D)return D;var z=D[Symbol.toPrimitive];if(z!==void 0){var W=z.call(D,j);if(F(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(D)})(B,"string");return F(Y)=="symbol"?Y:Y+""}var L=(function(){return B=function j(z){var W=z.utilities,q=z.options;(function(de,O){if(!(de instanceof O))throw new TypeError("Cannot call a class as a function")})(this,j),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=q,P.bindMethods(j,this),this.pageSize=this.utilities.getOptions().layoutCandidatesPageSize||5},Y=[{key:"destroy",value:function(){this.candidateBoxElement&&(this.candidateBoxElement.remove(),this.pageIndex=0)}},{key:"show",value:function(j){var z=this,W=j.candidateValue,q=j.targetElement,de=j.onSelect;if(W&&W.length){var O=this.utilities.chunkArray(W.split(" "),this.pageSize);this.renderPage({candidateListPages:O,targetElement:q,pageIndex:this.pageIndex,nbPages:O.length,onItemSelected:function(G,Q){de(G,Q),z.destroy()}})}}},{key:"renderPage",value:function(j){var z,W=this,q=j.candidateListPages,de=j.targetElement,O=j.pageIndex,G=j.nbPages,Q=j.onItemSelected;(z=this.candidateBoxElement)===null||z===void 0||z.remove(),this.candidateBoxElement=document.createElement("div"),this.candidateBoxElement.className="hg-candidate-box";var V=document.createElement("ul");V.className="hg-candidate-box-list",q[O].forEach((function(R){var re,xe=document.createElement("li"),we=function(){var ye=new(W.options.useTouchEvents?TouchEvent:MouseEvent)("click");return Object.defineProperty(ye,"target",{value:xe}),ye};xe.className="hg-candidate-box-list-item",xe.innerHTML=((re=W.options.display)===null||re===void 0?void 0:re[R])||R,W.options.useTouchEvents?xe.ontouchstart=function(ye){return Q(R,ye||we())}:xe.onclick=function(){var ye=arguments.length>0&&arguments[0]!==void 0?arguments[0]:we();return Q(R,ye)},V.appendChild(xe)}));var J=O>0,ie=document.createElement("div");ie.classList.add("hg-candidate-box-prev"),J&&ie.classList.add("hg-candidate-box-btn-active");var he=function(){J&&W.renderPage({candidateListPages:q,targetElement:de,pageIndex:O-1,nbPages:G,onItemSelected:Q})};this.options.useTouchEvents?ie.ontouchstart=he:ie.onclick=he,this.candidateBoxElement.appendChild(ie),this.candidateBoxElement.appendChild(V);var fe=O<G-1,se=document.createElement("div");se.classList.add("hg-candidate-box-next"),fe&&se.classList.add("hg-candidate-box-btn-active");var U=function(){fe&&W.renderPage({candidateListPages:q,targetElement:de,pageIndex:O+1,nbPages:G,onItemSelected:Q})};this.options.useTouchEvents?se.ontouchstart=U:se.onclick=U,this.candidateBoxElement.appendChild(se),de.prepend(this.candidateBoxElement)}}],Y&&$(B.prototype,Y),D&&$(B,D),Object.defineProperty(B,"prototype",{writable:!1}),B;var B,Y,D})(),te=L;function ae(B){return(function(Y){if(Array.isArray(Y))return ee(Y)})(B)||(function(Y){if(typeof Symbol<"u"&&Y[Symbol.iterator]!=null||Y["@@iterator"]!=null)return Array.from(Y)})(B)||(function(Y,D){if(Y){if(typeof Y=="string")return ee(Y,D);var j={}.toString.call(Y).slice(8,-1);return j==="Object"&&Y.constructor&&(j=Y.constructor.name),j==="Map"||j==="Set"?Array.from(Y):j==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(j)?ee(Y,D):void 0}})(B)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
  8359. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function ee(B,Y){(Y==null||Y>B.length)&&(Y=B.length);for(var D=0,j=Array(Y);D<Y;D++)j[D]=B[D];return j}function me(B){return me=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},me(B)}function le(B,Y){var D=Object.keys(B);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(B);Y&&(j=j.filter((function(z){return Object.getOwnPropertyDescriptor(B,z).enumerable}))),D.push.apply(D,j)}return D}function ue(B,Y){for(var D=0;D<Y.length;D++){var j=Y[D];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty(B,ne(j.key),j)}}function K(B,Y,D){return(Y=ne(Y))in B?Object.defineProperty(B,Y,{value:D,enumerable:!0,configurable:!0,writable:!0}):B[Y]=D,B}function ne(B){var Y=(function(D,j){if(me(D)!="object"||!D)return D;var z=D[Symbol.toPrimitive];if(z!==void 0){var W=z.call(D,j);if(me(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(D)})(B,"string");return me(Y)=="symbol"?Y:Y+""}var oe=(function(){return B=function j(z,W){var q=this;if((function(he,fe){if(!(he instanceof fe))throw new TypeError("Cannot call a class as a function")})(this,j),K(this,"input",void 0),K(this,"options",void 0),K(this,"utilities",void 0),K(this,"caretPosition",void 0),K(this,"caretPositionEnd",void 0),K(this,"keyboardDOM",void 0),K(this,"keyboardPluginClasses",void 0),K(this,"keyboardDOMClass",void 0),K(this,"buttonElements",void 0),K(this,"currentInstanceName",void 0),K(this,"allKeyboardInstances",void 0),K(this,"keyboardInstanceNames",void 0),K(this,"isFirstKeyboardInstance",void 0),K(this,"physicalKeyboard",void 0),K(this,"modules",void 0),K(this,"activeButtonClass",void 0),K(this,"holdInteractionTimeout",void 0),K(this,"holdTimeout",void 0),K(this,"isMouseHold",void 0),K(this,"initialized",void 0),K(this,"candidateBox",void 0),K(this,"keyboardRowsDOM",void 0),K(this,"defaultName","default"),K(this,"activeInputElement",null),K(this,"handleParams",(function(he,fe){var se,U,R;if(typeof he=="string")se=he.split(".").join(""),U=document.querySelector(".".concat(se)),R=fe;else if(he instanceof HTMLDivElement){if(!he.className)throw console.warn("Any DOM element passed as parameter must have a class."),new Error("KEYBOARD_DOM_CLASS_ERROR");se=he.className.split(" ")[0],U=he,R=fe}else se="simple-keyboard",U=document.querySelector(".".concat(se)),R=he;return{keyboardDOMClass:se,keyboardDOM:U,options:R}})),K(this,"getOptions",(function(){return q.options})),K(this,"getCaretPosition",(function(){return q.caretPosition})),K(this,"getCaretPositionEnd",(function(){return q.caretPositionEnd})),K(this,"registerModule",(function(he,fe){q.modules[he]||(q.modules[he]={}),fe(q.modules[he])})),K(this,"getKeyboardClassString",(function(){for(var he=arguments.length,fe=new Array(he),se=0;se<he;se++)fe[se]=arguments[se];return[q.keyboardDOMClass].concat(fe).filter((function(U){return!!U})).join(" ")})),typeof window<"u"){var de=this.handleParams(z,W),O=de.keyboardDOMClass,G=de.keyboardDOM,Q=de.options,V=Q===void 0?{}:Q;this.utilities=new P({getOptions:this.getOptions,getCaretPosition:this.getCaretPosition,getCaretPositionEnd:this.getCaretPositionEnd,dispatch:this.dispatch}),this.caretPosition=null,this.caretPositionEnd=null,this.keyboardDOM=G,this.options=(function(he){for(var fe=1;fe<arguments.length;fe++){var se=arguments[fe]!=null?arguments[fe]:{};fe%2?le(Object(se),!0).forEach((function(U){K(he,U,se[U])})):Object.getOwnPropertyDescriptors?Object.defineProperties(he,Object.getOwnPropertyDescriptors(se)):le(Object(se)).forEach((function(U){Object.defineProperty(he,U,Object.getOwnPropertyDescriptor(se,U))}))}return he})({layoutName:"default",theme:"hg-theme-default",inputName:"default",preventMouseDownDefault:!1,enableLayoutCandidates:!0,excludeFromLayout:{}},V),this.keyboardPluginClasses="",P.bindMethods(j,this);var J=this.options.inputName,ie=J===void 0?this.defaultName:J;if(this.input={},this.input[ie]="",this.keyboardDOMClass=O,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 C({dispatch:this.dispatch,getOptions:this.getOptions}),this.candidateBox=this.options.enableLayoutCandidates?new te({utilities:this.utilities,options:this.options}):null,!this.keyboardDOM)throw console.warn('".'.concat(O,'" was not found in the DOM.')),new Error("KEYBOARD_DOM_ERROR");this.render(),this.modules={},this.loadModules()}},Y=[{key:"setCaretPosition",value:function(j){var z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j;this.caretPosition=j,this.caretPositionEnd=z}},{key:"getInputCandidates",value:function(j){var z=this,W=this.options,q=W.layoutCandidates,de=W.layoutCandidatesCaseSensitiveMatch;if(!q||me(q)!=="object")return{};var O=Object.keys(q).filter((function(V){var J=j.substring(0,z.getCaretPositionEnd()||0)||j,ie=new RegExp("".concat(z.utilities.escapeRegex(V),"$"),de?"g":"gi");return!!ae(J.matchAll(ie)).length}));if(O.length>1){var G=O.sort((function(V,J){return J.length-V.length}))[0];return{candidateKey:G,candidateValue:q[G]}}if(O.length){var Q=O[0];return{candidateKey:Q,candidateValue:q[Q]}}return{}}},{key:"showCandidatesBox",value:function(j,z,W){var q=this;this.candidateBox&&this.candidateBox.show({candidateValue:z,targetElement:W,onSelect:function(de,O){var G=q.options,Q=G.layoutCandidatesCaseSensitiveMatch,V=G.disableCandidateNormalization,J=G.enableLayoutCandidatesKeyPress,ie=de;V||(ie=de.normalize("NFD")),typeof q.options.beforeInputUpdate=="function"&&q.options.beforeInputUpdate(q);var he=q.getInput(q.options.inputName,!0),fe=q.getCaretPositionEnd()||0,se=he.substring(0,fe||0)||he,U=new RegExp("".concat(q.utilities.escapeRegex(j),"$"),Q?"g":"gi"),R=se.replace(U,ie),re=he.replace(se,R),xe=R.length-se.length,we=(fe||he.length)+xe;we<0&&(we=0),q.setInput(re,q.options.inputName,!0),q.setCaretPosition(we),J&&typeof q.options.onKeyPress=="function"&&q.options.onKeyPress(de,O),typeof q.options.onChange=="function"&&q.options.onChange(q.getInput(q.options.inputName,!0),O),typeof q.options.onChangeAll=="function"&&q.options.onChangeAll(q.getAllInputs(),O)}})}},{key:"handleButtonClicked",value:function(j,z){var W=this.options,q=W.inputName,de=q===void 0?this.defaultName:q,O=W.debug;if(j!=="{//}"){this.input[de]||(this.input[de]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var G=this.utilities.getUpdatedInput(j,this.input[de],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(j)&&this.activeInputElement&&this.input[de]&&this.input[de]===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(j,z);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(j,z),this.input[de]!==G&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid(G))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,G))return;var Q=this.utilities.getUpdatedInput(j,this.input[de],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(Q,this.options.inputName,!0),O&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),z?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),z),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),z),z!=null&&z.target&&this.options.enableLayoutCandidates){var V,J=this.getInputCandidates(G),ie=J.candidateKey,he=J.candidateValue;ie&&he?this.showCandidatesBox(ie,he,this.keyboardDOM):(V=this.candidateBox)===null||V===void 0||V.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)),O&&console.log("Key pressed:",j)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(j){this.options.syncInstanceInputs?this.dispatch((function(z){z.isMouseHold=j})):this.isMouseHold=j}},{key:"handleButtonMouseDown",value:function(j,z){var W=this;z&&(this.options.preventMouseDownDefault&&z.preventDefault(),this.options.stopMouseDownPropagation&&z.stopPropagation(),z.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()&&(!j.includes("{")&&!j.includes("}")||j==="{delete}"||j==="{backspace}"||j==="{bksp}"||j==="{space}"||j==="{tab}")||j==="{arrowright}"||j==="{arrowleft}"||j==="{arrowup}"||j==="{arrowdown}")&&(W.options.debug&&console.log("Button held:",j),W.handleButtonHold(j)),clearTimeout(W.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(j,z){var W=this;z&&(this.options.preventMouseUpDefault&&z.preventDefault&&z.preventDefault(),this.options.stopMouseUpPropagation&&z.stopPropagation&&z.stopPropagation(),!(z.target===this.keyboardDOM||z.target&&this.keyboardDOM.contains(z.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(z.target===this.candidateBox.candidateBoxElement||z.target&&this.candidateBox.candidateBoxElement.contains(z.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(q){q.classList.remove(W.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),j&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(j,z)}},{key:"handleKeyboardContainerMouseDown",value:function(j){this.options.preventMouseDownDefault&&j.preventDefault()}},{key:"handleButtonHold",value:function(j){var z=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){z.getMouseHold()?(z.handleButtonClicked(j),z.handleButtonHold(j)):clearTimeout(z.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var j=this;this.dispatch((function(z){z.replaceInput(j.input),z.setCaretPosition(j.caretPosition,j.caretPositionEnd)}))}},{key:"clearInput",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[j]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,z=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!z&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[j].replace("‫","").replace("‬","")+"‬":this.input[j]}},{key:"getAllInputs",value:function(){var j=this,z={};return Object.keys(this.input).forEach((function(W){z[W]=j.getInput(W,!0)})),z}},{key:"setInput",value:function(j){var z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,W=arguments.length>2?arguments[2]:void 0;this.input[z]=j,!W&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(j){this.input=j}},{key:"setOptions",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},z=this.changedOptions(j);this.options=Object.assign(this.options,j),z.length&&(this.options.debug&&console.log("changedOptions",z),this.onSetOptions(z),this.render())}},{key:"changedOptions",value:function(j){var z=this;return Object.keys(j).filter((function(W){return JSON.stringify(j[W])!==JSON.stringify(z.options[W])}))}},{key:"onSetOptions",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];j.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(j.includes("layoutCandidatesPageSize")||j.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new te({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(j){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(z){j(window.SimpleKeyboardInstances[z],z)}))}},{key:"addButtonTheme",value:function(j,z){var W=this;z&&j&&(j.split(" ").forEach((function(q){z.split(" ").forEach((function(de){W.options.buttonTheme||(W.options.buttonTheme=[]);var O=!1;W.options.buttonTheme.map((function(G){if(G!=null&&G.class.split(" ").includes(de)){O=!0;var Q=G.buttons.split(" ");Q.includes(q)||(O=!0,Q.push(q),G.buttons=Q.join(" "))}return G})),O||W.options.buttonTheme.push({class:de,buttons:j})}))})),this.render())}},{key:"removeButtonTheme",value:function(j,z){var W=this;if(!j&&!z)return this.options.buttonTheme=[],void this.render();j&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(j.split(" ").forEach((function(q){var de;(de=W.options)===null||de===void 0||(de=de.buttonTheme)===null||de===void 0||de.map((function(O,G){if(O&&z&&z.includes(O.class)||!z){var Q,V,J=(Q=O)===null||Q===void 0?void 0:Q.buttons.split(" ").filter((function(ie){return ie!==q}));O&&J!=null&&J.length?O.buttons=J.join(" "):((V=W.options.buttonTheme)===null||V===void 0||V.splice(G,1),O=null)}return O}))})),this.render())}},{key:"getButtonElement",value:function(j){var z,W=this.buttonElements[j];return W&&(z=W.length>1?W:W[0]),z}},{key:"inputPatternIsValid",value:function(j){var z,W=this.options.inputPattern;if((z=W instanceof RegExp?W:W[this.options.inputName||this.defaultName])&&j){var q=z.test(j);return this.options.debug&&console.log('inputPattern ("'.concat(z,'"): ').concat(q?"passed":"did not pass!")),q}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var j=this.options.physicalKeyboardHighlightPreventDefault,z=j!==void 0&&j;document.addEventListener("keyup",this.handleKeyUp,z),document.addEventListener("keydown",this.handleKeyDown,z),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(j){this.caretEventHandler(j),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(j)}},{key:"handleKeyDown",value:function(j){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(j)}},{key:"handleMouseUp",value:function(j){this.caretEventHandler(j)}},{key:"handleTouchEnd",value:function(j){this.caretEventHandler(j)}},{key:"handleSelect",value:function(j){this.caretEventHandler(j)}},{key:"handleSelectionChange",value:function(j){navigator.userAgent.includes("Firefox")||this.caretEventHandler(j)}},{key:"caretEventHandler",value:function(j){var z,W=this;j.target.tagName&&(z=j.target.tagName.toLowerCase()),this.dispatch((function(q){var de=j.target===q.keyboardDOM||j.target&&q.keyboardDOM.contains(j.target);if(W.options.syncInstanceInputs&&Array.isArray(j.path)&&(de=j.path.some((function(Q){var V;return Q==null||(V=Q.hasAttribute)===null||V===void 0?void 0:V.call(Q,"data-skInstance")}))),(z==="textarea"||z==="input"&&["text","search","url","tel","password"].includes(j.target.type))&&!q.options.disableCaretPositioning){var O=j.target.selectionStart,G=j.target.selectionEnd;q.options.rtl&&(O=q.utilities.getRtlOffset(O,q.getInput()),G=q.utilities.getRtlOffset(G,q.getInput())),q.setCaretPosition(O,G),q.activeInputElement=j.target,q.options.debug&&console.log("Caret at: ",q.getCaretPosition(),q.getCaretPositionEnd(),j&&j.target.tagName.toLowerCase(),"(".concat(q.keyboardDOMClass,")"),j?.type)}else!q.options.disableCaretPositioning&&de||j?.type==="selectionchange"||(q.setCaretPosition(null),q.activeInputElement=null,q.options.debug&&console.log('Caret position reset due to "'.concat(j?.type,'" event'),j))}))}},{key:"recurseButtons",value:function(j){var z=this;j&&Object.keys(this.buttonElements).forEach((function(W){return z.buttonElements[W].forEach(j)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var j=this.options.physicalKeyboardHighlightPreventDefault,z=j!==void 0&&j;document.removeEventListener("keyup",this.handleKeyUp,z),document.removeEventListener("keydown",this.handleKeyDown,z),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(j){var z=this.options.buttonTheme,W=[];return Array.isArray(z)&&z.forEach((function(q){if(q&&q.class&&typeof q.class=="string"&&q.buttons&&typeof q.buttons=="string"){var de=q.class.split(" ");q.buttons.split(" ").includes(j)&&(W=[].concat(ae(W),ae(de)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',q)})),W}},{key:"setDOMButtonAttributes",value:function(j,z){var W=this.options.buttonAttributes;Array.isArray(W)&&W.forEach((function(q){q.attribute&&typeof q.attribute=="string"&&q.value&&typeof q.value=="string"?q.buttons&&typeof q.buttons=="string"?q.buttons.split(" ").includes(j)&&z(q.attribute,q.value):z(q.attribute,q.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',q)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(j){var z;if((z=j.target.classList)!==null&&z!==void 0&&z.contains("hg-button"))return j.preventDefault(),j.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var j=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(z){var W=j.utilities.isConstructor(z)?new z(j):z(j);W.init&&W.init(j)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(j,z){return!!this.modules[j]&&this.modules[j][z]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(j,z,W,q){var de=this,O=Array.from(j.children),G=0;return O.length&&W.forEach((function(Q,V){var J=q[V];if(!(J&&J>Q))return!1;var ie=Q-G,he=J-G,fe=document.createElement("div");fe.className+="hg-button-container";var se="".concat(de.options.layoutName,"-r").concat(z,"c").concat(V);fe.setAttribute("data-skUID",se);var U=O.splice(ie,he-ie+1);G+=he-ie,U.forEach((function(R){return fe.appendChild(R)})),O.splice(ie,0,fe),j.innerHTML="",O.forEach((function(R){return j.appendChild(R)})),de.options.debug&&console.log("rowDOMContainer",U,ie,he,G+1)})),j}},{key:"render",value:function(){var j=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var z="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}"]},q=this.options.useTouchEvents||!1,de=q?"hg-touch-events":"",O=this.options.useMouseEvents||!1,G=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,z,this.keyboardPluginClasses,de),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(Q,V){var J=Q.split(" ");j.options.excludeFromLayout&&j.options.excludeFromLayout[j.options.layoutName||j.defaultName]&&(J=J.filter((function(se){return j.options.excludeFromLayout&&!j.options.excludeFromLayout[j.options.layoutName||j.defaultName].includes(se)})));var ie=document.createElement("div");ie.className+="hg-row";var he=[],fe=[];J.forEach((function(se,U){var R,re=!G&&typeof se=="string"&&se.length>1&&se.indexOf("[")===0,xe=!G&&typeof se=="string"&&se.length>1&&se.indexOf("]")===se.length-1;re&&(he.push(U),se=se.replace(/\[/g,"")),xe&&(fe.push(U),se=se.replace(/\]/g,""));var we=j.utilities.getButtonClass(se),ye=j.utilities.getButtonDisplayName(se,j.options.display,j.options.mergeDisplay),Ae=j.options.useButtonTag?"button":"div",ve=document.createElement(Ae);ve.className+="hg-button ".concat(we),(R=ve.classList).add.apply(R,ae(j.getButtonThemeClasses(se))),j.setDOMButtonAttributes(se,(function(Ee,Se){ve.setAttribute(Ee,Se)})),j.activeButtonClass="hg-activeButton",!j.utilities.pointerEventsSupported()||q||O?q?(ve.ontouchstart=function(Ee){j.handleButtonClicked(se,Ee),j.handleButtonMouseDown(se,Ee)},ve.ontouchend=function(Ee){j.handleButtonMouseUp(se,Ee)},ve.ontouchcancel=function(Ee){j.handleButtonMouseUp(se,Ee)}):(ve.onclick=function(Ee){j.setMouseHold(!1),typeof j.options.onKeyReleased=="function"||j.options.useMouseEvents&&j.options.clickOnMouseDown||j.handleButtonClicked(se,Ee)},ve.onmousedown=function(Ee){(typeof j.options.onKeyReleased=="function"||j.options.useMouseEvents&&j.options.clickOnMouseDown)&&!j.isMouseHold&&j.handleButtonClicked(se,Ee),j.handleButtonMouseDown(se,Ee)},ve.onmouseup=function(Ee){j.handleButtonMouseUp(se,Ee)}):(ve.onpointerdown=function(Ee){j.handleButtonClicked(se,Ee),j.handleButtonMouseDown(se,Ee)},ve.onpointerup=function(Ee){j.handleButtonMouseUp(se,Ee)},ve.onpointercancel=function(Ee){j.handleButtonMouseUp(se,Ee)}),ve.setAttribute("data-skBtn",se);var Te="".concat(j.options.layoutName,"-r").concat(V,"b").concat(U);ve.setAttribute("data-skBtnUID",Te);var Fe=document.createElement("span");Fe.innerHTML=ye,ve.appendChild(Fe),j.buttonElements[se]||(j.buttonElements[se]=[]),j.buttonElements[se].push(ve),ie.appendChild(ve)})),ie=j.parseRowDOMContainers(ie,V,he,fe),j.keyboardRowsDOM.appendChild(ie)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||q||O?q?(document.ontouchend=function(Q){return j.handleButtonMouseUp(void 0,Q)},document.ontouchcancel=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.ontouchstart=function(Q){return j.handleKeyboardContainerMouseDown(Q)}):q||(document.onmouseup=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.onmousedown=function(Q){return j.handleKeyboardContainerMouseDown(Q)}):(document.onpointerup=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.onpointerdown=function(Q){return j.handleKeyboardContainerMouseDown(Q)}),this.onInit())}}],Y&&ue(B.prototype,Y),D&&ue(B,D),Object.defineProperty(B,"prototype",{writable:!1}),B;var B,Y,D})(),be=oe,_e=be;return m})()},442:function(l){l.exports=n}},i={};function s(l){var c=i[l];if(c!==void 0)return c.exports;var d=i[l]={exports:{}};return r[l].call(d.exports,d,d.exports,s),d.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var d in c)s.o(c,d)&&!s.o(l,d)&&Object.defineProperty(l,d,{enumerable:!0,get:c[d]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return b}}),s(981);var l=s(442),c=s(548),d=s.n(c);function u(g){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},u(g)}function m(g,_){var k=Object.keys(g);if(Object.getOwnPropertySymbols){var P=Object.getOwnPropertySymbols(g);_&&(P=P.filter((function(N){return Object.getOwnPropertyDescriptor(g,N).enumerable}))),k.push.apply(k,P)}return k}function p(g){for(var _=1;_<arguments.length;_++){var k=arguments[_]!=null?arguments[_]:{};_%2?m(Object(k),!0).forEach((function(P){f(g,P,k[P])})):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(k)):m(Object(k)).forEach((function(P){Object.defineProperty(g,P,Object.getOwnPropertyDescriptor(k,P))}))}return g}function f(g,_,k){return(_=(function(P){var N=(function(M,A){if(u(M)!="object"||!M)return M;var T=M[Symbol.toPrimitive];if(T!==void 0){var C=T.call(M,A);if(u(C)!="object")return C;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(M)})(P,"string");return u(N)=="symbol"?N:N+""})(_))in g?Object.defineProperty(g,_,{value:k,enumerable:!0,configurable:!0,writable:!0}):g[_]=k,g}var y=function(g){return p(p({},g),{},{keyboardRef:null})},v=function(g){var _=g.baseClass||"react-simple-keyboard",k=l.useRef(null),P=l.useRef(null),N=l.useRef(null),M=l.useRef(g);return l.useEffect((function(){return function(){N.current&&N.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")})})(g);if(!k.current){k.current=!0,A.debug&&console.log("ReactSimpleKeyboard: Init");var T=P.current,C=".".concat(_);N.current=new(d())(T||C,A),A.keyboardRef&&A.keyboardRef(N.current)}var F=(function(I,X){var L=y(X),te=y(I);return Object.keys(L).filter((function(ae){return L[ae]!==te[ae]}))})(M.current,A);if(F.length){var $=N.current;M.current=A,$?.setOptions(A),A.debug&&console.log("ReactSimpleKeyboard - setOptions called due to updated props:",F)}}),[k,_,M,g]),l.createElement("div",{className:_,ref:P})},b=v})(),o})()}))})(Vk)),Vk.exports}var brt=grt();const xrt=rc(brt),yrt=new Set(["text","password","email","search","url","number"]);function b3(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 vrt({onVisibilityChange:t}){const[e,n]=w.useState(!1),[r,i]=w.useState(!1),s=w.useRef(!1),[o,l]=w.useState("default"),c=w.useRef(null),d=w.useRef(null),u=w.useRef(null);w.useEffect(()=>{t?.(e)},[e,t]);const m=w.useCallback(v=>{if(s.current)return;const b=v.target;if(!b.closest('[data-vkb="false"]')){if(b instanceof HTMLInputElement){if(!yrt.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=w.useCallback(()=>{setTimeout(()=>{const v=document.activeElement;v&&(u.current?.contains(v)||v===c.current)||(n(!1),c.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",m),document.addEventListener("focusout",p),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",p)}),[m,p]);const f=w.useCallback(()=>{s.current=!0,i(!0),c.current?.blur(),c.current=null,setTimeout(()=>{n(!1),i(!1),s.current=!1},400)},[]),y=w.useCallback(v=>{const b=c.current;if(b){if(v==="{shift}"){l(g=>g==="default"?"shift":"default");return}if(v==="{lock}"){l(g=>g==="default"?"shift":"default");return}if(v==="{close}"){f();return}v==="{bksp}"?b3(b,b.value.slice(0,-1)):v==="{space}"?b3(b,b.value+" "):(b3(b,b.value+v),o==="shift"&&l("default")),b.focus(),d.current?.setInput?.(b.value)}},[o,f]);return e?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:v=>{v.preventDefault(),v.stopPropagation(),r||f()},onTouchStart:v=>{v.preventDefault(),v.stopPropagation(),r||f()},onClick:v=>{v.preventDefault(),v.stopPropagation()}}),!r&&a.jsx("div",{ref:u,className:"relative z-[9999] shrink-0",onMouseDown:v=>v.preventDefault(),onTouchStart:v=>{v.target.closest(".hg-button")||v.preventDefault()},children:a.jsx(xrt,{keyboardRef:v=>{d.current=v},layoutName:o,onKeyPress:y,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 wrt(){const[t,e]=w.useState(null),[n,r]=w.useState(null),[i,s]=w.useState(!1),[o,l]=w.useState(100),[c,d]=w.useState(0),u=w.useRef(Date.now()),{i18n:m}=Lt(),p=Eo(),f=Ic(),y=prt(),{data:v}=et({queryKey:["settings"],queryFn:pe.getSettings});w.useEffect(()=>{v?.language&&v.language!==m.language&&m.changeLanguage(v.language)},[v?.language,m]);const{data:b=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>wa.getDevices(),refetchInterval:3e4}),g=b[0],_=y.deviceOnline||!!g?.online,k=w.useMemo(()=>({...y,deviceOnline:_}),[y,_]),P=w.useRef(!1);w.useEffect(()=>{g&&!P.current&&(l(g.display_brightness),d(g.display_blank_timeout),P.current=!0)},[g]),w.useEffect(()=>{const be=document.documentElement,_e=be.classList.contains("dark");return be.classList.add("dark"),()=>{_e||be.classList.remove("dark")}},[]);const{data:N}=et({queryKey:["spoolbuddy-update-check",g?.device_id],queryFn:()=>g?wa.checkDaemonUpdate(g.device_id):Promise.resolve(null),enabled:!!g,refetchInterval:300*1e3,staleTime:0}),M=w.useRef(null);w.useEffect(()=>{if(_)if(N?.update_available&&N.latest_version){const be=`Update available: v${N.latest_version}`;r({type:"info",message:be}),M.current=be}else M.current&&(r(null),M.current=null);else{const be="SpoolBuddy device disconnected";r({type:"warning",message:be}),M.current=be}},[_,N?.update_available,N?.latest_version]);const A=w.useCallback(()=>{u.current=Date.now(),s(!1)},[]);w.useEffect(()=>(window.addEventListener("pointerdown",A),window.addEventListener("keydown",A),()=>{window.removeEventListener("pointerdown",A),window.removeEventListener("keydown",A)}),[A]);const T=!!(y.matchedSpool||y.unknownTagUid),C=w.useRef(!1);w.useEffect(()=>{T&&!C.current&&(A(),f.pathname!=="/spoolbuddy"&&p("/spoolbuddy")),C.current=T},[T,f.pathname,p,A]),w.useEffect(()=>{if(c<=0)return;const be=setInterval(()=>{Date.now()-u.current>=c*1e3&&s(!0)},1e3);return()=>clearInterval(be)},[c]);const{data:F=[]}=et({queryKey:["printers"],queryFn:()=>pe.getPrinters()}),$=ep({queries:F.map(be=>({queryKey:["printerStatus",be.id],queryFn:()=>pe.getPrinterStatus(be.id),refetchInterval:1e4,select:_e=>({connected:_e?.connected})}))}),I=w.useMemo(()=>F.filter((be,_e)=>$[_e]?.data?.connected),[F,$]),X=w.useRef(null),L=w.useRef(!1),te=50,ae=w.useRef(null),ee=w.useCallback(be=>{X.current={x:be.touches[0].clientX,y:be.touches[0].clientY},L.current=!1},[]),me=w.useCallback(be=>{if(!X.current)return;const _e=be.changedTouches[0].clientX-X.current.x,B=be.changedTouches[0].clientY-X.current.y,Y=X.current.y;if(X.current=null,L.current=!1,B>=te&&Math.abs(B)>Math.abs(_e)&&Y<120){ne(!0);return}if(I.length<2||Math.abs(_e)<te||Math.abs(B)>Math.abs(_e))return;const D=I.findIndex(z=>z.id===t),j=_e<0?(D+1)%I.length:(D-1+I.length)%I.length;e(I[j].id)},[I,t,e]);w.useEffect(()=>{const be=ae.current;if(!be)return;const _e=B=>{if(!X.current)return;const Y=Math.abs(B.touches[0].clientX-X.current.x),D=Math.abs(B.touches[0].clientY-X.current.y);if(L.current){B.preventDefault();return}Y>10&&Y>D&&(L.current=!0,B.preventDefault())};return be.addEventListener("touchmove",_e,{passive:!1}),()=>be.removeEventListener("touchmove",_e)},[]);const[le,ue]=w.useState(!1),[K,ne]=w.useState(!1),oe=o<100?{filter:`brightness(${o/100})`}:void 0;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:ae,"data-spoolbuddy-kiosk":!0,className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:{...oe,overscrollBehaviorX:"none"},onTouchStart:ee,onTouchEnd:me,children:[a.jsx("button",{onClick:()=>ne(!0),className:"w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none","aria-label":"Open quick menu",children:a.jsx("div",{className:"w-8 h-0.5 rounded-full bg-zinc-600"})}),a.jsx(ort,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:_}),a.jsx("main",{className:"flex-1 overflow-y-auto",children:a.jsx(qX,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:k,setAlert:r,displayBrightness:o,setDisplayBrightness:l,displayBlankTimeout:c,setDisplayBlankTimeout:d}})}),!le&&a.jsx(drt,{alert:n}),!le&&a.jsx(crt,{}),a.jsx(vrt,{onVisibilityChange:ue})]}),a.jsx(urt,{isOpen:K,onClose:()=>ne(!1),deviceId:g?.device_id??null,deviceOnline:_}),i&&a.jsx("div",{className:"fixed inset-0 bg-black z-[9999]",onPointerDown:be=>{be.stopPropagation(),A()}})]})}function rA({color:t,isEmpty:e,size:n=32}){return e?a.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:a.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):a.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[a.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),a.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const Srt="spoolbuddy-default-core-weight";function Ele(){try{const t=localStorage.getItem(Srt);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function _rt({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:Ele(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,y=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/y*100)):null,b=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,k=p!==null?p-_:null,P=k!==null?Math.abs(k)<=50:null,N=async()=>{if(e!==null){l(!0);try{await wa.updateSpoolWeight(t.id,Math.round(e)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(M){console.error("Failed to sync weight:",M)}finally{l(!1)}}};return a.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[a.jsxs("div",{className:"flex items-start gap-5",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(rA,{color:u,isEmpty:!1,size:100}),v!==null&&a.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:b},children:[v,"%"]})]}),a.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),a.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),a.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",y,"g"]})]}),a.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),a.jsx("div",{className:"mt-2 max-w-xs",children:a.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:b}})})})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),a.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[y,"g"]})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?a.jsxs("span",{className:`flex items-center gap-1 font-mono ${P?"text-green-500":"text-yellow-500"}`,children:[p,"g",P?a.jsx(Kr,{className:"w-3.5 h-3.5"}):a.jsxs(a.Fragment,{children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsx("button",{onClick:N,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:a.jsx(vr,{className:"w-4 h-4"})})]})]}):a.jsx("span",{className:"text-zinc-500",children:"—"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),a.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),a.jsxs("div",{className:"flex gap-2 justify-center",children:[i&&a.jsx("button",{onClick:i,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),a.jsx("button",{onClick:N,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":i?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&a.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function krt({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:i,onClose:s}){const{t:o}=Lt(),l=n??Ele(),c=e!==null?Math.round(Math.max(0,e)):null,d=c!==null?Math.round(Math.max(0,c-l)):null;return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[a.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:a.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),a.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&a.jsxs("div",{className:"text-sm text-zinc-400",children:[a.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),d!==null&&d>0&&a.jsxs("span",{className:"text-zinc-500",children:[" • ~",d,"g filament"]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[i&&a.jsx("button",{onClick:i,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&a.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[a.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&a.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function Nrt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Dle(t){return!t.tray_type||t.tray_type===""}function Crt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Prt({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function Trt({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),a.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function Art({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),a.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function Mrt({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function jrt({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Ert({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Fle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,i;return t<=e?(r="#22a352",i=Prt):t<=n?(r="#d4a017",i=Trt):(r="#c62828",i=Art),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx(i,{className:"w-3 h-3.5"}),a.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function Rle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,i;return t<=e?(r="#22a352",i=Mrt):t<=n?(r="#d4a017",i=jrt):(r="#c62828",i=Ert),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx(i,{className:"w-3 h-3.5"}),a.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function Yz({side:t}){return a.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function Drt({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:i,onClick:s}){const o=Dle(t),l=Nrt(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,d=r===0&&c!==null&&c>0?null:r,u=i??d??c;return a.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[a.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&a.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),a.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&u!==null&&u>=0&&a.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:mx(u)}})}),a.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function Lle({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:i,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],d=t.is_ams_ht,u=d?1:4;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-white font-medium text-base",children:Crt(t.id)}),r&&i&&a.jsx(Yz,{side:i})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&a.jsx(Rle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&a.jsx(Fle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),a.jsx("div",{className:`grid ${d?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:u}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return a.jsx(Drt,{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,Dle(f)?null:f):void 0},p)})})]})}function x3(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function y3(t){return!t.tray_type||t.tray_type===""}function Frt(t){return t?`#${t.slice(0,6)}`:"#808080"}const xP=t=>(t??"").trim().toUpperCase();function Rrt(t,e){const n=xP(t),r=xP(e);return!n||!r?"none":n===r?"exact":r.includes(n)||n.includes(r)?"partial":"none"}function Lrt(t,e){const n=xP(t),r=xP(e);return!n||!r?!1:n===r}function Ole({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:i}=Lt(),s=mn(),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[y,v]=w.useState(null);w.useEffect(()=>{t&&(l(null),d(null),m(!1),f(null),v(null))},[t]);const b=w.useCallback(_e=>{_e.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)),[t,b]);const{data:g}=et({queryKey:["printerStatus",r],queryFn:()=>pe.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:_}=et({queryKey:["printer",r],queryFn:()=>pe.getPrinter(r),enabled:t&&r!==null}),{data:k}=et({queryKey:["settings"],queryFn:()=>pe.getSettings(),enabled:t,staleTime:300*1e3}),{data:P}=et({queryKey:["spool-assignments",r],queryFn:()=>pe.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),N=w.useMemo(()=>{const _e={};if(!P)return _e;for(const B of P){const Y=B.spool;if(Y&&Y.label_weight>0&&Y.weight_used!=null){const D=Math.round(Math.max(0,Y.label_weight-Y.weight_used)/Y.label_weight*100);_e[`${B.ams_id}-${B.tray_id}`]=D}}return _e},[P]),M=k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,A=g?.connected??!1,T=w.useMemo(()=>g?.ams??[],[g?.ams]),C=w.useMemo(()=>T.filter(_e=>!_e.is_ams_ht),[T]),F=w.useMemo(()=>T.filter(_e=>_e.is_ams_ht),[T]),$=w.useMemo(()=>[...g?.vt_tray??[]].sort((_e,B)=>(_e.id??254)-(B.id??254)),[g?.vt_tray]),I=_?.nozzle_count===2||g?.temperatures?.nozzle_2!==void 0,X=w.useRef({});w.useEffect(()=>{g?.ams_extruder_map&&Object.keys(g.ams_extruder_map).length>0&&(X.current=g.ams_extruder_map)},[g?.ams_extruder_map]);const L=g?.ams_extruder_map&&Object.keys(g.ams_extruder_map).length>0?g.ams_extruder_map:X.current,te=w.useCallback(_e=>{if(!I)return null;const B=L[String(_e)],Y=_e>=128?_e-128:_e;return(B!==void 0?B:Y)===1?"L":"R"},[I,L]),ae=lt({mutationFn:async({amsId:_e,trayId:B})=>{if(!r)throw new Error("No printer selected");await pe.assignSpool({spool_id:n.id,printer_id:r,ams_id:_e,tray_id:B})},onSuccess:()=>{d("success"),l(i("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:_e=>{d("error"),l(_e instanceof Error?_e.message:i("spoolbuddy.modal.assignError","Failed to assign spool."))}}),ee=ae.isPending,me=w.useCallback((_e,B)=>{if(_e===254||_e===255){const D=_e===254?254:254+B;return $.find(j=>(j.id??254)===D)||null}return T.find(D=>D.id===_e)?.tray?.find(D=>D.id===B)||null},[T,$]),le=w.useCallback((_e,B)=>_e<=3?`${x3(_e)} ${i("ams.slot","Slot")} ${B+1}`:_e>=128&&_e<=135?x3(_e):_e===254?i("printers.extL","Ext-L"):I?i("printers.extR","Ext-R"):i("printers.ext","Ext"),[i,I]),ue=w.useCallback((_e,B)=>{d("info"),l(i("spoolbuddy.modal.assigning","Configuring slot...")),ae.mutate({amsId:_e,trayId:B})},[ae,i]),K=w.useCallback((_e,B)=>{if(!ee){if(!k?.disable_filament_warnings){const Y=me(_e,B);if(Y&&!y3(Y)){const D=Y.tray_sub_brands||Y.tray_type||"",j=Rrt(n.material,D),z=n.slicer_filament_name||n.slicer_filament,W=Y.tray_type||"",q=Lrt(z,W);if(j!=="exact"||!q){let de="profile";j==="none"&&!q?de="material_profile":j==="partial"&&!q?de="partial_profile":j==="none"?de="material":j==="partial"&&(de="partial");const O=le(_e,B);v({amsId:_e,trayId:B}),f({type:de,spoolMaterial:n.material||"",trayMaterial:D||"",spoolProfile:z||void 0,trayProfile:W||void 0,location:O}),m(!0);return}}}ue(_e,B)}},[ee,k?.disable_filament_warnings,n,me,le,ue]),ne=w.useCallback(()=>{y&&(m(!1),f(null),ue(y.amsId,y.trayId),v(null))},[y,ue]),oe=w.useMemo(()=>{const _e=[];for(const B of F){const Y=B.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},D=N[`${B.id}-0`]??null,j=Y.remain!=null&&Y.remain>=0?Y.remain:null,z=D===0&&j!==null&&j>0?null:D;_e.push({key:`ht-${B.id}`,label:x3(B.id),amsId:B.id,trayId:0,tray:Y,isEmpty:y3(Y),nozzleSide:te(B.id),effectiveFill:z??j})}for(const B of $){const Y=B.id??254,D=Y-254,j=N[`255-${D}`]??null,z=B.remain!=null&&B.remain>=0?B.remain:null,W=j===0&&z!==null&&z>0?null:j;_e.push({key:`ext-${Y}`,label:I?Y===254?i("printers.extL","Ext-L"):i("printers.extR","Ext-R"):i("printers.ext","Ext"),amsId:255,trayId:D,tray:B,isEmpty:y3(B),nozzleSide:I?Y===254?"L":"R":null,effectiveFill:W??z})}return _e},[F,$,I,i,te,N]);if(!t)return null;const be=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:be}}),a.jsx("div",{className:"min-w-0",children:a.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[i("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),a.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),a.jsx("button",{onClick:e,disabled:ee,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),o&&a.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&a.jsx(ct,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&a.jsx(fr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&a.jsx($a,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),a.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto",children:!A&&r?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsx("div",{className:"text-center text-white/50",children:a.jsx("p",{className:"text-lg mb-2",children:i("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):T.length===0&&$.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx(ea,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-lg mb-2",children:i("spoolbuddy.ams.noData","No AMS detected")}),a.jsx("p",{className:"text-sm",children:i("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):a.jsxs(a.Fragment,{children:[C.length>0&&a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:C.map(_e=>a.jsx(Lle,{unit:_e,activeSlot:null,onConfigureSlot:(B,Y)=>K(_e.id,Y),isDualNozzle:I,nozzleSide:te(_e.id),thresholds:M,fillOverrides:N},_e.id))}),oe.length>0&&a.jsx("div",{className:"flex gap-2 shrink-0",children:oe.map(({key:_e,label:B,amsId:Y,trayId:D,tray:j,isEmpty:z,nozzleSide:W,effectiveFill:q})=>{const de=Frt(j.tray_color);return a.jsxs("div",{onClick:()=>K(Y,D),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${ee?"opacity-50 pointer-events-none":""}`,children:[a.jsx("div",{className:"relative w-10 h-10 shrink-0",children:z?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:de}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:de,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-xs text-white/50 font-medium",children:B}),W&&a.jsx(Yz,{side:W})]}),a.jsx("div",{className:"text-sm text-white/80 truncate",children:z?"Empty":j.tray_type||"?"})]}),!z&&q!=null&&q>=0&&a.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:a.jsx("div",{className:"w-full rounded-full",style:{height:`${q}%`,backgroundColor:mx(q)}})})]},_e)})})]})}),a.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:a.jsx("button",{onClick:e,disabled:ee,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?i("spoolbuddy.dashboard.close","Close"):i("spoolbuddy.modal.cancel","Cancel")})})]}),u&&p&&(()=>{let _e="";return p.type==="material"?_e=i("inventory.assignMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type==="partial"?_e=i("inventory.assignPartialMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type==="material_profile"?_e=`${i("inventory.assignMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}
  8360. ${i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})}`:p.type==="partial_profile"?_e=`${i("inventory.assignPartialMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}
  8361. ${i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})}`:p.type==="profile"&&(_e=i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})),a.jsx(kn,{title:i("inventory.assignMismatchTitle"),message:_e,confirmText:i("inventory.assignMismatchConfirm"),variant:"warning",isLoading:ae.isPending,onConfirm:ne,onCancel:()=>{ae.isPending||(m(!1),v(null),f(null))}})})()]})}function Ort({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:i}){const{t:s}=Lt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),d=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(i(o),l(null))};return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:a.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),a.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[a.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?a.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):a.jsx("div",{className:"space-y-2",children:r.map(m=>a.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[a.jsx(rA,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),a.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),a.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),a.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[a.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),a.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}function uX(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Irt(t,e){const n=uX(t),r=uX(e);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}const mX=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function zrt(){const{t}=Lt(),[e,n]=w.useState(0);w.useEffect(()=>{const i=setInterval(()=>{n(s=>(s+1)%mX.length)},5e3);return()=>clearInterval(i)},[]);const r=mX[e];return a.jsxs("div",{className:"flex flex-col items-center text-center",children:[a.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[a.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:[0,1].map(i=>a.jsx("div",{className:"absolute rounded-full border spoolbuddy-optimized-ping",style:{width:80,height:80,borderColor:`${r}4D`,transition:"border-color 140ms linear",animationDelay:`${i*.8}s`}},i))}),a.jsxs("div",{className:"relative overflow-hidden rounded-full",children:[a.jsx("div",{className:"absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow",style:{background:`radial-gradient(circle, ${r} 0%, transparent 70%)`}}),a.jsx("div",{className:"relative",style:{transition:"opacity 140ms linear"},children:a.jsx(rA,{color:r,isEmpty:!1,size:100})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),a.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),a.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),a.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Urt(){const{t}=Lt();return a.jsxs("div",{className:"flex flex-col items-center text-center",children:[a.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:a.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:a.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),a.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),a.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),a.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Brt(){const{sbState:t,selectedPrinterId:e}=Zx(),{t:n}=Lt(),{showToast:r}=xn(),{data:i=[],refetch:s}=et({queryKey:["inventory-spools"],queryFn:()=>pe.getSpools(!1)}),{data:o=[]}=et({queryKey:["printers"],queryFn:()=>pe.getPrinters()}),l=ep({queries:o.map(ne=>({queryKey:["printerStatus",ne.id],queryFn:()=>pe.getPrinterStatus(ne.id),refetchInterval:1e4,select:oe=>({connected:oe?.connected})}))}),[c,d]=w.useState(null),[u,m]=w.useState(null),[p,f]=w.useState(null),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(!1),M=t.matchedSpool?.tag_uid??t.unknownTagUid??null,A=t.weight,T=t.weightStable,C=w.useRef(null);A===null?C.current=null:(C.current===null||Math.abs(A-C.current)>=3||T)&&(C.current=A);const $=C.current,I=w.useMemo(()=>{if(t.matchedSpool?.id){const ne=i.find(oe=>oe.id===t.matchedSpool?.id);if(ne)return ne}return c?i.find(ne=>Irt(ne.tag_uid,c))??null:null},[c,t.matchedSpool,i]),X=w.useMemo(()=>i.filter(ne=>!ne.tag_uid&&!ne.archived_at),[i]);w.useEffect(()=>{if(M){const ne=p===M;(c!==null&&c!==M||!ne&&c!==M)&&(d(M),m(null),f(null)),!ne&&A!==null&&T&&m(Math.round(Math.max(0,A)))}else p&&(d(null),f(null),m(null))},[M,A,T,c,p]);const L=()=>{f(c)},te=async ne=>{if(c)try{await pe.linkTagToSpool(ne.id,{tag_uid:c,tag_type:"generic",data_origin:"nfc_link"}),v(!1),s()}catch(oe){console.error("Failed to link tag:",oe)}},ae=async()=>{if(c){N(!0);try{const ne=me??u;await pe.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:c,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:ne!==null?Math.round(ne):null,last_weighed_at:ne!==null?new Date().toISOString():null})}catch(ne){const oe=ne instanceof Error?ne.message:String(ne);console.error("Failed to quick-add spool:",oe),r(oe||n("spoolbuddy.errors.quickAddFailed","Failed to add spool"),"error")}finally{k(!1),N(!1),s()}}},me=A!==null&&(M===c||M===null&&c!==null)?A:null,le=i.length,ue=new Set(i.map(ne=>ne.material)).size,K=new Set(i.filter(ne=>ne.brand).map(ne=>ne.brand)).size;return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:le}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),a.jsx("div",{className:"w-px h-5 bg-zinc-700"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ue}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),a.jsx("div",{className:"w-px h-5 bg-zinc-700"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:K}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),a.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[a.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[a.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),a.jsxs("div",{className:"space-y-2.5",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500":"bg-red-500"}`}),a.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),a.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),a.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:$!==null?`${Math.abs($)<=20?0:Math.round(Math.max(0,$))}g`:"—"})]}),a.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),a.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),a.jsx("span",{className:`text-sm font-medium ${M?"text-green-500":"text-zinc-500"}`,children:M?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),o.length>0&&a.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),a.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:o.map((ne,oe)=>{const be=l[oe]?.data?.connected??!1;return a.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${ne.name} — ${be?"Online":"Offline"}`,children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${be?"bg-green-500":"bg-zinc-600"}`}),a.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:ne.name})]},ne.id)})})]})]}),a.jsx("div",{className:"w-7/12 min-h-0",children:a.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),a.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(I||t.matchedSpool)&&c&&p!==c?a.jsx(_rt,{spool:(()=>{const ne=I??t.matchedSpool;return{id:ne.id,tag_uid:c,material:ne.material,subtype:ne.subtype,color_name:ne.color_name,rgba:ne.rgba,brand:ne.brand,label_weight:ne.label_weight,core_weight:ne.core_weight,weight_used:ne.weight_used}})(),scaleWeight:me??u,onSyncWeight:()=>s(),onAssignToAms:()=>g(!0),onClose:L}):M&&c&&!I&&!t.matchedSpool&&p!==c?a.jsx(krt,{tagUid:c,scaleWeight:me??u,onLinkSpool:X.length>0?()=>v(!0):void 0,onAddToInventory:()=>k(!0),onClose:L}):a.jsx(zrt,{}):a.jsx(Urt,{})})]})})]}),I&&c&&a.jsx(Ole,{isOpen:b,onClose:()=>g(!1),spool:I,printerId:e}),c&&a.jsx(Ort,{isOpen:y,onClose:()=>v(!1),tagId:c,untaggedSpools:X,onLink:te}),_&&c&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:a.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),a.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[a.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),a.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),a.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),a.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:c}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:()=>k(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),a.jsx("button",{onClick:ae,disabled:P,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:P?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function hX(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Hrt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function $p(t){return!t.tray_type||t.tray_type===""}function qrt(t){return t?`#${t.slice(0,6)}`:"#808080"}function $rt(){const{selectedPrinterId:t,setAlert:e}=Zx(),{t:n}=Lt(),r=mn(),{showToast:i}=xn(),{data:s}=et({queryKey:["printerStatus",t],queryFn:()=>pe.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=et({queryKey:["printer",t],queryFn:()=>pe.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=et({queryKey:["slotPresets",t],queryFn:()=>pe.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=et({queryKey:["settings"],queryFn:()=>pe.getSettings(),staleTime:300*1e3}),{data:d}=et({queryKey:["spoolman-status"],queryFn:pe.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=et({queryKey:["linked-spools"],queryFn:pe.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f}=et({queryKey:["spool-assignments",t],queryFn:()=>pe.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),y=w.useMemo(()=>{const Q={};if(!f)return Q;for(const V of f){const J=V.spool;if(J&&J.label_weight>0&&J.weight_used!=null){const ie=Math.round(Math.max(0,J.label_weight-J.weight_used)/J.label_weight*100);Q[`${V.ams_id}-${V.tray_id}`]=ie}}return Q},[f]),v=o?.serial_number??"",b=w.useCallback((Q,V,J)=>{if(!p||!v)return null;const ie=(J?.tray_uuid||J?.tag_uid||Su(v,Q,V))?.toUpperCase(),he=ie?p[ie]:void 0;return Rk(he)},[p,v]),g=s?.connected??!1,_=w.useRef({});w.useEffect(()=>{t&&s?.ams&&s.ams.length>0&&(_.current[t]=s.ams)},[s?.ams,t]);const k=w.useMemo(()=>{const Q=s?.ams;return Q&&Q.length>0?Q:(t?_.current[t]:null)??[]},[s?.ams,t]),P=w.useMemo(()=>k.filter(Q=>!Q.is_ams_ht),[k]),N=w.useMemo(()=>k.filter(Q=>Q.is_ams_ht),[k]),M=w.useMemo(()=>{const Q={};if(!p||!v)return Q;for(const V of P)for(let J=0;J<(V.tray?.length??0);J++){const ie=V.tray[J],he=b(V.id,J,$p(ie)?null:ie);he!==null&&(Q[`${V.id}-${J}`]=he)}return Q},[p,v,P,b]),A=w.useRef(void 0),T=s?.tray_now;T!==void 0&&T!==255?A.current=T:T===255&&(A.current=void 0);const C=T!==void 0&&T!==255?T:A.current,F=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,$=w.useMemo(()=>[...s?.vt_tray??[]].sort((Q,V)=>(Q.id??254)-(V.id??254)),[s?.vt_tray]),I=c?{humidityGood:Number(c.ams_humidity_good)||40,humidityFair:Number(c.ams_humidity_fair)||60,tempGood:Number(c.ams_temp_good)||28,tempFair:Number(c.ams_temp_fair)||35}:void 0,X=w.useRef({});w.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(X.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const L=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:X.current,te=w.useCallback(Q=>{if(!F)return null;const V=L[String(Q)],J=Q>=128?Q-128:Q;return(V!==void 0?V:J)===1?"L":"R"},[F,L]),[ae,ee]=w.useState(null),[me,le]=w.useState(null),[ue,K]=w.useState(null),[ne,oe]=w.useState(null),be=w.useCallback((Q,V)=>f?.find(J=>J.ams_id===Number(Q)&&J.tray_id===Number(V)),[f]),_e=w.useCallback((Q,V,J)=>{if(!p||!v)return;const ie=(J?.tray_uuid||J?.tag_uid||Su(v,Q,V))?.toUpperCase();return ie?p[ie]:void 0},[p,v]),B=lt({mutationFn:({printerId:Q,amsId:V,trayId:J})=>pe.unassignSpool(Q,V,J),onSuccess:()=>{r.invalidateQueries({queryKey:["spool-assignments",t]}),i(n("inventory.unassignSuccess","Spool unassigned"),"success"),le(null)}}),Y=lt({mutationFn:Q=>pe.unlinkSpool(Q),onSuccess:Q=>{i(n("spoolman.unlinkSuccess")||Q?.message,"success"),r.invalidateQueries({queryKey:["linked-spools"]}),r.invalidateQueries({queryKey:["unlinked-spools"]}),le(null)},onError:Q=>{i(Q.message||n("spoolman.unlinkFailed"),"error")}}),D=w.useCallback(Q=>C===void 0?null:Q<=3&&Math.floor(C/4)===Q?C%4:Q>=128&&Q<=135&&C===Ux(Q,0,!1)?0:null,[C]),j=w.useCallback((Q,V,J)=>{const ie=Q>=128?(Q-128)*4+V+64:Q*4+V,he=l?.[ie],fe=L[String(Q)],se=Q>=128?Q-128:Q,U=fe!==void 0?fe:se,R={amsId:Q,trayId:V,trayCount:J&&Q>=128?1:4,tray:J,trayType:J?.tray_type||void 0,trayColor:J?.tray_color||void 0,traySubBrands:J?.tray_sub_brands||void 0,trayInfoIdx:J?.tray_info_idx||void 0,extruderId:F?U:void 0,caliIdx:J?.cali_idx,savedPresetId:he?.preset_id,location:`${hX(Q)} Slot ${V+1}`};le(R)},[l,L,F]),z=w.useCallback(Q=>{const V=Q.id??254,J=V-254,ie=l?.[1020+J],he={amsId:255,trayId:J,trayCount:1,tray:$p(Q)?null:Q,trayType:Q.tray_type||void 0,trayColor:Q.tray_color||void 0,traySubBrands:Q.tray_sub_brands||void 0,trayInfoIdx:Q.tray_info_idx||void 0,extruderId:F?V===254?1:0:void 0,caliIdx:Q.cali_idx,savedPresetId:ie?.preset_id,location:F?V===254?"Ext-L":"Ext-R":"External"};le(he)},[l,F]),W=w.useCallback(()=>{if(!me)return;const{tray:Q,location:V,...J}=me;le(null),ee(J)},[me]),q=w.useCallback(()=>{if(!me||!t)return;const{amsId:Q,trayId:V,trayType:J,trayColor:ie,location:he}=me;le(null),K({printerId:t,amsId:Q,trayId:V,trayInfo:{type:J||"",material:J,color:ie?.slice(0,6)||"",location:he}})},[me,t]),de=w.useCallback(()=>{if(!me||!t)return;const{amsId:Q,trayId:V,tray:J}=me,ie=(J?.tray_uuid||J?.tag_uid||Su(v,Q,V))?.toUpperCase()||"";le(null),oe({tagUid:J?.tag_uid||ie,trayUuid:J?.tray_uuid||"",printerId:t,amsId:Q,trayId:V})},[me,t,v]),O=w.useCallback(()=>{if(!me||!t)return;const{amsId:Q,trayId:V}=me;B.mutate({printerId:t,amsId:Q,trayId:V})},[me,t,B]);w.useEffect(()=>{if(!g&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const Q of k){const V=Q.tray||[];for(let J=0;J<V.length;J++){const ie=V[J];if(ie.remain!==null&&ie.remain>=0&&ie.remain<15&&ie.tray_type){const he=Q.id===254||Q.id===255,fe=!he&&Q.id>=128,se=uS(Q.id,J,fe,he);e({type:"warning",message:`Low Filament: ${ie.tray_type} (${se}) - ${ie.remain}% remaining`});return}}}e(null)},[k,g,t,e,n]);const G=w.useMemo(()=>{const Q=[];for(const V of N){const J=V.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},ie=b(V.id,0,$p(J)?null:J),he=y[`${V.id}-0`]??null,fe=J.remain!=null&&J.remain>=0?J.remain:null,se=he===0&&fe!==null&&fe>0?null:he;Q.push({key:`ht-${V.id}`,label:hX(V.id),tray:J,isEmpty:$p(J),isActive:D(V.id)===0,temp:V.temp,humidity:V.humidity,nozzleSide:te(V.id),effectiveFill:ie??se??fe,onClick:()=>j(V.id,0,$p(J)?null:J)})}for(const V of $){const J=V.id??254,ie=F&&C===254?J===254&&s?.active_extruder===1||J===255&&s?.active_extruder===0:C===J,he=J-254,fe=b(255,he,$p(V)?null:V),se=y[`255-${he}`]??null,U=V.remain!=null&&V.remain>=0?V.remain:null,R=se===0&&U!==null&&U>0?null:se;Q.push({key:`ext-${J}`,label:F?J===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:V,isEmpty:$p(V),isActive:ie,nozzleSide:null,effectiveFill:fe??R??U,onClick:()=>z(V)})}return Q},[N,$,F,C,s?.active_extruder,n,D,te,j,z,y,b]);return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsx("div",{className:"flex-1 min-h-0",children:t?g?k.length===0&&$.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx(ea,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),a.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):a.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:P.map(Q=>a.jsx(Lle,{unit:Q,activeSlot:D(Q.id),onConfigureSlot:j,isDualNozzle:F,nozzleSide:te(Q.id),thresholds:I,fillOverrides:y,spoolmanFillOverrides:M},Q.id))}),G.length>0&&a.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:G.map(({key:Q,label:V,tray:J,isEmpty:ie,isActive:he,temp:fe,humidity:se,nozzleSide:U,effectiveFill:R,onClick:re})=>{const xe=qrt(J.tray_color);return a.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${he?"ring-2 ring-bambu-green":""}`,onClick:re,children:[a.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[ie?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:xe}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:xe,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),he&&a.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:V}),U&&a.jsx(Yz,{side:U})]}),a.jsx("div",{className:"text-sm text-white/80 truncate",children:ie?"Empty":J.tray_type||"?"}),(fe!=null||se!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[fe!=null&&a.jsx(Rle,{temp:fe,goodThreshold:I?.tempGood,fairThreshold:I?.tempFair}),se!=null&&a.jsx(Fle,{humidity:se,goodThreshold:I?.humidityGood,fairThreshold:I?.humidityFair})]})]}),!ie&&R!=null&&R>=0&&a.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:a.jsx("div",{className:"w-full rounded-full",style:{height:`${R}%`,backgroundColor:mx(R)}})})]},Q)})})]}):a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsx("div",{className:"text-center text-white/50",children:a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),a.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ae&&t&&a.jsx(_ae,{isOpen:!!ae,onClose:()=>ee(null),printerId:t,slotInfo:ae,printerModel:Hrt(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}}),me&&t&&(()=>{const Q=be(me.amsId,me.trayId),V=_e(me.amsId,me.trayId,me.tray);return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>le(null)}),a.jsxs("div",{className:"relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[me.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${me.trayColor.slice(0,6)}`}}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:me.location}),me.traySubBrands&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",me.traySubBrands,")"]})]}),a.jsx("button",{onClick:()=>le(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-2",children:[!u&&Q?.spool&&a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),a.jsxs("div",{className:"flex items-center gap-2",children:[Q.spool.rgba&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${Q.spool.rgba.substring(0,6)}`}}),a.jsxs("span",{className:"text-sm text-white",children:[Q.spool.brand?`${Q.spool.brand} `:"",Q.spool.material,Q.spool.color_name?` - ${Q.spool.color_name}`:""]})]})]}),u&&V&&a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("spoolman.linkedSpool","Linked spool")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",V.id,V.remaining_weight!=null?` (${Math.round(V.remaining_weight)}g)`:""]})})]}),a.jsxs("button",{onClick:W,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left",children:[a.jsx(Nd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("configureAmsSlot.title")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Q?a.jsxs("button",{onClick:O,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",children:[a.jsx(qh,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool","Unassign")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):a.jsxs("button",{onClick:q,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[a.jsx(Na,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(V?.id?a.jsxs("button",{onClick:()=>Y.mutate(V.id),disabled:Y.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[a.jsx(qh,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-amber-400 font-medium",children:n("spoolman.unlinkSpool")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):a.jsxs("button",{onClick:de,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[a.jsx(Lu,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("spoolman.linkToSpoolman")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),ue&&a.jsx(Sae,{isOpen:!!ue,onClose:()=>{K(null),r.invalidateQueries({queryKey:["spool-assignments",t]})},printerId:ue.printerId,amsId:ue.amsId,trayId:ue.trayId,trayInfo:ue.trayInfo}),ne&&a.jsx(wae,{isOpen:!!ne,onClose:()=>oe(null),tagUid:ne.tagUid,trayUuid:ne.trayUuid,printerId:ne.printerId,amsId:ne.amsId,trayId:ne.trayId})]})}function Vrt({type:t,deviceId:e,onClose:n}){const{t:r}=Lt(),[i,s]=w.useState(!1),[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState(!1);w.useEffect(()=>{const y=v=>{v.key==="Escape"&&!i&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[i,n]);const p=w.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(r("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device...
  8362. `)),await wa.queueDiagnostics(e,t);let y=null;const v=60;let b=0;for(;b<v&&!y;){await new Promise(g=>setTimeout(g,500));try{y=await wa.getDiagnosticResult(e,t);break}catch{b++,b%4===0&&l(g=>g+".")}}if(!y)throw new Error("Diagnostic timed out - device did not report results");l(y.output),y.success||d(`Exit code: ${y.exit_code}`)}catch(y){d(y instanceof Error?y.message:"Unknown error"),l("")}finally{s(!1)}},[t,e,r]),f=t==="scale"?r("spoolbuddy.diagnostic.scaleTitle","Scale Diagnostic"):t==="read_tag"?r("spoolbuddy.diagnostic.readTagTitle","Read Tag Diagnostic"):r("spoolbuddy.diagnostic.nfcTitle","NFC Reader Diagnostic");return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:n,children:a.jsxs("div",{className:"bg-zinc-800 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col animate-slide-up",onClick:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"flex justify-between items-center p-4 border-b border-zinc-700",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:f}),a.jsx("button",{onClick:n,className:"text-zinc-400 hover:text-white transition-colors","aria-label":"Close",children:a.jsx(Bt,{size:20})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm",children:i?a.jsxs("div",{className:"flex items-center gap-2 text-green-400",children:[a.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full"}),a.jsx("span",{children:r("spoolbuddy.diagnostic.running","Running diagnostic on device...")})]}):o?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"text-green-400 whitespace-pre-wrap break-words",children:o}),c&&a.jsxs("div",{className:"text-red-400 mt-2",children:["❌ ",c]})]}):u?a.jsx("div",{children:c?a.jsxs("div",{className:"text-red-400",children:["ERROR: ",c]}):a.jsx("span",{className:"text-green-400",children:r("spoolbuddy.diagnostic.completed","Diagnostic completed successfully.")})}):a.jsxs("div",{className:"text-zinc-500",children:[r("spoolbuddy.diagnostic.clickStart",'Click "Run Diagnostic" to start the hardware diagnostic on')," ",e,"."]})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800",children:[a.jsx("button",{onClick:p,disabled:i,className:"flex-1 flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed px-4 py-2 rounded font-semibold text-white transition-colors",children:i?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),r("spoolbuddy.diagnostic.runningBtn","Running...")]}):u?a.jsxs(a.Fragment,{children:[a.jsx(q3,{size:16}),r("spoolbuddy.diagnostic.runAgain","Run Again")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ds,{size:16}),r("spoolbuddy.diagnostic.runBtn","Run Diagnostic")]})}),a.jsx("button",{onClick:n,className:"px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors",children:r("spoolbuddy.diagnostic.close","Close")})]})]})})}function Grt(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 Wrt(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 Krt=[{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 Yrt({device:t}){const{t:e}=Lt(),[n,r]=w.useState(null),[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{!i&&t.backend_url&&s(t.backend_url)},[t.backend_url,i]);const p=async()=>{if(!i.trim()){m({type:"error",text:e("spoolbuddy.settings.systemFieldsRequired","Backend URL is required.")});return}d(!0),m(null);try{await wa.updateSystemConfig(t.device_id,i.trim(),o.trim()||void 0),m({type:"ok",text:e("spoolbuddy.settings.systemQueued","Config queued.")})}catch(f){m({type:"error",text:f instanceof Error?f.message:e("common.error","Error")})}finally{d(!1)}};return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),a.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),a.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"IP"}),a.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),a.jsx("span",{className:"text-zinc-300",children:Grt(t.uptime_s)})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"ID"}),a.jsx("span",{className:"text-zinc-400 font-mono truncate ml-2",children:t.device_id})]})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:e("spoolbuddy.settings.systemConfig","Backend & Auth")}),a.jsx("input",{value:i,onChange:f=>s(f.target.value),placeholder:"http://192.168.1.100:5000",className:"w-full px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"password",value:o,onChange:f=>l(f.target.value),placeholder:e("spoolbuddy.settings.apiTokenPlaceholder","API token"),className:"flex-1 px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),a.jsx("button",{onClick:p,disabled:c,className:"px-3 py-1.5 rounded bg-green-700 hover:bg-green-600 disabled:bg-zinc-700 text-xs font-medium text-zinc-100",children:e("spoolbuddy.settings.saveConfig","Save")})]}),u&&a.jsx("div",{className:`text-xs ${u.type==="ok"?"text-green-400":"text-red-400"}`,children:u.text})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 flex flex-col gap-2",children:[a.jsxs("button",{onClick:()=>r("nfc"),className:"flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(NQ,{className:"w-4 h-4 text-blue-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-blue-100",children:e("spoolbuddy.settings.nfcDiagnostic","NFC Diagnostic")})]}),a.jsxs("button",{onClick:()=>r("scale"),className:"flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-yellow-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-yellow-100",children:e("spoolbuddy.settings.scaleDiagnostic","Scale Diagnostic")})]}),a.jsxs("button",{onClick:()=>r("read_tag"),className:"flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(Ms,{className:"w-4 h-4 text-emerald-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-emerald-100",children:e("spoolbuddy.settings.readTagDiagnostic","Read Tag")})]})]})]}),n&&t&&a.jsx(Vrt,{type:n,deviceId:t.device_id,onClose:()=>r(null)})]})}function Xrt({device:t,onBrightnessChange:e,onBlankTimeoutChange:n}){const{t:r}=Lt(),[i,s]=w.useState(t.display_brightness),[o,l]=w.useState(t.display_blank_timeout),[c,d]=w.useState(!1),u=w.useRef(void 0),m=w.useRef(void 0);w.useEffect(()=>{s(t.display_brightness),l(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const p=w.useCallback(()=>{d(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>d(!1),1500)},[]),f=w.useCallback((b,g)=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{wa.updateDisplay(t.device_id,b,g).then(()=>p()).catch(_=>console.error("Failed to update display:",_))},300)},[t.device_id,p]),y=b=>{s(b),e(b),f(b,o)},v=b=>{l(b),n(b),f(i,b)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:r("spoolbuddy.settings.brightness","Brightness")}),c&&a.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[a.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),r("spoolbuddy.settings.saved","Saved")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("svg",{className:"w-4 h-4 text-zinc-500 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}),a.jsx("input",{type:"range",min:0,max:100,value:i,onChange:b=>y(parseInt(b.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[i,"%"]})]}),!t.has_backlight&&a.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:r("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:r("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),a.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:r("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),a.jsx("div",{className:"grid grid-cols-3 gap-2",children:Krt.map(b=>a.jsx("button",{onClick:()=>v(b.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${o===b.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:b.label},b.value))})]}),a.jsx("p",{className:"text-xs text-zinc-600 text-center",children:r("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function Qrt({step:t,labels:e}){return a.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[a.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?a.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),a.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),a.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),a.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),a.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function Zrt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:i}=Lt(),[s,o]=w.useState("idle"),[l,c]=w.useState("500"),[d,u]=w.useState(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),v=_=>{_==="backspace"?c(k=>k.slice(0,-1)||""):_==="."&&!l.includes(".")?c(k=>k+"."):_>="0"&&_<="9"&&c(k=>k==="0"?_:k+_)},b=async()=>{p(!0),y(null);try{await wa.tare(t.device_id),y({type:"ok",msg:i("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{y({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},g=async()=>{if(s==="tare"){p(!0),y(null);try{u(r),await wa.tare(t.device_id),y({type:"ok",msg:i("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{y({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const _=parseFloat(l);if(r===null||!_||_<=0)return;p(!0),y(null);try{await wa.setCalibrationFactor(t.device_id,_,r,d??void 0),y({type:"ok",msg:i("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{y({type:"error",msg:i("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),a.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[a.jsxs("span",{children:[i("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),a.jsx("span",{className:"mx-1.5",children:"·"}),a.jsxs("span",{children:[i("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&a.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[i("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Wrt(t.last_calibrated_at)]})]}),f&&a.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick: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&&a.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),i("spoolbuddy.weight.tare","Tare")]}),a.jsx("button",{onClick:()=>{o("tare"),y(null)},className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:i("spoolbuddy.weight.calibrate","Calibrate")})]})]}):a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Qrt,{step:s,labels:{tare:i("spoolbuddy.weight.tare","Tare"),weight:i("spoolbuddy.settings.knownWeight","Known weight")}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),a.jsx("span",{className:`text-xs ml-auto ${n?"text-green-400":"text-amber-400"}`,children:n?i("spoolbuddy.settings.stable","Stable"):i("spoolbuddy.settings.settling","Settling...")})]}),f&&a.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),s==="tare"?a.jsx("p",{className:"text-sm text-zinc-300 mb-3",children:i("spoolbuddy.settings.calStep1","Remove all items from the scale and press Set Zero.")}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:i("spoolbuddy.settings.knownWeight","Known weight")}),a.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100",children:[l||"0",a.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1 mb-1.5",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(_=>a.jsx("button",{onClick:()=>v(_),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${_==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:_==="backspace"?"⌫":_},_))})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>{o("idle"),y(null)},className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]",children:i("common.cancel","Cancel")}),a.jsxs("button",{onClick:g,disabled:m,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2",children:[m&&a.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s==="tare"?i("spoolbuddy.settings.setZero","Set Zero"):i("spoolbuddy.settings.calibrateNow","Calibrate")]})]})]})]})}function Jrt({device:t}){const{t:e}=Lt(),[n,r]=w.useState(null),[i,s]=w.useState(null),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.update_status==="pending"||t.update_status==="updating";w.useEffect(()=>{u&&n==="applying"&&r(null)},[u,n]),w.useEffect(()=>{const k=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",k),()=>window.removeEventListener("spoolbuddy-online",k)},[u]);const{data:m,refetch:p}=et({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>wa.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=et({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>wa.getSSHPublicKey(),enabled:o,staleTime:1/0}),y=async()=>{r("checking"),s(null);try{await p()}finally{r(null)}},v=async()=>{r("applying"),s(null);try{await wa.triggerUpdate(t.device_id)}catch(k){s(k instanceof Error?k.message:"Failed to trigger update"),r(null)}},b=n!=null||u,g=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),d(!0),setTimeout(()=>d(!1),2e3))},_=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),a.jsx("span",{className:"text-zinc-200 font-mono",children:_||a.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),b?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a.jsx("span",{className:"text-green-300 text-xs",children:n==="checking"?e("spoolbuddy.settings.checking","Checking for updates..."):t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}):t.update_status==="error"?a.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):i?a.jsx("p",{className:"text-xs text-red-300",children:i}):m?.update_available?a.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",_," → ",m.latest_version]}):null,!b&&(m?.update_available?a.jsx("button",{onClick:v,disabled:!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors",children:t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")}):a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:y,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:e("spoolbuddy.settings.checkUpdates","Check for Updates")}),a.jsx("button",{onClick:v,disabled:!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors",children:e("spoolbuddy.settings.forceUpdate","Force Update")})]}))]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[a.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),a.jsx("svg",{className:`w-3 h-3 text-zinc-500 transition-transform ${o?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&a.jsxs("div",{className:"mt-2 space-y-2",children:[a.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),f?.public_key?a.jsxs("div",{className:"relative",children:[a.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:f.public_key}),a.jsx("button",{onClick:g,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):a.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function pX({percent:t,color:e}){return a.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all ${e}`,style:{width:`${Math.min(100,Math.max(0,t))}%`}})})}function eat(t){const e=Math.floor(t/86400),n=Math.floor(t%86400/3600),r=Math.floor(t%3600/60);return e>0?`${e}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function tat({device:t}){const{t:e}=Lt(),n=t.system_stats;if(!n)return a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("p",{className:"text-sm text-zinc-500",children:e("spoolbuddy.settings.systemStatsWaiting","Waiting for system stats...")})});const r=n.memory,i=n.disk,s=(n.cpu_temp_c??0)>=80?"text-red-400":(n.cpu_temp_c??0)>=65?"text-amber-400":"text-green-400",o=(r?.percent??0)>=90?"bg-red-500":(r?.percent??0)>=70?"bg-amber-500":"bg-green-500",l=(i?.percent??0)>=90?"bg-red-500":(i?.percent??0)>=70?"bg-amber-500":"bg-green-500";return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:"CPU"}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.cores","Cores")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.cpu_count??"-"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.loadAvg","Load Avg")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.load_avg?n.load_avg.join(" / "):"-"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.temp","Temp")}),a.jsx("span",{className:`font-mono font-medium ${s}`,children:n.cpu_temp_c!=null?`${n.cpu_temp_c}°C`:"-"})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.memory","Memory")}),r?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(pX,{percent:r.percent??0,color:o}),a.jsxs("div",{className:"space-y-1 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.used","Used")}),a.jsxs("span",{className:"text-zinc-300 font-mono",children:[r.used_mb," / ",r.total_mb," MB"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.available","Free")}),a.jsxs("span",{className:"text-zinc-300 font-mono",children:[r.available_mb," MB"]})]})]})]}):a.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})]}),a.jsx("div",{className:"bg-zinc-800 rounded-lg px-3 py-2",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 shrink-0",children:e("spoolbuddy.settings.disk","Disk")}),i?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex-1",children:a.jsx(pX,{percent:i.percent??0,color:l})}),a.jsxs("span",{className:"text-xs text-zinc-300 font-mono shrink-0",children:[i.used_gb," / ",i.total_gb," GB"]})]}):a.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.osInfo","OS")}),a.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.os&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.distro","Distro")}),a.jsx("span",{className:"text-zinc-300 truncate ml-2",children:n.os.os})]}),n.os?.kernel&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.kernel","Kernel")}),a.jsx("span",{className:"text-zinc-300 font-mono truncate ml-2",children:n.os.kernel})]}),n.os?.arch&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.arch","Arch")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.arch})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.runtime","Runtime")}),a.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.python&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"Python"}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.python})]}),n.system_uptime_s!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.systemUptime","Uptime")}),a.jsx("span",{className:"text-zinc-300",children:eat(n.system_uptime_s)})]})]})]})]})]})}function nat(){const{sbState:t,setDisplayBrightness:e,setDisplayBlankTimeout:n}=Zx(),{t:r}=Lt(),[i,s]=w.useState("device"),{data:o=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>wa.getDevices(),refetchInterval:1e4}),l=t.deviceId?o.find(d=>d.device_id===t.deviceId)??o[0]:o[0],c=[{id:"device",label:r("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:r("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:r("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:r("spoolbuddy.settings.tabUpdates","Updates")},{id:"system",label:r("spoolbuddy.settings.tabSystem","System")}];return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:r("spoolbuddy.nav.settings","Settings")}),a.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:c.map(d=>a.jsx("button",{onClick:()=>s(d.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${i===d.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:d.label},d.id))}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:l?a.jsxs(a.Fragment,{children:[i==="device"&&a.jsx(Yrt,{device:l}),i==="display"&&a.jsx(Xrt,{device:l,onBrightnessChange:e,onBlankTimeoutChange:n}),i==="scale"&&a.jsx(Zrt,{device:l,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),i==="updates"&&a.jsx(Jrt,{device:l}),i==="system"&&a.jsx(tat,{device:l})]}):a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-center text-zinc-500",children:a.jsx("p",{className:"text-sm",children:r("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function rat({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:i}=Lt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[d,u]=w.useState("500"),[m,p]=w.useState(null),[f,y]=w.useState(!1),v=k=>{k==="backspace"?u(P=>P.slice(0,-1)||""):k==="."&&!d.includes(".")?u(P=>P+"."):k>="0"&&k<="9"&&u(P=>P==="0"?k:P+k)},b=async()=>{y(!0);try{await wa.tare(t.device_id)}catch(k){console.error("Failed to tare:",k)}finally{y(!1)}},g=()=>{c("tare")},_=async()=>{if(l==="tare"){o(!0);try{p(r),await wa.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(r===null||!k||k<=0)return;o(!0);try{await wa.setCalibrationFactor(t.device_id,k,r,m??void 0),c("idle")}catch(P){console.error("Failed to calibrate:",P)}finally{o(!1)}}};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-zinc-400",children:i("spoolbuddy.settings.currentWeight","Current weight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.tareOffset","Tare offset")}),a.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.calFactor","Cal. factor")}),a.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick: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")}),a.jsx("button",{onClick:g,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:i("spoolbuddy.weight.calibrate","Calibrate")})]}):a.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[a.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?i("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):i("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-zinc-400",children:i("spoolbuddy.settings.knownWeight","Known weight (g)")}),a.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100",children:[d||"0",a.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(k=>a.jsx("button",{onClick:()=>v(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))})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:i("common.cancel","Cancel")}),a.jsx("button",{onClick:_,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?i("spoolbuddy.settings.setZero","Set Zero"):i("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function aat(){const{sbState:t}=Zx(),{t:e}=Lt(),n=Eo(),{data:r=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>wa.getDevices(),refetchInterval:1e4}),i=t.deviceId?r.find(s=>s.device_id===t.deviceId)??r[0]:r[0];return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("button",{onClick:()=>n("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),a.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:i?a.jsx(rat,{device:i,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-center text-zinc-500",children:a.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const iat=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function sat(){const{t}=Lt(),{sbState:e}=Zx(),[n,r]=w.useState("existing"),[i,s]=w.useState(null),[o,l]=w.useState(""),[c,d]=w.useState("idle"),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState(null),{data:_=[],refetch:k}=et({queryKey:["inventory-spools"],queryFn:()=>pe.getSpools(!1),refetchInterval:1e4}),{data:P=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>wa.getDevices(),refetchInterval:5e3}),{data:N}=et({queryKey:["settings"],queryFn:pe.getSettings}),M=P[0],A=e.deviceOnline,T=yo(N?.currency||"USD"),C=w.useMemo(()=>{let ue;if(n==="existing")ue=_.filter(K=>!K.tag_uid&&!K.archived_at);else if(n==="replace")ue=_.filter(K=>(K.tag_uid||K.tray_uuid)&&!K.archived_at);else return[];if(o){const K=o.toLowerCase();ue=ue.filter(ne=>ne.material?.toLowerCase().includes(K)||ne.color_name?.toLowerCase().includes(K)||ne.brand?.toLowerCase().includes(K)||ne.subtype?.toLowerCase().includes(K))}return ue},[_,n,o]),F=w.useCallback(ue=>{const K=ue.detail;(K.sak??K.data?.sak)===0&&(v(!0),g(K.tag_uid??K.data?.tag_uid??null))},[]),$=w.useCallback(ue=>{const K=ue.detail;v(!0),g(K.tag_uid??K.data?.tag_uid??null)},[]),I=w.useCallback(()=>{v(!1),g(null)},[]),X=w.useCallback(ue=>{const K=ue.detail;(K.spool_id===i?.id||K.data?.spool_id===i?.id)&&(d("success"),m(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),k(),setTimeout(()=>{d("idle"),s(null),m("")},5e3))},[i,t,k]),L=w.useCallback(ue=>{const K=ue.detail;(K.spool_id===i?.id||K.data?.spool_id===i?.id)&&(d("error"),m(K.message??K.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[i,t]);w.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",F),window.addEventListener("spoolbuddy-tag-matched",$),window.addEventListener("spoolbuddy-tag-removed",I),window.addEventListener("spoolbuddy-tag-written",X),window.addEventListener("spoolbuddy-tag-write-failed",L),()=>{window.removeEventListener("spoolbuddy-unknown-tag",F),window.removeEventListener("spoolbuddy-tag-matched",$),window.removeEventListener("spoolbuddy-tag-removed",I),window.removeEventListener("spoolbuddy-tag-written",X),window.removeEventListener("spoolbuddy-tag-write-failed",L)}),[F,$,I,X,L]),w.useEffect(()=>{s(null),d("idle"),m(""),l("")},[n]);const te=async()=>{if(!(!i||!M)){d("writing"),m(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{await wa.writeTag(M.device_id,i.id)}catch{d("error"),m(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},ae=async()=>{if(M){try{await wa.cancelWrite(M.device_id)}catch{}d("idle"),m("")}},ee=async()=>{if(!(!i||!fX(i))){f(!0),d("idle"),m("");try{await pe.linkTagToSpool(i.id,{tag_uid:"",tray_uuid:"",data_origin:"manual"}),await k(),s(null),d("success"),m(t("spoolbuddy.writeTag.untagSuccess","Tag removed from spool")),setTimeout(()=>{d("idle"),m("")},2500)}catch{d("error"),m(t("spoolbuddy.writeTag.untagFailed","Failed to remove tag from spool"))}finally{f(!1)}}},me=w.useCallback(ue=>{s(ue),d("idle"),m(""),k()},[k]),le=i&&A&&c!=="writing"&&c!=="success";return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(ue=>a.jsx("button",{onClick:()=>r(ue.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===ue.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:ue.label},ue.key))}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?a.jsx(lat,{currencySymbol:T,onCreated:me,selectedSpool:i,t}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"p-3 shrink-0",children:a.jsx("input",{type:"text",value:o,onChange:ue=>l(ue.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:C.length===0?a.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):C.map(ue=>a.jsx(oat,{spool:ue,selected:i?.id===ue.id,showTag:n==="replace",onClick:()=>{s(ue),d("idle"),m("")}},ue.id))})]})}),a.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:a.jsx(cat,{writeStatus:c,writeMessage:u,selectedSpool:i,tagOnReader:y,tagUid:b,deviceOnline:A,canWrite:!!le,isReplace:n==="replace",canUntag:n==="replace"&&!!i&&fX(i),untagging:p,onWrite:te,onUntag:ee,onCancel:ae,onRetry:()=>{d("idle"),m("")},t})})]})]})}function fX(t){return!!(t.tag_uid||t.tray_uuid)}function oat({spool:t,selected:e,showTag:n,onClick:r}){const i=t.rgba?`#${t.rgba.slice(0,6)}`:"#666",s=Math.max(0,t.label_weight-t.weight_used),o=t.label_weight>0?Math.round(s/t.label_weight*100):0;return a.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[a.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:i}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]})}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&a.jsx("span",{children:t.color_name}),a.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&a.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&a.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:a.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]})}function lat({currencySymbol:t,onCreated:e,selectedSpool:n,t:r}){const[i,s]=w.useState("simple"),[o,l]=w.useState("filament"),[c,d]=w.useState(qL),[u,m]=w.useState({}),[p,f]=w.useState(!1),[y,v]=w.useState(1),[b,g]=w.useState(!1),[_,k]=w.useState(null),[P,N]=w.useState(!1),[M,A]=w.useState(!1),[T,C]=w.useState([]),[F,$]=w.useState([]),[I,X]=w.useState([]),[L,te]=w.useState([]),[ae,ee]=w.useState(""),[me,le]=w.useState([]),[ue,K]=w.useState([]),[ne,oe]=w.useState(new Set),[be,_e]=w.useState(new Set);w.useEffect(()=>{le(kle())},[]),w.useEffect(()=>{(async()=>{if(i==="full"){A(!0);try{const fe=await pe.getCloudStatus();if(N(fe.is_authenticated),fe.is_authenticated){const se=await pe.getFilamentPresets();C(se)}}catch{N(!1)}finally{A(!1)}pe.getSpoolCatalog().then(X).catch(()=>{}),pe.getColorCatalog().then(te).catch(()=>{}),pe.getLocalPresets().then(fe=>$(fe.filament)).catch(()=>{});try{const fe=await pe.getPrinters(),se=await Promise.all(fe.map(R=>pe.getPrinterStatus(R.id).catch(()=>null))),U=[];for(let R=0;R<fe.length;R++){const re=fe[R],we=se[R]?.connected??!1;let ye=[];if(we)try{ye=(await pe.getKProfiles(re.id)).profiles.map(ve=>({cali_idx:ve.slot_id,filament_id:ve.filament_id,setting_id:ve.setting_id||"",name:ve.name,k_value:parseFloat(ve.k_value)||0,n_coef:parseFloat(ve.n_coef)||0,extruder_id:ve.extruder_id,nozzle_diameter:ve.nozzle_diameter}))}catch{}U.push({printer:{...re,connected:we},calibrations:ye})}K(U)}catch{}}})()},[i]),w.useEffect(()=>{ue.length>0&&_e(new Set(ue.map(he=>String(he.printer.id))))},[ue]);const B=w.useMemo(()=>Sle(T,new Set,F),[T,F]),Y=w.useMemo(()=>_le(c.slicer_filament,B),[c.slicer_filament,B]),D=w.useMemo(()=>{const he=wle(T,F),fe=L.map(se=>se.manufacturer?.trim()).filter(se=>!!se);return Array.from(new Set([...he,...fe])).sort((se,U)=>se.localeCompare(U))},[T,F,L]),j=w.useMemo(()=>{const he=L.map(fe=>fe.material?.trim()).filter(fe=>!!fe);return Array.from(new Set([...xle,...he])).sort((fe,se)=>fe.localeCompare(se))},[L]),z=w.useMemo(()=>{const he=[];for(const fe of L){const se=fe.manufacturer?.trim(),U=fe.material?.trim();se&&U&&he.push({brand:se,material:U})}for(const fe of T){const se=Jh(fe.name);se.brand&&se.material&&he.push({brand:se.brand,material:se.material})}for(const fe of F){const se=Jh(fe.name),U=fe.filament_vendor?.trim()||se.brand,R=se.material;U&&R&&he.push({brand:U,material:R})}return he},[T,L,F]),W=w.useMemo(()=>{const he=new Map;for(const fe of z){const se=fe.brand.toLowerCase(),U=fe.material.toLowerCase();he.has(se)||he.set(se,new Set),he.get(se).add(U)}return he},[z]),q=w.useMemo(()=>{const he=new Map;for(const fe of z){const se=fe.brand.toLowerCase(),U=fe.material.toLowerCase();he.has(U)||he.set(U,new Set),he.get(U).add(se)}return he},[z]),de=w.useMemo(()=>{if(!c.material)return D;const he=c.material.toLowerCase(),fe=q.get(he);return!fe||fe.size===0?D:D.filter(se=>fe.has(se.toLowerCase()))},[D,c.material,q]),O=w.useMemo(()=>{if(!c.brand)return j;const he=c.brand.toLowerCase(),fe=W.get(he);return!fe||fe.size===0?j:j.filter(se=>fe.has(se.toLowerCase()))},[j,c.brand,W]),G=(he,fe)=>{d(se=>({...se,[he]:fe})),u[he]&&m(se=>({...se,[he]:void 0}))},Q=he=>{le(fe=>Nle(he,fe))},V=async he=>{if(ne.size===0){try{await pe.saveSpoolKProfiles(he,[])}catch{}return}const fe=[];for(const se of ne){const[U,R,re]=se.split(":"),xe=parseInt(U),we=parseInt(R),ye=re==="null"?0:parseInt(re),Ae=ue.find(ve=>ve.printer.id===xe);if(Ae){const ve=Ae.calibrations.find(Te=>Te.cali_idx===we);ve&&fe.push({printer_id:xe,extruder:ye,nozzle_diameter:ve.nozzle_diameter||"0.4",k_value:ve.k_value,name:ve.name||null,cali_idx:ve.cali_idx,setting_id:ve.setting_id||null})}}fe.length>0&&await pe.saveSpoolKProfiles(he,fe)},J=async()=>{k(null);const he=ble(c,i==="simple"?!0:p);if(!he.isValid){m(he.errors),l("filament");return}const fe=Y?.displayName||ae||null,se={material:c.material,subtype:c.subtype||null,brand:c.brand||null,color_name:c.color_name||null,rgba:c.rgba||null,label_weight:c.label_weight,core_weight:c.core_weight,core_weight_catalog_id:c.core_weight_catalog_id,weight_used:c.weight_used,slicer_filament:c.slicer_filament||null,slicer_filament_name:fe,nozzle_temp_min:null,nozzle_temp_max:null,note:c.note||null,cost_per_kg:c.cost_per_kg,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,last_scale_weight:null,last_weighed_at:null};g(!0);try{if(y>1){const U=await pe.bulkCreateSpools(se,y);for(const R of U)await V(R.id);U.length>0&&e(U[0])}else{const U=await pe.createSpool(se);await V(U.id),e(U)}}catch{k(r("spoolbuddy.writeTag.createFailed","Failed to create spool"))}finally{g(!1)}},ie=`#${(c.rgba||"808080FF").slice(0,6)}`;return a.jsxs("div",{className:"p-3 space-y-3 overflow-y-auto h-full",children:[a.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-zinc-200",children:r("spoolbuddy.writeTag.viewMode","View")}),a.jsxs("div",{className:"flex rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("button",{type:"button",onClick:()=>s("simple"),className:`px-3 py-1.5 text-xs font-medium ${i==="simple"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.simpleView","Simple")}),a.jsx("button",{type:"button",onClick:()=>s("full"),className:`px-3 py-1.5 text-xs font-medium ${i==="full"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.fullView","Full")})]})]}),i==="simple"?n?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),a.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),a.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),a.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):a.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.material","Material")}),a.jsx("select",{value:c.material,onChange:he=>G("material",he.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:iat.map(he=>a.jsx("option",{value:he,children:he},he))})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.colorName","Color Name")}),a.jsx("input",{type:"text",value:c.color_name,onChange:he=>G("color_name",he.target.value),placeholder:"Jade White",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.color","Color")}),a.jsx("input",{type:"color",value:ie,onChange:he=>G("rgba",he.target.value.replace("#","").toUpperCase()+"FF"),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.brand","Brand")}),a.jsx("input",{type:"text",value:c.brand,onChange:he=>G("brand",he.target.value),placeholder:"Polymaker",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.weight","Weight (g)")}),a.jsx("input",{type:"number",value:c.label_weight,onChange:he=>G("label_weight",parseInt(he.target.value)||0),min:0,max:1e4,className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green"})]}),a.jsx("button",{onClick:J,disabled:b||!c.material,className:"w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:b?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-zinc-200",children:r("inventory.quickAdd","Quick Add")}),a.jsx("button",{type:"button",onClick:()=>f(he=>!he),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{onClick:()=>l("filament"),className:`flex-1 py-2.5 text-sm font-medium ${o==="filament"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.filamentInfoTab","Filament")}),!p&&a.jsx("button",{onClick:()=>l("pa-profile"),className:`flex-1 py-2.5 text-sm font-medium ${o==="pa-profile"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.paProfileTab","PA Profile")})]}),a.jsx("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3",children:o==="filament"?a.jsxs("div",{className:"space-y-4",children:[a.jsx(Cle,{formData:c,updateField:G,cloudAuthenticated:P,loadingCloudPresets:M,presetInputValue:ae,setPresetInputValue:ee,selectedPresetOption:Y,filamentOptions:B,availableBrands:de,availableMaterials:O,quickAdd:p,quantity:y,onQuantityChange:v,errors:u}),a.jsx(Ple,{formData:c,updateField:G,recentColors:me,onColorUsed:Q,catalogColors:L}),a.jsx(Tle,{formData:c,updateField:G,spoolCatalog:I,currencySymbol:t})]}):a.jsx(Ale,{formData:c,updateField:G,printersWithCalibrations:ue,selectedProfiles:ne,setSelectedProfiles:oe,expandedPrinters:be,setExpandedPrinters:_e})})]}),_&&a.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2",children:_}),i==="full"&&a.jsx("button",{onClick:J,disabled:b,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:b?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")}),i==="full"&&n&&a.jsxs("div",{className:"flex flex-col items-center justify-center p-4 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),a.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),a.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),a.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]})]})}function cat({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:r,tagUid:i,deviceOnline:s,canWrite:o,isReplace:l,canUntag:c,untagging:d,onWrite:u,onUntag:m,onCancel:p,onRetry:f,t:y}){if(t==="success")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),a.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&a.jsxs("p",{className:"text-zinc-400 text-sm",children:[n.brand?`${n.brand} `:"",n.material,n.color_name?` - ${n.color_name}`:""]})]});if(t==="error")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),a.jsx("p",{className:"text-red-400 font-medium",children:e}),a.jsx("button",{onClick:f,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:y("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsxs("div",{className:"relative w-16 h-16",children:[a.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),a.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(qv,{className:"w-8 h-8 text-bambu-green"})})]}),a.jsx("p",{className:"text-bambu-green font-medium",children:y("spoolbuddy.writeTag.writing","Writing tag...")}),a.jsx("p",{className:"text-zinc-500 text-xs",children:e}),a.jsx("button",{onClick:p,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:y("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[a.jsx(qv,{className:"w-12 h-12 text-zinc-600"}),a.jsx("p",{className:"text-zinc-500 text-sm",children:y("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[a.jsx(qv,{className:"w-12 h-12 text-zinc-600"}),a.jsx("p",{className:"text-zinc-400 text-sm",children:y("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const v=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[a.jsx("div",{className:"relative w-16 h-16",children:r?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(qv,{className:"w-8 h-8 text-bambu-green"})})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(qv,{className:"w-8 h-8 text-zinc-500"})})]})}),r?a.jsxs("div",{className:"space-y-1",children:[a.jsx("p",{className:"text-bambu-green text-sm font-medium",children:y("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),i&&a.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:i})]}):a.jsx("p",{className:"text-zinc-400 text-sm",children:y("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),a.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:v}}),a.jsxs("div",{className:"text-left min-w-0",children:[a.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),a.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&a.jsx("p",{className:"text-yellow-500/80 text-xs",children:y("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),a.jsx("button",{onClick:u,disabled:!o,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm",children:l?y("spoolbuddy.writeTag.replaceTag","Replace Tag"):y("spoolbuddy.writeTag.writeTag","Write Tag")}),l&&c&&a.jsx("button",{onClick:m,disabled:d,className:"w-full py-2.5 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary disabled:opacity-40 disabled:cursor-not-allowed text-zinc-200 rounded-lg transition-colors text-sm",children:d?y("spoolbuddy.writeTag.untagging","Removing tag..."):y("spoolbuddy.writeTag.untagSpool","Untag Selected Spool")})]})}function qv({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const dat="spoolbuddy-default-core-weight";function uat(){try{const t=localStorage.getItem(dat);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function mat({spool:t,liveScaleWeight:e,persistedGrossWeight:n,onClose:r,onSyncWeight:i,onAssignToAms:s,className:o}){const{t:l}=Lt(),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(null),{data:y}=et({queryKey:["spool-k-profiles",t.id],queryFn:()=>pe.getSpoolKProfiles(t.id),enabled:!t.k_profiles||t.k_profiles.length===0,staleTime:300*1e3}),v=t.k_profiles&&t.k_profiles.length>0?t.k_profiles:y,b=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",g=t.core_weight&&t.core_weight>0?t.core_weight:uat(),_=e!==null?Math.round(Math.max(0,e)):null,k=p??(n!==void 0?n!==null?Math.round(Math.max(0,n)):null:_),P=Math.round(Math.max(0,(t.label_weight||0)-(t.weight_used||0))),A=_!==null&&_>=10?Math.round(Math.max(0,_-g)):P,T=Math.round(t.label_weight||1e3),C=T>0?Math.min(100,Math.round(A/T*100)):null,F=C!==null?C>50?"#22c55e":C>20?"#eab308":"#ef4444":"#808080",I=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+g,X=_!==null?_-I:null,L=X!==null?Math.abs(X)<=50:null,te=Math.round(I),ae=k??te,ee=t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null?`${t.nozzle_temp_min}-${t.nozzle_temp_max}°C`:null,me=t.slicer_filament_name||t.slicer_filament||null,le=t.note?.trim()||null,ue=v&&v.length>0?Array.from(new Set(v.map(ne=>ne.k_value.toFixed(3)))).join(", "):null,K=async()=>{if(e===null)return;const ne=Math.round(Math.max(0,e));d(!0);try{await wa.updateSpoolWeight(t.id,ne),f(ne),m(!0),i?.(),setTimeout(()=>m(!1),3e3)}catch(oe){console.error("Failed to sync weight:",oe)}finally{d(!1)}};return a.jsxs("div",{className:`flex flex-col items-center space-y-4 max-w-md ${o??""}`,children:[a.jsxs("div",{className:"flex items-start gap-5",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(rA,{color:b,isEmpty:!1,size:100}),C!==null&&a.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:F},children:[C,"%"]})]}),a.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),a.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[A,"g"]}),a.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",T,"g"]})]}),a.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:l("spoolbuddy.spool.remaining","Remaining")}),a.jsx("div",{className:"mt-2 max-w-xs",children:a.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${C??0}%`,backgroundColor:F}})})})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.grossWeight","Gross weight")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[ae,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.coreWeight","Core")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[g,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.spoolSize","Spool size")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[T,"g"]})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.scaleWeight","Scale")}),_!==null?a.jsxs("span",{className:`flex items-center gap-1 font-mono ${L?"text-green-500":"text-yellow-500"}`,children:[_,"g",L?a.jsx(Kr,{className:"w-3.5 h-3.5"}):a.jsxs(a.Fragment,{children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsx("button",{onClick:K,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:l("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:a.jsx(vr,{className:"w-4 h-4"})})]})]}):a.jsx("span",{className:"text-zinc-500",children:"—"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.tagId","Tag")}),a.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]}),ee&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.nozzleTemp","Nozzle")}),a.jsx("span",{className:"font-mono text-zinc-300",children:ee})]}),t.cost_per_kg!=null&&t.cost_per_kg>0&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.costPerKg","Cost/kg")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[t.cost_per_kg.toFixed(2),"/kg"]})]}),ue&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.kProfiles","K-Profile")}),a.jsx("span",{className:"font-mono text-zinc-300 truncate max-w-[220px] text-right",title:ue,children:ue})]}),me&&a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:l("spoolbuddy.inventory.slicerFilament","Slicer Filament")}),a.jsx("p",{className:"text-sm text-zinc-300 whitespace-pre-wrap break-words",children:me})]}),le&&a.jsxs("div",{className:"col-span-2",children:[a.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:l("spoolbuddy.inventory.note","Note")}),a.jsx("p",{className:"text-sm leading-5 text-zinc-300 whitespace-pre-wrap break-words max-h-[3.75rem] overflow-y-auto pr-1",children:le})]})]}),a.jsxs("div",{className:"flex gap-2 justify-center",children:[s&&a.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:l("spoolbuddy.modal.assignToAms","Assign to AMS")}),a.jsx("button",{onClick:K,disabled:e===null||c,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${u?"bg-green-600/20 text-green-400":s?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:c?"...":u?l("spoolbuddy.dashboard.weightSynced","Synced!"):l("spoolbuddy.dashboard.syncWeight","Sync Weight")}),r&&a.jsx("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:l("spoolbuddy.dashboard.close","Close")})]})]})}function hat(t){return t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"}function pat(t){return Math.max(0,t.label_weight-t.weight_used)}function fat(t){return t.label_weight<=0?0:Math.max(0,Math.min(100,(t.label_weight-t.weight_used)/t.label_weight*100))}function gat(t){const e=[t.material];return t.subtype&&e.push(t.subtype),e.join(" ")}function Ile(t){const e=t.ams_id===254||t.ams_id===255,n=!e&&t.ams_id>=128;return uS(t.ams_id,t.tray_id,n,e)}function bat({color:t,size:e=56}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 56 56",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:t}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:t,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}function xat(){const{sbState:t,selectedPrinterId:e}=Zx(),{t:n}=Lt(),[r,i]=w.useState(""),[s,o]=w.useState("all"),[l,c]=w.useState(null),[d,u]=w.useState(!1),{data:m}=et({queryKey:["spoolman-settings"],queryFn:pe.getSpoolmanSettings,staleTime:300*1e3}),{data:p=[],isLoading:f,refetch:y}=et({queryKey:["inventory-spools"],queryFn:()=>pe.getSpools(!1),refetchInterval:3e4}),{data:v=[]}=et({queryKey:["spool-assignments"],queryFn:()=>pe.getAssignments(),refetchInterval:3e4}),b=w.useMemo(()=>{const A={};return v.forEach(T=>{A[T.spool_id]=T}),A},[v]),g=w.useMemo(()=>p.filter(A=>!A.archived_at),[p]),_=w.useMemo(()=>new Set(v.map(A=>A.spool_id)),[v]),k=w.useMemo(()=>g.filter(A=>_.has(A.id)).length,[g,_]),P=w.useMemo(()=>{const A=new Set;return g.forEach(T=>A.add(T.material)),Array.from(A).sort()},[g]),N=w.useMemo(()=>{let A=g;if(s==="in_ams"?A=A.filter(T=>_.has(T.id)):s!=="all"&&(A=A.filter(T=>T.material===s)),r.trim()){const T=r.toLowerCase().trim();A=A.filter(C=>C.material.toLowerCase().includes(T)||C.subtype&&C.subtype.toLowerCase().includes(T)||C.brand&&C.brand.toLowerCase().includes(T)||C.color_name&&C.color_name.toLowerCase().includes(T)||C.note&&C.note.toLowerCase().includes(T))}return[...A].sort((T,C)=>{const F=_.has(T.id)?0:1,$=_.has(C.id)?0:1;return F!==$?F-$:new Date(C.updated_at).getTime()-new Date(T.updated_at).getTime()})},[g,s,r,_]);return m?.spoolman_enabled==="true"&&m?.spoolman_url?a.jsx("div",{className:"h-full flex flex-col",children:a.jsx("iframe",{src:`${m.spoolman_url.replace(/\/+$/,"")}/spool`,className:"flex-1 w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"px-3 pt-3 pb-2 space-y-2.5",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40"}),a.jsx("input",{type:"text",value:r,onChange:A=>i(A.target.value),placeholder:n("spoolbuddy.inventory.searchPlaceholder","Search spools..."),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-white/30 focus:outline-none focus:border-bambu-green"}),r&&a.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/60",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-1.5 overflow-x-auto no-scrollbar",children:[a.jsx(v3,{active:s==="all",onClick:()=>o("all"),label:`${n("spoolbuddy.inventory.all","All")} (${g.length})`,green:!0}),k>0&&a.jsx(v3,{active:s==="in_ams",onClick:()=>o("in_ams"),label:`${n("spoolbuddy.inventory.inAms","In AMS")} (${k})`}),P.map(A=>a.jsx(v3,{active:s===A,onClick:()=>o(s===A?"all":A),label:A},A))]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3",children:f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx("div",{className:"w-8 h-8 border-2 border-bambu-green border-t-transparent rounded-full animate-spin"})}):N.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-white/30",children:[a.jsx(Na,{className:"w-12 h-12 mb-3"}),a.jsx("p",{className:"text-sm",children:r||s!=="all"?n("spoolbuddy.inventory.noResults","No spools match your filters"):n("spoolbuddy.inventory.empty","No spools in inventory")})]}):a.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(130px,1fr))] gap-2",children:N.map(A=>a.jsx(yat,{spool:A,assignment:b[A.id],onClick:()=>c(A.id)},A.id))})}),l!=null&&(()=>{const A=p.find(C=>C.id===l);if(!A)return null;const T=()=>{c(null),u(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(vat,{spool:A,assignment:b[A.id],sbState:t,onSyncWeight:()=>{y()},onAssignToAms:()=>u(!0),onClose:T}),a.jsx(Ole,{isOpen:d,onClose:()=>u(!1),spool:A,printerId:e})]})})()]})}function v3({active:t,onClick:e,label:n,green:r}){return a.jsx("button",{onClick:e,className:`px-4 py-1.5 rounded-full text-sm font-medium border whitespace-nowrap shrink-0 transition-colors ${t?r?"bg-bambu-green/20 text-bambu-green border-bambu-green/50":"bg-white/10 text-white border-white/20":"bg-transparent text-white/40 border-bambu-dark-tertiary hover:text-white/60"}`,children:n})}function yat({spool:t,assignment:e,onClick:n}){const r=hat(t),i=fat(t),s=pat(t),o=FT(t.color_name,t.rgba);return a.jsxs("button",{onClick:n,className:"bg-bambu-dark-secondary rounded-xl p-3 flex flex-col items-center text-center gap-1.5 border border-transparent hover:border-bambu-green/50 transition-colors",children:[a.jsx(bat,{color:r,size:56}),a.jsx("p",{className:"text-xs font-semibold text-white leading-tight truncate w-full",children:gat(t)}),a.jsxs("div",{className:"flex items-center gap-1 min-w-0 max-w-full",children:[a.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 border border-white/10",style:{backgroundColor:r}}),a.jsx("span",{className:"text-[11px] text-white/50 truncate",children:o||"-"})]}),a.jsxs("div",{className:"w-full space-y-0.5",children:[a.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${i>50?"bg-bambu-green":i>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(i,100)}%`}})}),a.jsxs("p",{className:"text-[11px] text-white/40",children:[Math.round(s),"g (",Math.round(i),"%)"]})]}),e&&a.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-bambu-green/20 text-bambu-green",children:Ile(e)})]})}function vat({spool:t,assignment:e,sbState:n,onSyncWeight:r,onAssignToAms:i,onClose:s}){const l=n.deviceOnline&&n.weight!==null?Math.round(n.weight):null,c=t.last_scale_weight!=null?Math.round(t.last_scale_weight):null;return a.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4",onClick:s,children:a.jsx("div",{className:"w-full max-w-md bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-2xl p-4 overflow-y-auto max-h-[90vh]",onClick:d=>d.stopPropagation(),children:a.jsxs("div",{className:"space-y-3",children:[e&&a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-bambu-green/20 text-bambu-green",children:Ile(e)}),e.printer_name&&a.jsx("span",{className:"text-xs text-zinc-400",children:e.printer_name})]}),a.jsx("div",{className:"flex justify-center",children:a.jsx(mat,{spool:t,liveScaleWeight:l,persistedGrossWeight:c,onSyncWeight:r,onAssignToAms:i,onClose:s,className:"max-w-md"})})]})})})}class wat extends w.Component{state={error:null,errorInfo:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,n){this.setState({errorInfo:n}),console.error("React crash:",e,n)}render(){return this.state.error?a.jsxs("div",{style:{padding:24,color:"#ef4444",backgroundColor:"#18181b",minHeight:"100vh",fontFamily:"monospace"},children:[a.jsx("h1",{style:{fontSize:20,marginBottom:12},children:"UI Crash"}),a.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:14},children:this.state.error.message}),a.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:12,color:"#a1a1aa",marginTop:12},children:this.state.error.stack}),a.jsx("button",{onClick:()=>{this.setState({error:null,errorInfo:null})},style:{marginTop:16,padding:"8px 16px",backgroundColor:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:"Retry"})]}):this.props.children}}const Sat=new Ehe({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function _at(){return srt(),null}function gX({children:t}){return irt(),a.jsx(a.Fragment,{children:t})}function bX({children:t}){const{authEnabled:e,loading:n,user:r}=_r();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?a.jsx(gx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function w3({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:i}=_r();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?i?a.jsx(a.Fragment,{children:t}):a.jsx(gx,{to:"/",replace:!0}):a.jsx(gx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function kat({children:t}){const{authEnabled:e,loading:n}=_r();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?a.jsx(gx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function Nat(){return a.jsx(wat,{children:a.jsx(Exe,{children:a.jsx(Bxe,{children:a.jsx(Dhe,{client:Sat,children:a.jsxs(zxe,{children:[a.jsx(_at,{}),a.jsx(Zme,{children:a.jsxs(Pme,{children:[a.jsx(Mr,{path:"/setup",element:a.jsx(kat,{children:a.jsx(rrt,{})})}),a.jsx(Mr,{path:"/login",element:a.jsx(nrt,{})}),a.jsx(Mr,{path:"/camera/:printerId",element:a.jsx(knt,{})}),a.jsx(Mr,{path:"/overlay/:printerId",element:a.jsx(Ant,{})}),a.jsxs(Mr,{element:a.jsx(bX,{children:a.jsx(gX,{children:a.jsx(wrt,{})})}),children:[a.jsx(Mr,{path:"spoolbuddy",element:a.jsx(Brt,{})}),a.jsx(Mr,{path:"spoolbuddy/ams",element:a.jsx($rt,{})}),a.jsx(Mr,{path:"spoolbuddy/write-tag",element:a.jsx(sat,{})}),a.jsx(Mr,{path:"spoolbuddy/inventory",element:a.jsx(xat,{})}),a.jsx(Mr,{path:"spoolbuddy/settings",element:a.jsx(nat,{})}),a.jsx(Mr,{path:"spoolbuddy/calibration",element:a.jsx(aat,{})})]}),a.jsxs(Mr,{element:a.jsx(bX,{children:a.jsx(gX,{children:a.jsx(tye,{})})}),children:[a.jsx(Mr,{index:!0,element:a.jsx(rGe,{})}),a.jsx(Mr,{path:"archives",element:a.jsx(YZe,{})}),a.jsx(Mr,{path:"queue",element:a.jsx(Vet,{})}),a.jsx(Mr,{path:"stats",element:a.jsx(ctt,{})}),a.jsx(Mr,{path:"profiles",element:a.jsx(tnt,{})}),a.jsx(Mr,{path:"maintenance",element:a.jsx(snt,{})}),a.jsx(Mr,{path:"projects",element:a.jsx(lnt,{})}),a.jsx(Mr,{path:"projects/:id",element:a.jsx(hnt,{})}),a.jsx(Mr,{path:"inventory",element:a.jsx(Knt,{})}),a.jsx(Mr,{path:"files",element:a.jsx(vnt,{})}),a.jsx(Mr,{path:"settings",element:a.jsx(w3,{children:a.jsx(Btt,{})})}),a.jsx(Mr,{path:"groups/new",element:a.jsx(w3,{children:a.jsx(rX,{})})}),a.jsx(Mr,{path:"groups/:id/edit",element:a.jsx(w3,{children:a.jsx(rX,{})})}),a.jsx(Mr,{path:"users",element:a.jsx(gx,{to:"/settings?tab=users",replace:!0})}),a.jsx(Mr,{path:"groups",element:a.jsx(gx,{to:"/settings?tab=users",replace:!0})}),a.jsx(Mr,{path:"system",element:a.jsx(trt,{})}),a.jsx(Mr,{path:"notifications",element:a.jsx(art,{})}),a.jsx(Mr,{path:"external/:id",element:a.jsx(Mnt,{})})]})]})})]})})})})})}Sde.createRoot(document.getElementById("root")).render(a.jsx(w.StrictMode,{children:a.jsx(Nat,{})}));