opus-submitter/polylan_submitter/static_source/vite/assets/opus_magnum-CBb_5LJ1.js
2026-05-15 14:51:05 +02:00

6 lines
76 KiB
JavaScript

import{e as Ut,r as I,m as Bt,t as Vt,c as ne,i as me,a as nt,b as ds,d as fs,h as hs,f as vs,g as Gt,o as Wt,w as $e,n as Se,j as ms,k as pe,l as h,p as f,q as oe,s as e,u as R,v as y,x as A,F as Q,y as ee,z as T,A as Xe,B as ps,C as ce,D as Ht,E as ve,G as ze,H as gs,I as ot,J as dt,K as Jt,L as bs,M as ke,N as ys,O as _s}from"./style-CrNkWMsg.js";import{_ as ft}from"./RankBadge.vue_vue_type_script_setup_true_lang-CzaIkt15.js";/*!
* pinia v3.0.3
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/let Kt;const Ce=n=>Kt=n,Yt=Symbol();function et(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var we;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(we||(we={}));function ws(){const n=Ut(!0),a=n.run(()=>I({}));let s=[],t=[];const o=Bt({install(r){Ce(o),o._a=r,r.provide(Yt,o),r.config.globalProperties.$pinia=o,t.forEach(u=>s.push(u)),t=[]},use(r){return this._a?s.push(r):t.push(r),this},_p:s,_a:null,_e:n,_s:new Map,state:a});return o}const Zt=()=>{};function ht(n,a,s,t=Zt){n.push(a);const o=()=>{const r=n.indexOf(a);r>-1&&(n.splice(r,1),t())};return!s&&Gt()&&Wt(o),o}function he(n,...a){n.slice().forEach(s=>{s(...a)})}const xs=n=>n(),vt=Symbol(),Re=Symbol();function tt(n,a){n instanceof Map&&a instanceof Map?a.forEach((s,t)=>n.set(t,s)):n instanceof Set&&a instanceof Set&&a.forEach(n.add,n);for(const s in a){if(!a.hasOwnProperty(s))continue;const t=a[s],o=n[s];et(o)&&et(t)&&n.hasOwnProperty(s)&&!me(t)&&!nt(t)?n[s]=tt(o,t):n[s]=t}return n}const zs=Symbol();function ks(n){return!et(n)||!Object.prototype.hasOwnProperty.call(n,zs)}const{assign:de}=Object;function Ss(n){return!!(me(n)&&n.effect)}function $s(n,a,s,t){const{state:o,actions:r,getters:u}=a,d=s.state.value[n];let g;function w(){d||(s.state.value[n]=o?o():{});const x=ms(s.state.value[n]);return de(x,r,Object.keys(u||{}).reduce((P,$)=>(P[$]=Bt(ne(()=>{Ce(s);const l=s._s.get(n);return u[$].call(l,l)})),P),{}))}return g=Qt(n,w,a,s,t,!0),g}function Qt(n,a,s={},t,o,r){let u;const d=de({actions:{}},s),g={deep:!0};let w,x,P=[],$=[],l;const p=t.state.value[n];!r&&!p&&(t.state.value[n]={}),I({});let z;function b(D){let M;w=x=!1,typeof D=="function"?(D(t.state.value[n]),M={type:we.patchFunction,storeId:n,events:l}):(tt(t.state.value[n],D),M={type:we.patchObject,payload:D,storeId:n,events:l});const F=z=Symbol();Se().then(()=>{z===F&&(w=!0)}),x=!0,he(P,M,t.state.value[n])}const i=r?function(){const{state:M}=s,F=M?M():{};this.$patch(H=>{de(H,F)})}:Zt;function c(){u.stop(),P=[],$=[],t._s.delete(n)}const v=(D,M="")=>{if(vt in D)return D[Re]=M,D;const F=function(){Ce(t);const H=Array.from(arguments),ae=[],ue=[];function ge(U){ae.push(U)}function X(U){ue.push(U)}he($,{args:H,name:F[Re],store:S,after:ge,onError:X});let se;try{se=D.apply(this&&this.$id===n?this:S,H)}catch(U){throw he(ue,U),U}return se instanceof Promise?se.then(U=>(he(ae,U),U)).catch(U=>(he(ue,U),Promise.reject(U))):(he(ae,se),se)};return F[vt]=!0,F[Re]=M,F},C={_p:t,$id:n,$onAction:ht.bind(null,$),$patch:b,$reset:i,$subscribe(D,M={}){const F=ht(P,D,M.detached,()=>H()),H=u.run(()=>$e(()=>t.state.value[n],ae=>{(M.flush==="sync"?x:w)&&D({storeId:n,type:we.direct,events:l},ae)},de({},g,M)));return F},$dispose:c},S=vs(C);t._s.set(n,S);const te=(t._a&&t._a.runWithContext||xs)(()=>t._e.run(()=>(u=Ut()).run(()=>a({action:v}))));for(const D in te){const M=te[D];if(me(M)&&!Ss(M)||nt(M))r||(p&&ks(M)&&(me(M)?M.value=p[D]:tt(M,p[D])),t.state.value[n][D]=M);else if(typeof M=="function"){const F=v(M,D);te[D]=F,d.actions[D]=M}}return de(S,te),de(Vt(S),te),Object.defineProperty(S,"$state",{get:()=>t.state.value[n],set:D=>{b(M=>{de(M,D)})}}),t._p.forEach(D=>{de(S,u.run(()=>D({store:S,app:t._a,pinia:t,options:d})))}),p&&r&&s.hydrate&&s.hydrate(S.$state,p),w=!0,x=!0,S}/*! #__NO_SIDE_EFFECTS__ */function at(n,a,s){let t;const o=typeof a=="function";t=o?s:a;function r(u,d){const g=hs();return u=u||(g?fs(Yt,null):null),u&&Ce(u),u=Kt,u._s.has(n)||(o?Qt(n,a,t,u):$s(n,t,u)),u._s.get(n)}return r.$id=n,r}function rt(n){const a=Vt(n),s={};for(const t in a){const o=a[t];o.effect?s[t]=ne({get:()=>n[t],set(r){n[t]=r}}):(me(o)||nt(o))&&(s[t]=ds(n,t))}return s}const mt="/api";class Cs{async request(a,s={}){try{const t=await fetch(`${mt}${a}`,{headers:{"Content-Type":"application/json",...s.headers},...s}),o=await t.json();return t.ok?{data:o,status:t.status}:{error:o.detail||`HTTP ${t.status}`,status:t.status}}catch(t){return{error:t instanceof Error?t.message:"Network error",status:0}}}async uploadRequest(a,s){try{const t=await fetch(`${mt}${a}`,{method:"POST",body:s}),o=await t.json();return t.ok?{data:o,status:t.status}:{error:o.detail||`HTTP ${t.status}`,status:t.status}}catch(t){return{error:t instanceof Error?t.message:"Network error",status:0}}}async getPuzzles(){return this.request("/submissions/puzzles")}async getSubmissions(a=20,s=0){return this.request(`/submissions/submissions?limit=${a}&offset=${s}`)}async getSubmission(a){return this.request(`/submissions/submissions/${a}`)}async createSubmission(a,s){const t=new FormData;return t.append("data",JSON.stringify(a)),s.forEach(o=>{t.append("files",o)}),this.uploadRequest("/submissions/submissions",t)}async validateResponse(a,s){return this.request(`/submissions/responses/${a}/validate`,{method:"PUT",body:JSON.stringify(s)})}async autoValidateResponses(a){return this.request(`/submissions/responses/${a}/validate/auto`,{method:"PUT"})}async getResponsesNeedingValidation(){return this.request("/submissions/responses/needs-validation")}async validateSubmission(a){return this.request(`/submissions/submissions/${a}/validate`,{method:"POST"})}async deleteSubmission(a){return this.request(`/submissions/submissions/${a}`,{method:"DELETE"})}async getStats(){return this.request("/submissions/stats")}async healthCheck(){return this.request("/health")}async getUserInfo(){return this.request("/user")}}const re=new Cs,Ps={async loadPuzzles(){const n=await re.getPuzzles();return n.error?(console.error("Failed to load puzzles:",n.error),[]):n.data||[]},findPuzzleByName(n,a){if(!a)return null;let s=n.find(t=>t.title.toLowerCase()===a.toLowerCase());return s||(s=n.find(t=>t.title.toLowerCase().includes(a.toLowerCase())||a.toLowerCase().includes(t.title.toLowerCase()))),s||null}},pt={async createFromFiles(n,a,s,t){const o=n.map(u=>{const d=Ps.findPuzzleByName(a,u.ocrData?.puzzle||"");if(d)return{puzzle_id:d.id,puzzle_name:u.ocrData?.puzzle||"",cost:u.ocrData?.cost,cycles:u.ocrData?.cycles,area:u.ocrData?.area,needs_manual_validation:(u.ocrData?.confidence.overall??0)<=.8,ocr_confidence_cost:u.ocrData?.confidence?.cost||0,ocr_confidence_cycles:u.ocrData?.confidence?.cycles||0,ocr_confidence_area:u.ocrData?.confidence?.area||0}}).filter(u=>u!==void 0),r=n.map(u=>u.file);return re.createSubmission({notes:s,manual_validation_requested:t,responses:o},r)},async loadSubmissions(n=20,a=0){const s=await re.getSubmissions(n,a);return s.error?(console.error("Failed to load submissions:",s.error),[]):s.data?.items||[]}},Xt={getErrorMessage(n){return typeof n=="string"?n:n instanceof Error?n.message:typeof n=="object"&&n!==null&&"detail"in n?String(n.detail):"An unknown error occurred"},isNetworkError(n){return typeof n=="string"&&n.includes("Network")},isValidationError(n){return n===400},isAuthError(n){return n===401||n===403}},Pe=at("puzzles",()=>{const n=I([]),a=I(!1),s=I(""),t=ne(()=>n.value.map(d=>d.title)),o=ne(()=>d=>{if(!d)return null;const g=n.value.find(x=>x.title.toLowerCase()===d.toLowerCase());return g||n.value.find(x=>x.title.toLowerCase().includes(d.toLowerCase())||d.toLowerCase().includes(x.title.toLowerCase()))||null}),r=async()=>{if(!(n.value.length>0))try{a.value=!0,s.value="";const d=await re.getPuzzles();if(d.error){s.value=d.error,console.error("Failed to load puzzles:",d.error);return}d.data&&(n.value=d.data)}catch(d){s.value="Failed to load puzzles",console.error("Error loading puzzles:",d)}finally{a.value=!1}};return{puzzles:n,isLoading:a,error:s,puzzleNames:t,findPuzzleByName:o,loadPuzzles:r,refreshPuzzles:async()=>{n.value=[],await r()}}}),lt=at("submissions",()=>{const n=I([]),a=I(!1),s=I(""),t=I(!1),o=Pe(),{puzzles:r}=rt(o),u=async($=20,l=0)=>{try{a.value=!0,s.value="";const p=await pt.loadSubmissions($,l);l===0?n.value=p:n.value.push(...p)}catch(p){s.value="Failed to load submissions",console.error("Error loading submissions:",p)}finally{a.value=!1}},d=async($,l,p)=>{try{a.value=!0,s.value="";const z=await pt.createFromFiles($,r.value,l,p);if(z.error)throw s.value=z.error,new Error(z.error);return z.data?(n.value.unshift(z.data),z.data):void 0}catch(z){throw s.value=z instanceof Error?z.message:"Failed to create submission",z}finally{a.value=!1}},g=()=>{t.value=!0},w=()=>{t.value=!1};return{submissions:n,isLoading:a,error:s,isSubmissionModalOpen:t,loadSubmissions:u,createSubmission:d,openSubmissionModal:g,closeSubmissionModal:w,refreshSubmissions:async()=>{n.value=[],await u()},handleSubmission:async $=>{try{a.value=!0,s.value="";const l=await d($.files,$.notes,$.manualValidationRequested);if(l){const p=l.responses.map(z=>z.puzzle_name).join(", ");alert(`Solutions submitted successfully for puzzles: ${p}`)}else alert("Submission created successfully!");w()}catch(l){const p=Xt.getErrorMessage(l);s.value=p,alert(`Submission failed: ${p}`),console.error("Submission error:",l)}finally{a.value=!1}}}}),Ls={class:"card-body"},Rs={class:"flex items-start justify-between"},Es={class:"flex-1"},Os={class:"text-sm text-base-content/70 mb-2"},Ms={class:"flex items-center gap-2 mb-3"},Ns={class:"badge badge-primary badge-sm"},As={class:"badge badge-ghost badge-sm"},Ds={key:0,class:"text-sm text-base-content/80 mb-4"},js={key:1,class:"bg-base-200 p-3 rounded-lg mb-4"},Is={class:"grid grid-cols-3 gap-2"},Ts={class:"text-center"},qs={class:"font-bold text-primary"},Fs={class:"text-center"},Us={class:"font-bold text-primary"},Bs={class:"text-center"},Vs={class:"font-bold text-primary"},Gs={key:2,class:"flex flex-wrap gap-1 mb-4"},Ws={key:0,class:"badge badge-outline badge-xs"},Hs={class:"flex flex-col items-end gap-2"},Js={class:"tooltip","data-tip":"View on Steam Workshop"},Ks=["href"],Ys={key:0,class:"mt-1"},Zs={class:"divider"},Qs={class:"text-sm font-medium"},Xs={class:"table table-xs"},en={key:0,class:"badge badge-success badge-xs"},tn={key:1,class:"text-base-content/50"},sn={key:0,class:"badge badge-info badge-xs"},nn={key:1,class:"text-base-content/50"},on={key:0,class:"badge badge-warning badge-xs"},an={key:1,class:"text-base-content/50"},rn={class:"flex items-center gap-1"},ln={class:"badge badge-ghost badge-xs"},cn=["data-tip"],un={key:1,class:"tooltip","data-tip":"Needs manual validation"},dn=pe({__name:"PuzzleCard",props:{puzzle:{},responses:{}},setup(n){const{openSubmissionModal:a}=lt();return(s,t)=>(f(),h("div",{class:oe(["card bg-base-100 shadow-lg hover:shadow-2xl transition-shadow duration-300",n.responses?.length==0?"shadow-red-900":"shadow-primary-300"])},[e("div",Ls,[e("div",Rs,[e("div",Es,[e("h3",{class:oe(["card-title text-lg font-bold",n.responses?.length==0?"text-error":"text-primary"])},y(n.puzzle.title),3),e("p",Os," by "+y(n.puzzle.author_name),1),e("div",Ms,[e("div",Ns,y(n.puzzle.steam_item_id),1),e("div",As,"ID: "+y(n.puzzle.id),1)]),n.puzzle.description?(f(),h("p",Ds,y(n.puzzle.description),1)):R("",!0),n.puzzle.points_factor?(f(),h("div",js,[t[7]||(t[7]=e("p",{class:"text-xs text-base-content/70 font-semibold mb-2"},"Points Coefficients",-1)),e("div",Is,[e("div",Ts,[e("span",qs,[t[1]||(t[1]=e("small",null,"x",-1)),A(y(n.puzzle.points_factor.cost),1)]),t[2]||(t[2]=e("p",{class:"text-xs text-base-content/70"},"Cost",-1))]),e("div",Fs,[e("span",Us,[t[3]||(t[3]=e("small",null,"x",-1)),A(y(n.puzzle.points_factor.cycles),1)]),t[4]||(t[4]=e("p",{class:"text-xs text-base-content/70"},"Cycles",-1))]),e("div",Bs,[e("span",Vs,[t[5]||(t[5]=e("small",null,"x",-1)),A(y(n.puzzle.points_factor.area),1)]),t[6]||(t[6]=e("p",{class:"text-xs text-base-content/70"},"Area",-1))])])])):R("",!0),n.puzzle.tags&&n.puzzle.tags.length>0?(f(),h("div",Gs,[(f(!0),h(Q,null,ee(n.puzzle.tags.slice(0,3),o=>(f(),h("span",{key:o,class:"badge badge-outline badge-xs"},y(o),1))),128)),n.puzzle.tags.length>3?(f(),h("span",Ws," +"+y(n.puzzle.tags.length-3)+" more ",1)):R("",!0)])):R("",!0)]),e("div",Hs,[e("div",Js,[e("a",{href:`https://steamcommunity.com/workshop/filedetails/?id=${n.puzzle.steam_item_id}`,target:"_blank",class:"btn btn-ghost btn-sm btn-square"},[...t[8]||(t[8]=[e("i",{class:"mdi mdi-steam text-lg"},null,-1)])],8,Ks)])])]),n.responses&&n.responses.length>0?(f(),h("div",Ys,[e("div",Zs,[e("span",Qs,"Solutions ("+y(n.responses.length)+")",1)]),e("div",null,[e("table",Xs,[t[11]||(t[11]=e("thead",null,[e("tr",null,[e("th",null,"Cost"),e("th",null,"Cycles"),e("th",null,"Area"),e("th",null,"Files")])],-1)),e("tbody",null,[(f(!0),h(Q,null,ee(n.responses,o=>(f(),h("tr",{key:o.id,class:"hover"},[e("td",null,[o.final_cost||o.cost?(f(),h("span",en,y(o.final_cost||o.cost),1)):(f(),h("span",tn,"-"))]),e("td",null,[o.final_cycles||o.cycles?(f(),h("span",sn,y(o.final_cycles||o.cycles),1)):(f(),h("span",nn,"-"))]),e("td",null,[o.final_area||o.area?(f(),h("span",on,y(o.final_area||o.area),1)):(f(),h("span",an,"-"))]),e("td",null,[e("div",rn,[e("span",ln,y(o.files?.length||0),1),o.files?.length?(f(),h("div",{key:0,class:"tooltip","data-tip":o.files.map(r=>r.original_filename||r.file?.name).join(", ")},[...t[9]||(t[9]=[e("i",{class:"mdi mdi-information-outline text-xs"},null,-1)])],8,cn)):R("",!0),o.needs_manual_validation?(f(),h("div",un,[...t[10]||(t[10]=[e("i",{class:"mdi mdi-alert-circle text-xs text-warning"},null,-1)])])):R("",!0)])])]))),128))])])])])):(f(),h("div",{key:1,class:"mt-6 text-center py-4 border-2 border-dashed border-base-300 rounded-lg hover:border-primary transition-colors duration-300 cursor-pointer",onClick:t[0]||(t[0]=(...o)=>T(a)&&T(a)(...o))},[...t[12]||(t[12]=[e("i",{class:"mdi mdi-upload text-2xl text-base-content/40"},null,-1),e("p",{class:"text-sm text-base-content/60 mt-2"},"No solutions yet",-1),e("p",{class:"text-xs text-base-content/40"}," Upload solutions using the submit button ",-1)])]))])],2))}});var Ee={exports:{}},gt;function fn(){return gt||(gt=1,(function(n){var a=(function(s){var t=Object.prototype,o=t.hasOwnProperty,r=Object.defineProperty||function(_,m,k){_[m]=k.value},u,d=typeof Symbol=="function"?Symbol:{},g=d.iterator||"@@iterator",w=d.asyncIterator||"@@asyncIterator",x=d.toStringTag||"@@toStringTag";function P(_,m,k){return Object.defineProperty(_,m,{value:k,enumerable:!0,configurable:!0,writable:!0}),_[m]}try{P({},"")}catch{P=function(m,k,E){return m[k]=E}}function $(_,m,k,E){var L=m&&m.prototype instanceof v?m:v,j=Object.create(L.prototype),W=new se(E||[]);return r(j,"_invoke",{value:ae(_,k,W)}),j}s.wrap=$;function l(_,m,k){try{return{type:"normal",arg:_.call(m,k)}}catch(E){return{type:"throw",arg:E}}}var p="suspendedStart",z="suspendedYield",b="executing",i="completed",c={};function v(){}function C(){}function S(){}var q={};P(q,g,function(){return this});var te=Object.getPrototypeOf,D=te&&te(te(U([])));D&&D!==t&&o.call(D,g)&&(q=D);var M=S.prototype=v.prototype=Object.create(q);C.prototype=S,r(M,"constructor",{value:S,configurable:!0}),r(S,"constructor",{value:C,configurable:!0}),C.displayName=P(S,x,"GeneratorFunction");function F(_){["next","throw","return"].forEach(function(m){P(_,m,function(k){return this._invoke(m,k)})})}s.isGeneratorFunction=function(_){var m=typeof _=="function"&&_.constructor;return m?m===C||(m.displayName||m.name)==="GeneratorFunction":!1},s.mark=function(_){return Object.setPrototypeOf?Object.setPrototypeOf(_,S):(_.__proto__=S,P(_,x,"GeneratorFunction")),_.prototype=Object.create(M),_},s.awrap=function(_){return{__await:_}};function H(_,m){function k(j,W,V,Y){var B=l(_[j],_,W);if(B.type==="throw")Y(B.arg);else{var be=B.arg,fe=be.value;return fe&&typeof fe=="object"&&o.call(fe,"__await")?m.resolve(fe.__await).then(function(le){k("next",le,V,Y)},function(le){k("throw",le,V,Y)}):m.resolve(fe).then(function(le){be.value=le,V(be)},function(le){return k("throw",le,V,Y)})}}var E;function L(j,W){function V(){return new m(function(Y,B){k(j,W,Y,B)})}return E=E?E.then(V,V):V()}r(this,"_invoke",{value:L})}F(H.prototype),P(H.prototype,w,function(){return this}),s.AsyncIterator=H,s.async=function(_,m,k,E,L){L===void 0&&(L=Promise);var j=new H($(_,m,k,E),L);return s.isGeneratorFunction(m)?j:j.next().then(function(W){return W.done?W.value:j.next()})};function ae(_,m,k){var E=p;return function(j,W){if(E===b)throw new Error("Generator is already running");if(E===i){if(j==="throw")throw W;return K()}for(k.method=j,k.arg=W;;){var V=k.delegate;if(V){var Y=ue(V,k);if(Y){if(Y===c)continue;return Y}}if(k.method==="next")k.sent=k._sent=k.arg;else if(k.method==="throw"){if(E===p)throw E=i,k.arg;k.dispatchException(k.arg)}else k.method==="return"&&k.abrupt("return",k.arg);E=b;var B=l(_,m,k);if(B.type==="normal"){if(E=k.done?i:z,B.arg===c)continue;return{value:B.arg,done:k.done}}else B.type==="throw"&&(E=i,k.method="throw",k.arg=B.arg)}}}function ue(_,m){var k=m.method,E=_.iterator[k];if(E===u)return m.delegate=null,k==="throw"&&_.iterator.return&&(m.method="return",m.arg=u,ue(_,m),m.method==="throw")||k!=="return"&&(m.method="throw",m.arg=new TypeError("The iterator does not provide a '"+k+"' method")),c;var L=l(E,_.iterator,m.arg);if(L.type==="throw")return m.method="throw",m.arg=L.arg,m.delegate=null,c;var j=L.arg;if(!j)return m.method="throw",m.arg=new TypeError("iterator result is not an object"),m.delegate=null,c;if(j.done)m[_.resultName]=j.value,m.next=_.nextLoc,m.method!=="return"&&(m.method="next",m.arg=u);else return j;return m.delegate=null,c}F(M),P(M,x,"Generator"),P(M,g,function(){return this}),P(M,"toString",function(){return"[object Generator]"});function ge(_){var m={tryLoc:_[0]};1 in _&&(m.catchLoc=_[1]),2 in _&&(m.finallyLoc=_[2],m.afterLoc=_[3]),this.tryEntries.push(m)}function X(_){var m=_.completion||{};m.type="normal",delete m.arg,_.completion=m}function se(_){this.tryEntries=[{tryLoc:"root"}],_.forEach(ge,this),this.reset(!0)}s.keys=function(_){var m=Object(_),k=[];for(var E in m)k.push(E);return k.reverse(),function L(){for(;k.length;){var j=k.pop();if(j in m)return L.value=j,L.done=!1,L}return L.done=!0,L}};function U(_){if(_){var m=_[g];if(m)return m.call(_);if(typeof _.next=="function")return _;if(!isNaN(_.length)){var k=-1,E=function L(){for(;++k<_.length;)if(o.call(_,k))return L.value=_[k],L.done=!1,L;return L.value=u,L.done=!0,L};return E.next=E}}return{next:K}}s.values=U;function K(){return{value:u,done:!0}}return se.prototype={constructor:se,reset:function(_){if(this.prev=0,this.next=0,this.sent=this._sent=u,this.done=!1,this.delegate=null,this.method="next",this.arg=u,this.tryEntries.forEach(X),!_)for(var m in this)m.charAt(0)==="t"&&o.call(this,m)&&!isNaN(+m.slice(1))&&(this[m]=u)},stop:function(){this.done=!0;var _=this.tryEntries[0],m=_.completion;if(m.type==="throw")throw m.arg;return this.rval},dispatchException:function(_){if(this.done)throw _;var m=this;function k(Y,B){return j.type="throw",j.arg=_,m.next=Y,B&&(m.method="next",m.arg=u),!!B}for(var E=this.tryEntries.length-1;E>=0;--E){var L=this.tryEntries[E],j=L.completion;if(L.tryLoc==="root")return k("end");if(L.tryLoc<=this.prev){var W=o.call(L,"catchLoc"),V=o.call(L,"finallyLoc");if(W&&V){if(this.prev<L.catchLoc)return k(L.catchLoc,!0);if(this.prev<L.finallyLoc)return k(L.finallyLoc)}else if(W){if(this.prev<L.catchLoc)return k(L.catchLoc,!0)}else if(V){if(this.prev<L.finallyLoc)return k(L.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(_,m){for(var k=this.tryEntries.length-1;k>=0;--k){var E=this.tryEntries[k];if(E.tryLoc<=this.prev&&o.call(E,"finallyLoc")&&this.prev<E.finallyLoc){var L=E;break}}L&&(_==="break"||_==="continue")&&L.tryLoc<=m&&m<=L.finallyLoc&&(L=null);var j=L?L.completion:{};return j.type=_,j.arg=m,L?(this.method="next",this.next=L.finallyLoc,c):this.complete(j)},complete:function(_,m){if(_.type==="throw")throw _.arg;return _.type==="break"||_.type==="continue"?this.next=_.arg:_.type==="return"?(this.rval=this.arg=_.arg,this.method="return",this.next="end"):_.type==="normal"&&m&&(this.next=m),c},finish:function(_){for(var m=this.tryEntries.length-1;m>=0;--m){var k=this.tryEntries[m];if(k.finallyLoc===_)return this.complete(k.completion,k.afterLoc),X(k),c}},catch:function(_){for(var m=this.tryEntries.length-1;m>=0;--m){var k=this.tryEntries[m];if(k.tryLoc===_){var E=k.completion;if(E.type==="throw"){var L=E.arg;X(k)}return L}}throw new Error("illegal catch attempt")},delegateYield:function(_,m,k){return this.delegate={iterator:U(_),resultName:m,nextLoc:k},this.method==="next"&&(this.arg=u),c}},s})(n.exports);try{regeneratorRuntime=a}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=a:Function("r","regeneratorRuntime = r")(a)}})(Ee)),Ee.exports}var Oe,bt;function it(){return bt||(bt=1,Oe=(n,a)=>`${n}-${a}-${Math.random().toString(16).slice(3,8)}`),Oe}var Me,yt;function es(){if(yt)return Me;yt=1;const n=it();let a=0;return Me=({id:s,action:t,payload:o={}})=>{let r=s;return typeof r>"u"&&(r=n("Job",a),a+=1),{id:r,action:t,payload:o}},Me}var ye={},_t;function ct(){if(_t)return ye;_t=1;let n=!1;return ye.logging=n,ye.setLogging=a=>{n=a},ye.log=(...a)=>n?console.log.apply(this,a):null,ye}var Ne,wt;function hn(){if(wt)return Ne;wt=1;const n=es(),{log:a}=ct(),s=it();let t=0;return Ne=()=>{const o=s("Scheduler",t),r={},u={};let d=[];t+=1;const g=()=>d.length,w=()=>Object.keys(r).length,x=()=>{if(d.length!==0){const z=Object.keys(r);for(let b=0;b<z.length;b+=1)if(typeof u[z[b]]>"u"){d[0](r[z[b]]);break}}},P=(z,b)=>new Promise((i,c)=>{const v=n({action:z,payload:b});d.push(async C=>{d.shift(),u[C.id]=v;try{i(await C[z].apply(this,[...b,v.id]))}catch(S){c(S)}finally{delete u[C.id],x()}}),a(`[${o}]: Add ${v.id} to JobQueue`),a(`[${o}]: JobQueue length=${d.length}`),x()});return{addWorker:z=>(r[z.id]=z,a(`[${o}]: Add ${z.id}`),a(`[${o}]: Number of workers=${w()}`),x(),z.id),addJob:async(z,...b)=>{if(w()===0)throw Error(`[${o}]: You need to have at least one worker before adding jobs`);return P(z,b)},terminate:async()=>{Object.keys(r).forEach(async z=>{await r[z].terminate()}),d=[]},getQueueLen:g,getNumWorkers:w}},Ne}function vn(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ae,xt;function mn(){if(xt)return Ae;xt=1;function n(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}return Ae=n,Ae}var De,zt;function pn(){if(zt)return De;zt=1;const n=mn();return De=a=>{const s={};return typeof WorkerGlobalScope<"u"?s.type="webworker":n()?s.type="electron":typeof document=="object"?s.type="browser":typeof process=="object"&&typeof vn=="function"&&(s.type="node"),typeof a>"u"?s:s[a]},De}var je,kt;function gn(){if(kt)return je;kt=1;const a=pn()("type")==="browser"?s=>new URL(s,window.location.href).href:s=>s;return je=s=>{const t={...s};return["corePath","workerPath","langPath"].forEach(o=>{s[o]&&(t[o]=a(t[o]))}),t},je}var Ie,St;function bn(){return St||(St=1,Ie=n=>{const a=[],s=[],t=[],o=[],r=[];return n.blocks&&n.blocks.forEach(u=>{u.paragraphs.forEach(d=>{d.lines.forEach(g=>{g.words.forEach(w=>{w.symbols.forEach(x=>{r.push({...x,page:n,block:u,paragraph:d,line:g,word:w})}),o.push({...w,page:n,block:u,paragraph:d,line:g})}),t.push({...g,page:n,block:u,paragraph:d})}),s.push({...d,page:n,block:u})}),a.push({...u,page:n})}),{...n,blocks:a,paragraphs:s,lines:t,words:o,symbols:r}}),Ie}var Te,$t;function ts(){return $t||($t=1,Te={TESSERACT_ONLY:0,LSTM_ONLY:1,TESSERACT_LSTM_COMBINED:2,DEFAULT:3}),Te}const yn="5.1.1",_n={version:yn};var qe,Ct;function wn(){return Ct||(Ct=1,qe={workerBlobURL:!0,logger:()=>{}}),qe}var Fe,Pt;function xn(){if(Pt)return Fe;Pt=1;const n=_n.version;return Fe={...wn(),workerPath:`https://cdn.jsdelivr.net/npm/tesseract.js@v${n}/dist/worker.min.js`},Fe}var Ue,Lt;function zn(){return Lt||(Lt=1,Ue=({workerPath:n,workerBlobURL:a})=>{let s;if(Blob&&URL&&a){const t=new Blob([`importScripts("${n}");`],{type:"application/javascript"});s=new Worker(URL.createObjectURL(t))}else s=new Worker(n);return s}),Ue}var Be,Rt;function kn(){return Rt||(Rt=1,Be=n=>{n.terminate()}),Be}var Ve,Et;function Sn(){return Et||(Et=1,Ve=(n,a)=>{n.onmessage=({data:s})=>{a(s)}}),Ve}var Ge,Ot;function $n(){return Ot||(Ot=1,Ge=async(n,a)=>{n.postMessage(a)}),Ge}var We,Mt;function Cn(){if(Mt)return We;Mt=1;const n=s=>new Promise((t,o)=>{const r=new FileReader;r.onload=()=>{t(r.result)},r.onerror=({target:{error:{code:u}}})=>{o(Error(`File could not be read! Code=${u}`))},r.readAsArrayBuffer(s)}),a=async s=>{let t=s;if(typeof s>"u")return"undefined";if(typeof s=="string")/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(s)?t=atob(s.split(",")[1]).split("").map(o=>o.charCodeAt(0)):t=await(await fetch(s)).arrayBuffer();else if(typeof HTMLElement<"u"&&s instanceof HTMLElement)s.tagName==="IMG"&&(t=await a(s.src)),s.tagName==="VIDEO"&&(t=await a(s.poster)),s.tagName==="CANVAS"&&await new Promise(o=>{s.toBlob(async r=>{t=await n(r),o()})});else if(typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas){const o=await s.convertToBlob();t=await n(o)}else(s instanceof File||s instanceof Blob)&&(t=await n(s));return new Uint8Array(t)};return We=a,We}var He,Nt;function Pn(){if(Nt)return He;Nt=1;const n=xn(),a=zn(),s=kn(),t=Sn(),o=$n(),r=Cn();return He={defaultOptions:n,spawnWorker:a,terminateWorker:s,onMessage:t,send:o,loadImage:r},He}var Je,At;function ss(){if(At)return Je;At=1;const n=gn(),a=bn(),s=es(),{log:t}=ct(),o=it(),r=ts(),{defaultOptions:u,spawnWorker:d,terminateWorker:g,onMessage:w,loadImage:x,send:P}=Pn();let $=0;return Je=async(l="eng",p=r.LSTM_ONLY,z={},b={})=>{const i=o("Worker",$),{logger:c,errorHandler:v,...C}=n({...u,...z}),S={},q={},te=typeof l=="string"?l.split("+"):l;let D=p,M=b;const F=[r.DEFAULT,r.LSTM_ONLY].includes(p)&&!C.legacyCore;let H,ae;const ue=new Promise((O,N)=>{ae=O,H=N}),ge=O=>{H(O.message)};let X=d(C);X.onerror=ge,$+=1;const se=(O,N)=>{S[O]=N},U=(O,N)=>{q[O]=N},K=({id:O,action:N,payload:G})=>new Promise((Z,J)=>{t(`[${i}]: Start ${O}, action=${N}`);const ie=`${N}-${O}`;se(ie,Z),U(ie,J),P(X,{workerId:i,jobId:O,action:N,payload:G})}),_=()=>console.warn("`load` is depreciated and should be removed from code (workers now come pre-loaded)"),m=O=>K(s({id:O,action:"load",payload:{options:{lstmOnly:F,corePath:C.corePath,logging:C.logging}}})),k=(O,N,G)=>K(s({id:G,action:"FS",payload:{method:"writeFile",args:[O,N]}})),E=(O,N)=>K(s({id:N,action:"FS",payload:{method:"readFile",args:[O,{encoding:"utf8"}]}})),L=(O,N)=>K(s({id:N,action:"FS",payload:{method:"unlink",args:[O]}})),j=(O,N,G)=>K(s({id:G,action:"FS",payload:{method:O,args:N}})),W=()=>console.warn("`loadLanguage` is depreciated and should be removed from code (workers now come with language pre-loaded)"),V=(O,N)=>K(s({id:N,action:"loadLanguage",payload:{langs:O,options:{langPath:C.langPath,dataPath:C.dataPath,cachePath:C.cachePath,cacheMethod:C.cacheMethod,gzip:C.gzip,lstmOnly:[r.DEFAULT,r.LSTM_ONLY].includes(D)&&!C.legacyLang}}})),Y=()=>console.warn("`initialize` is depreciated and should be removed from code (workers now come pre-initialized)"),B=(O,N,G,Z)=>K(s({id:Z,action:"initialize",payload:{langs:O,oem:N,config:G}})),be=(O="eng",N,G,Z)=>{if(F&&[r.TESSERACT_ONLY,r.TESSERACT_LSTM_COMBINED].includes(N))throw Error("Legacy model requested but code missing.");const J=N||D;D=J;const ie=G||M;M=ie;const Le=(typeof O=="string"?O.split("+"):O).filter(us=>!te.includes(us));return te.push(...Le),Le.length>0?V(Le,Z).then(()=>B(O,J,ie,Z)):B(O,J,ie,Z)},fe=(O={},N)=>K(s({id:N,action:"setParameters",payload:{params:O}})),le=async(O,N={},G={blocks:!0,text:!0,hocr:!0,tsv:!0},Z)=>K(s({id:Z,action:"recognize",payload:{image:await x(O),options:N,output:G}})),rs=(O="Tesseract OCR Result",N=!1,G)=>(console.log("`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead."),K(s({id:G,action:"getPDF",payload:{title:O,textonly:N}}))),ls=async(O,N)=>{if(F)throw Error("`worker.detect` requires Legacy model, which was not loaded.");return K(s({id:N,action:"detect",payload:{image:await x(O)}}))},is=async()=>(X!==null&&(g(X),X=null),Promise.resolve());w(X,({workerId:O,jobId:N,status:G,action:Z,data:J})=>{const ie=`${Z}-${N}`;if(G==="resolve"){t(`[${O}]: Complete ${N}`);let xe=J;Z==="recognize"?xe=a(J):Z==="getPDF"&&(xe=Array.from({...J,length:Object.keys(J).length})),S[ie]({jobId:N,data:xe})}else if(G==="reject")if(q[ie](J),Z==="load"&&H(J),v)v(J);else throw Error(J);else G==="progress"&&c({...J,userJobId:N})});const cs={id:i,worker:X,setResolve:se,setReject:U,load:_,writeText:k,readText:E,removeFile:L,FS:j,loadLanguage:W,initialize:Y,reinitialize:be,setParameters:fe,recognize:le,getPDF:rs,detect:ls,terminate:is};return m().then(()=>V(l)).then(()=>B(l,p,b)).then(()=>ae(cs)).catch(()=>{}),ue},Je}var Ke,Dt;function Ln(){if(Dt)return Ke;Dt=1;const n=ss();return Ke={recognize:async(t,o,r)=>{const u=await n(o,1,r);return u.recognize(t).finally(async()=>{await u.terminate()})},detect:async(t,o)=>{const r=await n("osd",0,o);return r.detect(t).finally(async()=>{await r.terminate()})}},Ke}var Ye,jt;function Rn(){return jt||(jt=1,Ye={AFR:"afr",AMH:"amh",ARA:"ara",ASM:"asm",AZE:"aze",AZE_CYRL:"aze_cyrl",BEL:"bel",BEN:"ben",BOD:"bod",BOS:"bos",BUL:"bul",CAT:"cat",CEB:"ceb",CES:"ces",CHI_SIM:"chi_sim",CHI_TRA:"chi_tra",CHR:"chr",CYM:"cym",DAN:"dan",DEU:"deu",DZO:"dzo",ELL:"ell",ENG:"eng",ENM:"enm",EPO:"epo",EST:"est",EUS:"eus",FAS:"fas",FIN:"fin",FRA:"fra",FRK:"frk",FRM:"frm",GLE:"gle",GLG:"glg",GRC:"grc",GUJ:"guj",HAT:"hat",HEB:"heb",HIN:"hin",HRV:"hrv",HUN:"hun",IKU:"iku",IND:"ind",ISL:"isl",ITA:"ita",ITA_OLD:"ita_old",JAV:"jav",JPN:"jpn",KAN:"kan",KAT:"kat",KAT_OLD:"kat_old",KAZ:"kaz",KHM:"khm",KIR:"kir",KOR:"kor",KUR:"kur",LAO:"lao",LAT:"lat",LAV:"lav",LIT:"lit",MAL:"mal",MAR:"mar",MKD:"mkd",MLT:"mlt",MSA:"msa",MYA:"mya",NEP:"nep",NLD:"nld",NOR:"nor",ORI:"ori",PAN:"pan",POL:"pol",POR:"por",PUS:"pus",RON:"ron",RUS:"rus",SAN:"san",SIN:"sin",SLK:"slk",SLV:"slv",SPA:"spa",SPA_OLD:"spa_old",SQI:"sqi",SRP:"srp",SRP_LATN:"srp_latn",SWA:"swa",SWE:"swe",SYR:"syr",TAM:"tam",TEL:"tel",TGK:"tgk",TGL:"tgl",THA:"tha",TIR:"tir",TUR:"tur",UIG:"uig",UKR:"ukr",URD:"urd",UZB:"uzb",UZB_CYRL:"uzb_cyrl",VIE:"vie",YID:"yid"}),Ye}var Ze,It;function En(){return It||(It=1,Ze={OSD_ONLY:"0",AUTO_OSD:"1",AUTO_ONLY:"2",AUTO:"3",SINGLE_COLUMN:"4",SINGLE_BLOCK_VERT_TEXT:"5",SINGLE_BLOCK:"6",SINGLE_LINE:"7",SINGLE_WORD:"8",CIRCLE_WORD:"9",SINGLE_CHAR:"10",SPARSE_TEXT:"11",SPARSE_TEXT_OSD:"12",RAW_LINE:"13"}),Ze}var Qe,Tt;function On(){if(Tt)return Qe;Tt=1,fn();const n=hn(),a=ss(),s=Ln(),t=Rn(),o=ts(),r=En(),{setLogging:u}=ct();return Qe={languages:t,OEM:o,PSM:r,createScheduler:n,createWorker:a,setLogging:u,...s},Qe}var Mn=On();class ut{worker=null;availablePuzzleNames=[];regions={puzzle:{x:15,y:600,width:330,height:28},cost:{x:412,y:603,width:65,height:22},cycles:{x:577,y:603,width:65,height:22},area:{x:739,y:603,width:65,height:22}};async initialize(){this.worker||(this.worker=await Mn.createWorker("eng"),await this.worker.setParameters({tessedit_ocr_engine_mode:"3",tessedit_pageseg_mode:7}))}setAvailablePuzzleNames(a){this.availablePuzzleNames=a,console.log("OCR service updated with puzzle names:",a)}async configurePuzzleOCR(){this.worker&&(await this.worker.setParameters({load_system_dawg:"0",load_freq_dawg:"0",load_punc_dawg:"0",load_number_dawg:"0",load_unambig_dawg:"0",load_bigram_dawg:"0",load_fixed_length_dawgs:"0",tessedit_char_whitelist:this.getPuzzleCharacterSet(),tessedit_pageseg_mode:8,segment_penalty_dict_nonword:"2.0",segment_penalty_dict_frequent_word:"0.001",segment_penalty_dict_case_ok:"0.001",segment_penalty_dict_case_bad:"0.1",classify_enable_learning:"0",classify_enable_adaptive_matcher:"1",preserve_interword_spaces:"1"}),console.log("OCR configured for puzzle names with character set:",this.getPuzzleCharacterSet()))}getPuzzleCharacterSet(){if(this.availablePuzzleNames.length===0)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -";const a=new Set;return this.availablePuzzleNames.forEach(s=>{for(const t of s)a.add(t)}),Array.from(a).join("")}async extractOpusMagnumData(a){this.worker||await this.initialize();const s=URL.createObjectURL(a),t=new Image;return new Promise((o,r)=>{t.onload=async()=>{try{const u=document.createElement("canvas"),d=u.getContext("2d");u.width=t.width,u.height=t.height,d.drawImage(t,0,0);const g={},w={};for(const[$,l]of Object.entries(this.regions)){const p=document.createElement("canvas"),z=p.getContext("2d");p.width=l.width,p.height=l.height,z.drawImage(u,l.x,l.y,l.width,l.height,0,0,l.width,l.height);const b=z.getImageData(0,0,l.width,l.height);this.preprocessImage(b),z.putImageData(b,0,0),$==="cost"?await this.worker.setParameters({tessedit_char_whitelist:"0123456789G"}):$==="cycles"||$==="area"?await this.worker.setParameters({tessedit_char_whitelist:"0123456789"}):$==="puzzle"?await this.configurePuzzleOCR():await this.worker.setParameters({tessedit_char_whitelist:""});const{data:{text:i,confidence:c}}=await this.worker.recognize(p);let v=i.trim();if(w[$]=c/100,$==="cost"){if(v.endsWith("6")&&v.length>1){const C=v.slice(0,-1);/^\d+$/.test(C)&&(v=C)}v=v.replace(/G+$/g,""),v=v.replace(/[^0-9]/g,"")}else if($==="cycles"||$==="area")v=v.replace(/[^0-9]/g,"");else if($==="puzzle"&&(v=this.findBestPuzzleMatch(v),this.availablePuzzleNames.length>0&&!this.availablePuzzleNames.includes(v))){const C=this.findBestPuzzleMatchForced(v);C&&(v=C,console.log(`Forced OCR match: "${i.trim()}" -> "${v}"`))}g[$]=v}URL.revokeObjectURL(s);const x=Object.values(w),P=x.length>0?x.reduce(($,l)=>$+l,0)/x.length:0;o({puzzle:g.puzzle||"",cost:parseInt(g.cost||""),cycles:parseInt(g.cycles||""),area:parseInt(g.area||""),confidence:{puzzle:w.puzzle||0,cost:w.cost||0,cycles:w.cycles||0,area:w.area||0,overall:P}})}catch(u){URL.revokeObjectURL(s),r(u)}},t.onerror=()=>{URL.revokeObjectURL(s),r(new Error("Failed to load image"))},t.src=s})}preprocessImage(a){const s=a.data;for(let t=0;t<s.length;t+=4){const r=255-Math.round(.299*s[t]+.587*s[t+1]+.114*s[t+2]);s[t]=r,s[t+1]=r,s[t+2]=r}}levenshteinDistance(a,s){const t=Array(s.length+1).fill(null).map(()=>Array(a.length+1).fill(null));for(let o=0;o<=a.length;o++)t[0][o]=o;for(let o=0;o<=s.length;o++)t[o][0]=o;for(let o=1;o<=s.length;o++)for(let r=1;r<=a.length;r++){const u=a[r-1]===s[o-1]?0:1;t[o][r]=Math.min(t[o][r-1]+1,t[o-1][r]+1,t[o-1][r-1]+u)}return t[s.length][a.length]}findBestPuzzleMatch(a){if(!this.availablePuzzleNames.length)return a.trim();const s=a.trim();if(!s)return"";const t=this.availablePuzzleNames.find(d=>d.toLowerCase()===s.toLowerCase());if(t)return t;const o=this.availablePuzzleNames.find(d=>d.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(d.toLowerCase()));if(o)return o;let r=s,u=0;for(const d of this.availablePuzzleNames){const g=[this.calculateLevenshteinSimilarity(s,d),this.calculateJaroWinklerSimilarity(s,d),this.calculateNGramSimilarity(s,d,2)],w=Math.max(...g);w>u&&w>.4&&(u=w,r=d)}if(u<.6){const d=this.findBestCharacterMatch(s);d&&(r=d)}return r}calculateLevenshteinSimilarity(a,s){const t=this.levenshteinDistance(a.toLowerCase(),s.toLowerCase()),o=Math.max(a.length,s.length);return o===0?1:1-t/o}calculateJaroWinklerSimilarity(a,s){const t=a.toLowerCase(),o=s.toLowerCase();if(t===o)return 1;const r=Math.floor(Math.max(t.length,o.length)/2)-1;if(r<0)return 0;const u=new Array(t.length).fill(!1),d=new Array(o.length).fill(!1);let g=0,w=0;for(let l=0;l<t.length;l++){const p=Math.max(0,l-r),z=Math.min(l+r+1,o.length);for(let b=p;b<z;b++)if(!(d[b]||t[l]!==o[b])){u[l]=!0,d[b]=!0,g++;break}}if(g===0)return 0;let x=0;for(let l=0;l<t.length;l++)if(u[l]){for(;!d[x];)x++;t[l]!==o[x]&&w++,x++}const P=(g/t.length+g/o.length+(g-w/2)/g)/3;let $=0;for(let l=0;l<Math.min(t.length,o.length,4)&&t[l]===o[l];l++)$++;return P+.1*$*(1-P)}calculateNGramSimilarity(a,s,t){const o=a.toLowerCase(),r=s.toLowerCase();if(o===r)return 1;if(o.length<t||r.length<t)return 0;const u=new Set,d=new Set;for(let x=0;x<=o.length-t;x++)u.add(o.substr(x,t));for(let x=0;x<=r.length-t;x++)d.add(r.substr(x,t));const g=new Set([...u].filter(x=>d.has(x))),w=new Set([...u,...d]);return g.size/w.size}findBestCharacterMatch(a){let s=null,t=0;for(const o of this.availablePuzzleNames){const r=this.calculateCharacterFrequencyScore(a.toLowerCase(),o.toLowerCase());r>t&&r>.3&&(t=r,s=o)}return s}calculateCharacterFrequencyScore(a,s){const t=new Map,o=new Map;for(const g of a)t.set(g,(t.get(g)||0)+1);for(const g of s)o.set(g,(o.get(g)||0)+1);const r=new Set([...t.keys(),...o.keys()]);let u=0,d=0;for(const g of r){const w=t.get(g)||0,x=o.get(g)||0;u+=Math.min(w,x),d+=Math.max(w,x)}return d===0?0:u/d}findBestPuzzleMatchForced(a){if(!this.availablePuzzleNames.length||!a.trim())return null;const s=a.trim().toLowerCase();let t=this.availablePuzzleNames[0],o=0;for(const r of this.availablePuzzleNames){const u=[this.calculateLevenshteinSimilarity(s,r),this.calculateJaroWinklerSimilarity(s,r),this.calculateNGramSimilarity(s,r,2),this.calculateCharacterFrequencyScore(s,r.toLowerCase()),this.calculateLengthSimilarity(s,r.toLowerCase())],d=u[0]*.25+u[1]*.25+u[2]*.2+u[3]*.2+u[4]*.1;d>o&&(o=d,t=r)}return console.log(`Forced match for "${a}": "${t}" (score: ${o.toFixed(3)})`),t}calculateLengthSimilarity(a,s){const t=a.length,o=s.length,r=Math.max(t,o),u=Math.min(t,o);return r===0?1:u/r}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null)}static isValidOpusMagnumImage(a){return["image/jpeg","image/jpg","image/png","image/gif"].includes(a.type)}static drawDebugRegions(a){return new Promise((s,t)=>{const o=URL.createObjectURL(a),r=new Image;r.onload=()=>{const u=document.createElement("canvas"),d=u.getContext("2d");u.width=r.width,u.height=r.height,d.drawImage(r,0,0),d.strokeStyle="#00ff00",d.lineWidth=2;const g=new ut;Object.values(g.regions).forEach(w=>{d.strokeRect(w.x,w.y,w.width,w.height)}),URL.revokeObjectURL(o),s(u.toDataURL())},r.onerror=()=>{URL.revokeObjectURL(o),t(new Error("Failed to load image for debug"))},r.src=o})}}const st=new ut,_e=.8,ns=at("uploads",()=>{const n=I([]),a=ne(()=>n.value.some(g=>g.ocrProcessing)),s=ne(()=>n.value.some(g=>o(g))),t=ne(()=>n.value.filter(g=>g.needsManualPuzzleSelection)),o=g=>g.ocrData?.confidence?g.ocrData.confidence.cost<_e||g.ocrData.confidence.cycles<_e||g.ocrData.confidence.area<_e:!1,r=async g=>{for(;a.value;){const x=Math.floor(Math.random()*400)+100;console.log(`OCR is already processing, waiting ${x}ms...`),await new Promise(P=>setTimeout(P,x))}const w=n.value.indexOf(g);n.value[w].ocrProcessing=!0,n.value[w].ocrError=void 0,n.value[w].ocrData=void 0;try{console.log("Starting OCR processing for:",g.file.name),await st.initialize();const x=await st.extractOpusMagnumData(g.file);console.log("OCR completed:",x),await Se(),n.value[w].ocrData=x,x.confidence.puzzle<_e?(n.value[w].needsManualPuzzleSelection=!0,console.log(`Low puzzle confidence (${Math.round(x.confidence.puzzle*100)}%) for ${g.file.name}, requiring manual selection`)):n.value[w].needsManualPuzzleSelection=!1,await Se()}catch(x){console.error("OCR processing failed:",x),n.value[w].ocrError="Failed to extract puzzle data"}finally{n.value[w].ocrProcessing=!1}};return{submissionFiles:n,submissionFilesNeedingManualSelection:t,processOCR:r,processLowConfidenceOCRFiles:async()=>{const g=n.value.filter(w=>o(w));for(const w of g)r(w)},clearFiles:()=>{n.value=[]},isProcessingOCR:a,hasLowConfidence:s,CONFIDENCE_VALUE:_e}}),Nn={class:"form-control w-full"},An={key:0,class:"space-y-4"},Dn={key:1,class:"space-y-4"},jn={class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-4"},In={class:"aspect-square rounded-lg overflow-hidden bg-base-200"},Tn=["src","alt"],qn={class:"absolute inset-0 bg-black/80 opacity-0 group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center"},Fn=["onClick"],Un={class:"mt-2"},Bn={class:"text-xs font-medium truncate"},Vn={class:"text-xs text-base-content/60"},Gn={key:0,class:"mt-1 flex items-center gap-1"},Wn={key:1,class:"mt-1"},Hn={class:"text-xs text-error"},Jn={key:2,class:"mt-1 space-y-1"},Kn={class:"text-xs flex items-center justify-between"},Yn={class:"flex items-center gap-2"},Zn=["title"],Qn=["onClick"],Xn={class:"text-xs space-y-1 bg-base-200 p-2 rounded"},eo={key:0},to=["title"],so={key:1},no=["title"],oo={key:2},ao=["title"],ro={key:3},lo=["title"],io={key:3,class:"mt-2"},co={class:"mt-2"},uo=["onUpdate:modelValue","onChange"],fo=["value"],ho={key:4,class:"mt-1"},vo=["onClick"],mo={class:"flex justify-center"},po={key:0,class:"label"},go={class:"label-text-alt text-error"},bo=pe({__name:"FileUpload",setup(n){const a=Pe(),{submissionFiles:s,processOCR:t}=ns(),o=I(),r=I(!1),u=I("");$e(()=>a.puzzles,i=>{i&&i.length>0&&st.setAvailablePuzzleNames(a.puzzleNames)},{immediate:!0});const d=i=>{const c=i.target;c.files&&w(Array.from(c.files))},g=i=>{i.preventDefault(),r.value=!1,i.dataTransfer?.files&&w(Array.from(i.dataTransfer.files))},w=async i=>{u.value="";for(const c of i)if(x(c))try{const v=await P(c),C=c.type.startsWith("image/gif")?"gif":"image",S={file:c,file_url:"",preview:v,type:C,ocrProcessing:!1,ocrError:void 0,ocrData:void 0};s.push(S),p(c)&&Se(()=>{t(S)})}catch{u.value=`Failed to process ${c.name}`}},x=i=>i.type.startsWith("image/")?i.size>256*1024*1024?(u.value=`${i.name} is too large (max 256MB)`,!1):!0:(u.value=`${i.name} is not a valid image file`,!1),P=i=>new Promise((c,v)=>{const C=new FileReader;C.onload=S=>c(S.target?.result),C.onerror=v,C.readAsDataURL(i)}),$=i=>{s.splice(i,1)},l=i=>{if(i===0)return"0 Bytes";const c=1024,v=["Bytes","KB","MB","GB"],C=Math.floor(Math.log(i)/Math.log(c));return parseFloat((i/Math.pow(c,C)).toFixed(2))+" "+v[C]},p=i=>i.type.startsWith("image/")&&i.size>5e4,z=i=>i>=.8?"badge-success":i>=.6?"badge-warning":"badge-error",b=i=>{const c=s.findIndex(v=>v.file===i.file);c!==-1&&s[c].manualPuzzleSelection&&(s[c].needsManualPuzzleSelection=!1,console.log(`Manual puzzle selection: ${i.file.name} -> ${s[c].manualPuzzleSelection}`))};return(i,c)=>(f(),h("div",Nn,[c[19]||(c[19]=e("label",{class:"label"},[e("span",{class:"label-text font-medium"},"Upload Solution Files"),e("span",{class:"label-text-alt text-xs"},"Images or GIFs only")],-1)),e("div",{class:oe(["border-2 border-dashed border-base-300 rounded-lg p-6 text-center hover:border-primary transition-colors duration-300",{"border-primary bg-primary/5":r.value}]),onDrop:g,onDragover:c[2]||(c[2]=Xe(v=>r.value=!0,["prevent"])),onDragleave:c[3]||(c[3]=v=>r.value=!1),onDragenter:c[4]||(c[4]=Xe(()=>{},["prevent"]))},[e("input",{ref_key:"fileInput",ref:o,type:"file",multiple:"",accept:"image/*,.gif",class:"hidden",onChange:d},null,544),T(s).length===0?(f(),h("div",An,[c[6]||(c[6]=e("div",{class:"mx-auto w-12 h-12 text-base-content/40 flex items-center justify-center"},[e("i",{class:"mdi mdi-cloud-upload text-5xl"})],-1)),e("div",null,[c[5]||(c[5]=e("p",{class:"text-base-content/70 mb-2"},"Drop your files here or",-1)),e("button",{type:"button",onClick:c[0]||(c[0]=v=>o.value?.click()),class:"btn btn-primary btn-sm"}," Choose Files ")]),c[7]||(c[7]=e("p",{class:"text-xs text-base-content/50"}," Supported formats: JPG, PNG, GIF (max 256MB each) ",-1))])):(f(),h("div",Dn,[e("div",jn,[(f(!0),h(Q,null,ee(T(s),(v,C)=>(f(),h("div",{key:C,class:"relative group"},[e("div",In,[e("img",{src:v.preview,alt:v.file.name,class:"w-full h-full object-cover"},null,8,Tn)]),e("div",qn,[e("button",{onClick:S=>$(C),class:"btn btn-error btn-lg btn-circle"},[...c[8]||(c[8]=[e("i",{class:"mdi mdi-close"},null,-1)])],8,Fn)]),e("div",Un,[e("p",Bn,y(v.file.name),1),e("p",Vn,y(l(v.file.size))+" "+y(v.type.toUpperCase()),1),v.ocrProcessing?(f(),h("div",Gn,[...c[9]||(c[9]=[e("span",{class:"loading loading-spinner loading-xs"},null,-1),e("span",{class:"text-xs text-info"},"Extracting puzzle data...",-1)])])):v.ocrError?(f(),h("div",Wn,[e("p",Hn,y(v.ocrError),1)])):v.ocrData?(f(),h("div",Jn,[e("div",Kn,[e("div",Yn,[c[10]||(c[10]=e("span",{class:"font-medium text-success"}," OCR Complete",-1)),v.ocrData.confidence?(f(),h("span",{key:0,class:oe(["badge badge-xs",z(v.ocrData.confidence.overall)]),title:`Overall confidence: ${Math.round(v.ocrData.confidence.overall*100)}%`},y(Math.round(v.ocrData.confidence.overall*100))+"% ",11,Zn)):R("",!0)]),e("button",{onClick:S=>T(t)(v),class:"btn btn-xs btn-ghost",title:"Retry OCR"},[...c[11]||(c[11]=[e("i",{class:"mdi mdi-refresh"},null,-1)])],8,Qn)]),e("div",Xn,[v.ocrData.puzzle?(f(),h("div",eo,[c[12]||(c[12]=e("strong",null,"Puzzle:",-1)),A(" "+y(v.ocrData.puzzle)+" ",1),v.ocrData.confidence?.puzzle?(f(),h("span",{key:0,class:"ml-2 opacity-60",title:`Puzzle confidence: ${Math.round(v.ocrData.confidence.puzzle*100)}%`}," ("+y(Math.round(v.ocrData.confidence.puzzle*100))+"%) ",9,to)):R("",!0)])):R("",!0),v.ocrData.cost?(f(),h("div",so,[c[13]||(c[13]=e("strong",null,"Cost:",-1)),A(" "+y(v.ocrData.cost)+" ",1),v.ocrData.confidence?.cost?(f(),h("span",{key:0,class:"ml-2 opacity-60",title:`Cost confidence: ${Math.round(v.ocrData.confidence.cost*100)}%`}," ("+y(Math.round(v.ocrData.confidence.cost*100))+"%) ",9,no)):R("",!0)])):R("",!0),v.ocrData.cycles?(f(),h("div",oo,[c[14]||(c[14]=e("strong",null,"Cycles:",-1)),A(" "+y(v.ocrData.cycles)+" ",1),v.ocrData.confidence?.cycles?(f(),h("span",{key:0,class:"ml-2 opacity-60",title:`Cycles confidence: ${Math.round(v.ocrData.confidence.cycles*100)}%`}," ("+y(Math.round(v.ocrData.confidence.cycles*100))+"%) ",9,ao)):R("",!0)])):R("",!0),v.ocrData.area?(f(),h("div",ro,[c[15]||(c[15]=e("strong",null,"Area:",-1)),A(" "+y(v.ocrData.area)+" ",1),v.ocrData.confidence?.area?(f(),h("span",{key:0,class:"ml-2 opacity-60",title:`Area confidence: ${Math.round(v.ocrData.confidence.area*100)}%`}," ("+y(Math.round(v.ocrData.confidence.area*100))+"%) ",9,lo)):R("",!0)])):R("",!0)])])):R("",!0),v.needsManualPuzzleSelection?(f(),h("div",io,[c[17]||(c[17]=ps('<div class="alert alert-warning alert-sm"><i class="mdi mdi-alert-circle text-lg"></i><div class="flex-1"><div class="font-medium">Low OCR Confidence</div><div class="text-xs"> Please select the correct puzzle manually </div></div></div>',1)),e("div",co,[ce(e("select",{"onUpdate:modelValue":S=>v.manualPuzzleSelection=S,class:"select select-bordered select-sm w-full",onChange:S=>b(v)},[c[16]||(c[16]=e("option",{value:""},"Select puzzle...",-1)),(f(!0),h(Q,null,ee(T(a).puzzles,S=>(f(),h("option",{key:S.id,value:S.title},y(S.title),9,fo))),128))],40,uo),[[Ht,v.manualPuzzleSelection]])])])):!v.ocrProcessing&&!v.ocrError&&!v.ocrData?(f(),h("div",ho,[e("button",{onClick:S=>T(t)(v),class:"btn btn-xs btn-outline"},[...c[18]||(c[18]=[e("i",{class:"mdi mdi-text-recognition"},null,-1),A(" Extract Puzzle Data ",-1)])],8,vo)])):R("",!0)])]))),128))]),e("div",mo,[e("button",{type:"button",onClick:c[1]||(c[1]=v=>o.value?.click()),class:"btn btn-outline btn-sm"}," Add More Files ")])]))],34),u.value?(f(),h("div",po,[e("span",go,y(u.value),1)])):R("",!0)]))}}),yo={class:"card bg-base-100 shadow-xl"},_o={class:"card-body"},wo={key:0,class:"alert alert-info"},xo={class:"flex-1"},zo={class:"font-bold"},ko={class:"text-sm space-y-1 mt-1"},So={class:"badge badge-ghost badge-sm ml-2"},$o={key:1,class:"alert alert-warning"},Co={class:"flex-1"},Po={class:"text-sm"},Lo={class:"form-control"},Ro={class:"flex-1"},Eo={class:"flex label"},Oo={class:"label-text-alt"},Mo={class:"form-control"},No={class:"label cursor-pointer justify-start gap-3"},Ao=["disabled"],Do={class:"card-actions justify-end"},jo=["disabled"],Io={key:0,class:"loading loading-spinner loading-sm"},To={key:1},qo={key:2},Fo={key:3},Uo=pe({__name:"SubmissionForm",props:{puzzles:{},findPuzzleByName:{type:Function}},setup(n){const a=n,s=ns(),{submissionFiles:t,hasLowConfidence:o,submissionFilesNeedingManualSelection:r}=rt(s),{clearFiles:u,processLowConfidenceOCRFiles:d}=s,{handleSubmission:g}=lt(),w=I(""),x=I(!1),P=I(!1),$=ne(()=>w.value.length),l=ne(()=>{const b=t.value.length>0,i=!t.value.some(c=>c.needsManualPuzzleSelection);return b&&!P.value&&i});$e(o,b=>{b&&(x.value=!0)});const p=ne(()=>{const b={};return t.value.forEach(i=>{const c=i.manualPuzzleSelection||i.ocrData?.puzzle;c&&(b[c]||(b[c]={puzzle:a.findPuzzleByName(c),files:[]}),b[c].files.push(i))}),b}),z=async()=>{if(l.value){P.value=!0;try{g({files:t.value,notes:w.value.trim()||void 0,manualValidationRequested:o.value||x.value}),u(),w.value="",x.value=!1}catch(b){console.error("Submission error:",b)}finally{P.value=!1}}};return(b,i)=>(f(),h("div",yo,[e("div",_o,[i[9]||(i[9]=e("h2",{class:"card-title text-xl mb-6"},[e("i",{class:"mdi mdi-check-circle text-2xl text-primary"}),A(" Submit Solution ")],-1)),e("form",{onSubmit:Xe(z,["prevent"]),class:"space-y-6"},[Object.keys(p.value).length>0?(f(),h("div",wo,[i[3]||(i[3]=e("i",{class:"mdi mdi-information-outline text-xl"},null,-1)),e("div",xo,[e("h4",zo," Detected Puzzles ("+y(Object.keys(p.value).length)+") ",1),e("div",ko,[(f(!0),h(Q,null,ee(p.value,(c,v)=>(f(),h("div",{key:v,class:"flex justify-between"},[e("span",null,y(v),1),e("span",So,y(c.files.length)+" file(s)",1)]))),128))])])])):R("",!0),ve(bo),T(r).length>0?(f(),h("div",$o,[i[6]||(i[6]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",Co,[i[5]||(i[5]=e("div",{class:"font-bold"},"Manual Puzzle Selection Required",-1)),e("div",Po,y(T(r).length)+" file(s) have low OCR confidence for puzzle names. Please select the correct puzzle for each file before submitting. ",1),e("button",{class:"btn mt-3 w-full",onClick:i[0]||(i[0]=(...c)=>T(d)&&T(d)(...c))},[...i[4]||(i[4]=[e("span",{class:"mdi mdi-reload text-2xl"},null,-1),A(" Retry OCR on low confidence puzzle ",-1)])])])])):R("",!0),e("div",Lo,[e("div",Ro,[e("label",Eo,[i[7]||(i[7]=e("span",{class:"label-text font-medium"},"Notes (Optional)",-1)),e("span",Oo,y($.value)+"/500",1)]),ce(e("textarea",{"onUpdate:modelValue":i[1]||(i[1]=c=>w.value=c),class:"flex textarea textarea-bordered h-24 w-full resize-none",placeholder:"Add any notes about your solution, approach, or interesting findings...",maxlength:"500"},null,512),[[ze,w.value]])])]),e("div",Mo,[e("label",No,[ce(e("input",{type:"checkbox","onUpdate:modelValue":i[2]||(i[2]=c=>x.value=c),class:"checkbox checkbox-primary",disabled:T(o)},null,8,Ao),[[gs,x.value]]),i[8]||(i[8]=e("div",{class:"flex-1"},[e("span",{class:"label-text font-medium"},"Request manual validation"),e("div",{class:"label-text-alt text-xs opacity-70 mt-1"},[A(" Check this if you want an admin to manually review your submission, even if OCR confidence is high. "),e("br"),e("em",null,"Note: This will be automatically checked if any OCR confidence is below 80%.")])],-1))])]),e("div",Do,[e("button",{type:"submit",class:"btn btn-primary",disabled:!l.value},[P.value?(f(),h("span",Io)):R("",!0),P.value?(f(),h("span",To,"Submitting...")):T(r).length>0?(f(),h("span",qo," Select Puzzles ("+y(T(r).length)+" remaining) ",1)):(f(),h("span",Fo,"Submit Solution"))],8,jo)])],32)])]))}}),Bo={class:"card bg-base-100 shadow-xl"},Vo={class:"card-body"},Go={class:"stats stats-vertical lg:stats-horizontal shadow mb-6"},Wo={class:"stat"},Ho={class:"stat-value text-primary"},Jo={class:"stat"},Ko={class:"stat-value text-secondary"},Yo={class:"stat"},Zo={class:"stat-value text-warning"},Qo={class:"stat"},Xo={class:"stat-value text-success"},ea={key:0},ta={class:"overflow-x-auto"},sa={class:"table table-zebra"},na={class:"font-bold"},oa={class:"text-sm opacity-50"},aa={class:"text-sm space-y-1"},ra={class:"flex justify-between items-center"},la={class:"flex justify-between items-center"},ia={class:"flex justify-between items-center"},ca={class:"badge badge-warning badge-sm"},ua=["onClick"],da=["onClick"],fa={key:1,class:"text-center py-8"},ha={key:0,class:"modal modal-open"},va={class:"modal-box w-11/12 max-w-5xl"},ma=["src"],pa={key:0,class:"space-y-4"},ga={class:"alert alert-info"},ba={class:"font-bold"},ya={class:"grid grid-cols-4 gap-4"},_a={class:"form-control"},wa=["value"],xa={class:"form-control"},za=["placeholder"],ka={class:"form-control"},Sa=["placeholder"],$a={class:"form-control"},Ca=["placeholder"],Pa={class:"modal-action"},La=["disabled"],Ra={key:0,class:"loading loading-spinner loading-sm"},Ea={class:"mockup-code w-full"},Oa=pe({__name:"AdminPanel",setup(n,{expose:a}){const s=Pe(),t=I({total_submissions:0,total_responses:0,needs_validation:0,validated_submissions:0,validation_rate:0}),o=I([]),r=I(!1),u=I(!1),d=I({show:!1,response:null,data:{puzzle:-1,validated_cost:0,validated_cycles:0,validated_area:0}}),g=async()=>{try{r.value=!0;try{const i=await re.getStats();i.data&&(t.value=i.data)}catch(i){console.warn("Stats endpoint not available:",i),t.value={total_submissions:0,total_responses:0,needs_validation:0,validated_submissions:0,validation_rate:0}}const b=await re.getResponsesNeedingValidation();b.data&&(o.value=b.data)}catch(b){console.error("Failed to load admin data:",b)}finally{r.value=!1}},w=async()=>{for(const b of Array.from(o.value)){if(!b.id)continue;const{data:i,error:c}=await re.autoValidateResponses(b.id);if(i&&!i.needs_manual_validation)o.value=o.value.filter(v=>v.id!==b.id),t.value.needs_validation-=1;else if(c)break}},x=b=>{d.value.response=b,d.value.data={puzzle:b.puzzle_id||-1,validated_cost:b.cost||0,validated_cycles:b.cycles||0,validated_area:b.area||0},d.value.show=!0},P=()=>{d.value.show=!1,d.value.response=null,d.value.data={puzzle:-1,validated_cost:0,validated_cycles:0,validated_area:0}},$=async b=>{const{data:i}=await re.autoValidateResponses(b);console.log(i),i&&!i.needs_manual_validation&&(o.value=o.value.filter(c=>c.id!==b),console.log(t.value),t.value.needs_validation-=1,console.log(t.value))},l=async()=>{if(d.value.response?.id)try{u.value=!0;const b=await re.validateResponse(d.value.response.id,d.value.data);if(b.error){alert(`Validation failed: ${b.error}`);return}o.value=o.value.filter(i=>i.id!==d.value.response?.id),t.value.needs_validation=Math.max(0,t.value.needs_validation-1),P()}catch(b){console.error("Validation error:",b),alert("Validation failed")}finally{u.value=!1}};ot(()=>{g()});const p=b=>b>=.8?"badge-success":b>=.6?"badge-warning":"badge-error",z=b=>{const i=[b.ocr_confidence_cost,b.ocr_confidence_cycles,b.ocr_confidence_area].filter(v=>v!=null);if(i.length===0)return 0;const c=i.reduce((v,C)=>v+C,0)/i.length;return Math.round(c*100)};return a({refresh:g}),(b,i)=>(f(),h(Q,null,[e("div",Bo,[e("div",Vo,[i[14]||(i[14]=e("h2",{class:"card-title"},[e("i",{class:"mdi mdi-shield-account text-2xl text-warning"}),A(" Admin Panel ")],-1)),e("div",Go,[e("div",Wo,[i[4]||(i[4]=e("div",{class:"stat-title"},"Total Submissions",-1)),e("div",Ho,y(t.value.total_submissions),1)]),e("div",Jo,[i[5]||(i[5]=e("div",{class:"stat-title"},"Total Responses",-1)),e("div",Ko,y(t.value.total_responses),1)]),e("div",Yo,[i[6]||(i[6]=e("div",{class:"stat-title"},"Need Validation",-1)),e("div",Zo,y(t.value.needs_validation),1)]),e("div",Qo,[i[7]||(i[7]=e("div",{class:"stat-title"},"Validation Rate",-1)),e("div",Xo,y(Math.round(t.value.validation_rate*100))+"% ",1)])]),e("button",{class:"btn btn-sm btn-primary",onClick:w},[...i[8]||(i[8]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),A(" Auto validation for all responses ",-1)])]),o.value.length>0?(f(),h("div",ea,[i[12]||(i[12]=e("h3",{class:"text-lg font-bold mb-4"},"Responses Needing Validation",-1)),e("div",ta,[e("table",sa,[i[11]||(i[11]=e("thead",null,[e("tr",null,[e("th",null,"Puzzle"),e("th",null,"OCR Data"),e("th",null,"Confidence"),e("th",null,"Actions")])],-1)),e("tbody",null,[(f(!0),h(Q,null,ee(o.value,c=>(f(),h("tr",{key:c.id},[e("td",null,[e("div",na,y(c.puzzle_name),1),e("div",oa,"ID: "+y(c.id),1)]),e("td",null,[e("div",aa,[e("div",ra,[e("span",null,"Cost: "+y(c.cost||"-"),1),c.ocr_confidence_cost?(f(),h("span",{key:0,class:oe(["badge badge-xs",p(c.ocr_confidence_cost)])},y(Math.round(c.ocr_confidence_cost*100))+"% ",3)):R("",!0)]),e("div",la,[e("span",null,"Cycles: "+y(c.cycles||"-"),1),c.ocr_confidence_cycles?(f(),h("span",{key:0,class:oe(["badge badge-xs",p(c.ocr_confidence_cycles)])},y(Math.round(c.ocr_confidence_cycles*100))+"% ",3)):R("",!0)]),e("div",ia,[e("span",null,"Area: "+y(c.area||"-"),1),c.ocr_confidence_area?(f(),h("span",{key:0,class:oe(["badge badge-xs",p(c.ocr_confidence_area)])},y(Math.round(c.ocr_confidence_area*100))+"% ",3)):R("",!0)])])]),e("td",null,[e("div",ca,y(z(c))+"% ",1)]),e("td",null,[e("button",{onClick:v=>x(c),class:"btn btn-sm btn-primary mr-2"},[...i[9]||(i[9]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),A(" Validate ",-1)])],8,ua),c.id?(f(),h("button",{key:0,onClick:v=>$(c.id),class:"btn btn-sm btn-warning"},[...i[10]||(i[10]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),A(" Auto Validation ",-1)])],8,da)):R("",!0)])]))),128))])])])])):(f(),h("div",fa,[...i[13]||(i[13]=[e("i",{class:"mdi mdi-check-all text-6xl text-success opacity-50"},null,-1),e("p",{class:"text-lg font-medium mt-2"},"All responses validated!",-1),e("p",{class:"text-sm opacity-70"}," No responses currently need manual validation. ",-1)])]))])]),d.value.show?(f(),h("div",ha,[e("div",va,[i[22]||(i[22]=e("h3",{class:"font-bold text-lg mb-4"},"Validate Response",-1)),(f(!0),h(Q,null,ee(d.value.response?.files??[],c=>(f(),h("div",null,[e("img",{src:c.file_url},null,8,ma)]))),256)),d.value.response?(f(),h("div",pa,[e("div",ga,[i[16]||(i[16]=e("i",{class:"mdi mdi-information-outline"},null,-1)),e("div",null,[e("div",ba,y(d.value.response.puzzle_name),1),i[15]||(i[15]=e("div",{class:"text-sm"},"Review and correct the OCR data below",-1))])]),e("div",ya,[e("div",_a,[i[18]||(i[18]=e("label",{class:"label"},[e("span",{class:"label-text"},"Puzzle")],-1)),ce(e("select",{"onUpdate:modelValue":i[0]||(i[0]=c=>d.value.data.puzzle=c),class:"select select-bordered select-sm w-full"},[i[17]||(i[17]=e("option",{value:""},"Select puzzle...",-1)),(f(!0),h(Q,null,ee(T(s).puzzles,c=>(f(),h("option",{key:c.id,value:c.id},y(c.title),9,wa))),128))],512),[[Ht,d.value.data.puzzle]])]),e("div",xa,[i[19]||(i[19]=e("label",{class:"label"},[e("span",{class:"label-text"},"Cost")],-1)),ce(e("input",{"onUpdate:modelValue":i[1]||(i[1]=c=>d.value.data.validated_cost=c),type:"text",class:"input input-bordered input-sm",placeholder:d.value.response.cost?.toString()||"Enter cost"},null,8,za),[[ze,d.value.data.validated_cost]])]),e("div",ka,[i[20]||(i[20]=e("label",{class:"label"},[e("span",{class:"label-text"},"Cycles")],-1)),ce(e("input",{"onUpdate:modelValue":i[2]||(i[2]=c=>d.value.data.validated_cycles=c),type:"text",class:"input input-bordered input-sm",placeholder:d.value.response.cycles?.toString()||"Enter cycles"},null,8,Sa),[[ze,d.value.data.validated_cycles]])]),e("div",$a,[i[21]||(i[21]=e("label",{class:"label"},[e("span",{class:"label-text"},"Area")],-1)),ce(e("input",{"onUpdate:modelValue":i[3]||(i[3]=c=>d.value.data.validated_area=c),type:"text",class:"input input-bordered input-sm",placeholder:d.value.response.area?.toString()||"Enter area"},null,8,Ca),[[ze,d.value.data.validated_area]])])]),e("div",Pa,[e("button",{onClick:P,class:"btn btn-ghost"}," Cancel "),e("button",{onClick:l,class:"btn btn-primary",disabled:u.value},[u.value?(f(),h("span",Ra)):R("",!0),A(" "+y(u.value?"Validating...":"Validate"),1)],8,La)]),e("div",Ea,[e("pre",null,[e("code",null,y(d.value),1)])])])):R("",!0)]),e("div",{class:"modal-backdrop",onClick:P})])):R("",!0)],64))}}),Ma={class:"mb-8"},Na={class:"grid grid-cols-1 lg:grid-cols-3 gap-8"},Aa={class:"lg:col-span-1"},Da={class:"card bg-base-100 shadow-lg sticky top-8"},ja={class:"card-body"},Ia={class:"text-center mb-6"},Ta={class:"text-3xl font-bold"},qa={key:0,class:"flex justify-center py-8"},Fa={key:1,class:"space-y-4"},Ua={class:"text-center"},Ba={key:0,class:"text-4xl font-bold text-primary"},Va={key:1,class:"text-2xl text-base-content/50"},Ga={class:"text-center"},Wa={class:"text-2xl font-bold"},Ha={class:"text-center"},Ja={class:"text-2xl font-bold"},Ka={class:"lg:col-span-2"},Ya={class:"card bg-base-100 shadow-lg"},Za={class:"card-body"},Qa={key:0,class:"flex justify-center py-8"},Xa={key:1,class:"text-center py-8"},er={key:2,class:"space-y-6"},tr={class:"tabs tabs-border"},sr={class:"space-y-4"},nr={key:0,class:"text-center py-8"},or={key:1,class:"overflow-x-auto"},ar={class:"table table-zebra w-full"},rr={class:"font-bold"},lr={class:"font-medium"},ir={key:0,class:"badge badge-warning"},cr={class:"text-right"},ur={class:"text-right font-bold"},dr={class:"space-y-6"},fr=["onClick"],hr={class:"ml-auto badge badge-sm"},vr={key:0,class:"card-body"},mr={key:0,class:"text-center py-8"},pr={key:1,class:"space-y-6"},gr={key:0,class:"bg-base-200 p-4 rounded-lg"},br={class:"grid grid-cols-3 gap-4"},yr={class:"text-center"},_r={class:"text-2xl font-bold text-primary"},wr={class:"text-center"},xr={class:"text-2xl font-bold text-primary"},zr={class:"text-center"},kr={class:"text-2xl font-bold text-primary"},Sr={class:"grid grid-cols-1 md:grid-cols-3 gap-4"},$r={class:"card-body p-4"},Cr={class:"text-xs text-base-content/70 font-bold"},Pr={class:"font-bold text-lg"},Lr={key:0,class:"badge badge-warning"},Rr={class:"space-y-2 text-sm"},Er={class:"flex justify-between"},Or={key:0,class:"text-xs text-base-content/60"},Mr={class:"badge badge-sm"},Nr={class:"flex justify-between"},Ar={key:0,class:"text-xs text-base-content/60"},Dr={class:"badge badge-sm"},jr={class:"flex justify-between"},Ir={key:0,class:"text-xs text-base-content/60"},Tr={class:"badge badge-sm"},qr={class:"flex justify-between pt-2 border-t"},Fr={class:"badge badge-sm"},Ur={class:"flex justify-between pt-2 border-t"},Br={class:"badge badge-primary"},Vr={class:"overflow-x-auto"},Gr={class:"table table-zebra w-full table-sm"},Wr={class:"text-center"},Hr={key:0,class:"text-xs text-base-content/60 block"},Jr={class:"text-center"},Kr={key:0,class:"text-xs text-base-content/60 block"},Yr={class:"text-center"},Zr={key:0,class:"text-xs text-base-content/60 block"},Qr={class:"font-bold"},Xr={key:0,class:"badge badge-warning"},el={key:1,class:"badge"},tl={key:2,class:"badge"},sl={key:3},nl={class:"font-medium"},ol={class:"text-center"},al={key:0,class:"badge badge-sm"},rl={key:1,class:"text-base-content/40"},ll={class:"text-center"},il={key:0,class:"badge badge-sm"},cl={key:1,class:"text-base-content/40"},ul={class:"text-center"},dl={key:0,class:"badge badge-sm"},fl={key:1,class:"text-base-content/40"},hl={class:"text-center"},vl={key:0,class:"badge badge-sm"},ml={key:1,class:"text-base-content/40"},pl={class:"text-right font-bold text-primary text-lg"},gl=pe({__name:"Results",setup(n){const a=I(!0),s=I(null),t=I("overall"),o=I(null),r=I({username:"Player",rank:null,totalPoints:0,puzzlesSolved:0,isStaff:!1}),u=async()=>{a.value=!0;try{const $=await fetch("/api/results/results");if(!$.ok)throw new Error("Failed to fetch results");s.value=await $.json()}catch($){console.error("Error fetching results:",$)}finally{a.value=!1}},d=()=>s.value?s.value.users.map(l=>{const p=s.value.responses_by_userid[l.id]||[],z=p.reduce((i,c)=>i+(c.rank_points||0),0),b=p.length;return{user:l,totalPoints:z,puzzlesSolved:b}}).sort((l,p)=>p.totalPoints-l.totalPoints):[],g=$=>s.value?(s.value.ranking_by_puzzle[$]||[]).map(p=>({user:s.value.users.find(b=>b.id===p.user_id),cost:p.final_cost,cycles:p.final_cycles,area:p.final_area,points:p.points,rank_points:p.rank_points||0})).reverse():[],w=$=>{o.value=o.value===$?null:$},x=async()=>{try{const $=await fetch("/api/cache/clear",{method:"POST"});if($.ok)alert("Cache cleared successfully!"),await u();else{const l=await $.json();alert(`Error clearing cache: ${l.detail||"Unknown error"}`)}}catch($){console.error("Error clearing cache:",$),alert("Error clearing cache. Please try again.")}},P=async()=>{try{const $=await fetch("/api/user");if($.ok){const l=await $.json();if(l.is_authenticated){r.value.username=l.username,r.value.isStaff=l.is_staff||!1,await u();const p=d(),z=p.findIndex(b=>b.user.id===l.id);z!==-1&&(r.value.rank=z+1,r.value.totalPoints=p[z].totalPoints,r.value.puzzlesSolved=p[z].puzzlesSolved)}}}catch($){console.error("Error loading user data:",$),await u()}};return ot(()=>{P()}),($,l)=>(f(),h("div",Ma,[e("div",Na,[e("div",Aa,[e("div",Da,[l[9]||(l[9]=e("div",{class:"bg-gradient-to-br from-blue-600 to-blue-400 p-6 text-white rounded-t-2xl"},[e("i",{class:"mdi mdi-trophy text-4xl"}),e("h3",{class:"text-2xl font-bold mt-2"},"Your Ranking")],-1)),e("div",ja,[e("div",Ia,[l[2]||(l[2]=e("p",{class:"text-sm text-base-content/70"},"Player",-1)),e("p",Ta,y(r.value.username),1)]),l[8]||(l[8]=e("div",{class:"divider"},null,-1)),a.value?(f(),h("div",qa,[...l[3]||(l[3]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):(f(),h("div",Fa,[e("div",Ua,[l[4]||(l[4]=e("p",{class:"text-sm text-base-content/70 mb-1"},"Current Rank",-1)),r.value.rank!==null?(f(),h("p",Ba,[ve(ft,{rank:r.value.rank},null,8,["rank"])])):(f(),h("p",Va,"No rank yet"))]),e("div",Ga,[l[5]||(l[5]=e("p",{class:"text-sm text-base-content/70 mb-1"},"Total Points",-1)),e("p",Wa,y(r.value.totalPoints.toLocaleString()),1)]),e("div",Ha,[l[6]||(l[6]=e("p",{class:"text-sm text-base-content/70 mb-1"},"Puzzles Solved",-1)),e("p",Ja,y(r.value.puzzlesSolved),1)]),r.value.isStaff?(f(),h("button",{key:0,onClick:x,class:"btn btn-error btn-sm w-full mt-6"},[...l[7]||(l[7]=[e("i",{class:"mdi mdi-cache-clear mr-1"},null,-1),A(" Clear Cache ",-1)])])):R("",!0)]))])])]),e("div",Ka,[e("div",Ya,[e("div",Za,[l[37]||(l[37]=e("h2",{class:"card-title text-2xl mb-6"},[e("i",{class:"mdi mdi-trophy text-yellow-500 mr-2"}),A(" General Results ")],-1)),a.value?(f(),h("div",Qa,[...l[10]||(l[10]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):s.value?(f(),h("div",er,[e("div",tr,[e("button",{onClick:l[0]||(l[0]=p=>t.value="overall"),class:oe(["tab",t.value==="overall"?"tab-active":""])},[...l[12]||(l[12]=[e("i",{class:"mdi mdi-chart-line mr-2"},null,-1),A(" Overall Ranking ",-1)])],2),e("button",{onClick:l[1]||(l[1]=p=>t.value="byPuzzle"),class:oe(["tab",t.value==="byPuzzle"?"tab-active":""])},[...l[13]||(l[13]=[e("i",{class:"mdi mdi-puzzle mr-2"},null,-1),A(" By Puzzle ",-1)])],2)]),ce(e("div",sr,[d().length===0?(f(),h("div",nr,[...l[14]||(l[14]=[e("p",{class:"text-base-content/70"},"No submissions yet",-1)])])):(f(),h("div",or,[e("table",ar,[l[15]||(l[15]=e("thead",null,[e("tr",null,[e("th",null,"Rank"),e("th",null,"Player"),e("th",{class:"text-right"},"Puzzles Solved"),e("th",{class:"text-right"},"Total Points")])],-1)),e("tbody",null,[(f(!0),h(Q,null,ee(d(),(p,z)=>(f(),h("tr",{key:p.user.username},[e("td",rr,[ve(ft,{rank:z+1},null,8,["rank"])]),e("td",lr,[A(y(p.user.username)+" ",1),p.user.is_staff?(f(),h("span",ir," admin ")):R("",!0)]),e("td",cr,y(p.puzzlesSolved),1),e("td",ur,y(p.totalPoints),1)]))),128))])])]))],512),[[dt,t.value==="overall"]]),ce(e("div",dr,[(f(!0),h(Q,null,ee(s.value.puzzles,p=>(f(),h("div",{key:p.id,class:"card bg-base-100 border border-base-300"},[e("button",{onClick:z=>w(p.id),class:"btn btn-ghost btn-lg w-full justify-start text-lg font-bold hover:bg-primary/20 rounded-b-none"},[e("i",{class:oe(["mdi mr-2",o.value===p.id?"mdi-chevron-down":"mdi-chevron-right"])},null,2),A(" "+y(p.title)+" ",1),e("span",hr,y(g(p.id).length)+" submissions ",1)],8,fr),o.value===p.id?(f(),h("div",vr,[g(p.id).length===0?(f(),h("div",mr,[...l[16]||(l[16]=[e("p",{class:"text-base-content/70 text-lg"},"No submissions yet",-1)])])):(f(),h("div",pr,[p.points_factor?(f(),h("div",gr,[l[23]||(l[23]=e("p",{class:"text-sm text-base-content/70 mb-3 font-semibold"},"Points Coefficients",-1)),e("div",br,[e("div",yr,[e("span",_r,[l[17]||(l[17]=e("small",null,"x",-1)),A(y(p.points_factor.cost),1)]),l[18]||(l[18]=e("p",{class:"text-xs text-base-content/70"},"Cost",-1))]),e("div",wr,[e("span",xr,[l[19]||(l[19]=e("small",null,"x",-1)),A(y(p.points_factor.cycles),1)]),l[20]||(l[20]=e("p",{class:"text-xs text-base-content/70"},"Cycles",-1))]),e("div",zr,[e("span",kr,[l[21]||(l[21]=e("small",null,"x",-1)),A(y(p.points_factor.area),1)]),l[22]||(l[22]=e("p",{class:"text-xs text-base-content/70"},"Area",-1))])])])):R("",!0),e("div",Sr,[(f(!0),h(Q,null,ee(g(p.id).slice(0,3),(z,b)=>(f(),h("div",{key:b,class:"card bg-base-200"},[e("div",$r,[e("div",Cr,y(b===0?"🏆 1st Place":b===1?"🥈 2nd Place":"🥉 3rd Place"),1),e("h4",Pr,[A(y(z.user.username)+" ",1),z.user.is_staff?(f(),h("span",Lr," admin ")):R("",!0)]),l[29]||(l[29]=e("div",{class:"divider my-2"},null,-1)),e("div",Rr,[e("div",Er,[e("span",null,[l[24]||(l[24]=A("Cost",-1)),p.points_factor?(f(),h("span",Or," (x"+y(p.points_factor.cost)+") ",1)):R("",!0)]),e("span",Mr,y(z.cost||"N/A"),1)]),e("div",Nr,[e("span",null,[l[25]||(l[25]=A("Cycles",-1)),p.points_factor?(f(),h("span",Ar," (x"+y(p.points_factor.cycles)+") ",1)):R("",!0)]),e("span",Dr,y(z.cycles||"N/A"),1)]),e("div",jr,[e("span",null,[l[26]||(l[26]=A("Area",-1)),p.points_factor?(f(),h("span",Ir," (x"+y(p.points_factor.area)+") ",1)):R("",!0)]),e("span",Tr,y(z.area||"N/A"),1)]),e("div",qr,[l[27]||(l[27]=e("span",null,"Total (with coef.)",-1)),e("span",Fr,y(z.points||"N/A"),1)]),e("div",Ur,[l[28]||(l[28]=e("span",{class:"font-bold"},"Points",-1)),e("span",Br,y(z.rank_points)+" pts",1)])])])]))),128))]),e("div",Vr,[e("table",Gr,[e("thead",null,[e("tr",null,[l[33]||(l[33]=e("th",{class:"w-12"},"Rank",-1)),l[34]||(l[34]=e("th",null,"Player",-1)),e("th",Wr,[l[30]||(l[30]=A(" Cost ",-1)),p.points_factor?(f(),h("span",Hr,"(x"+y(p.points_factor.cost)+")",1)):R("",!0)]),e("th",Jr,[l[31]||(l[31]=A(" Cycles ",-1)),p.points_factor?(f(),h("span",Kr,"(x"+y(p.points_factor.cycles)+")",1)):R("",!0)]),e("th",Yr,[l[32]||(l[32]=A(" Area ",-1)),p.points_factor?(f(),h("span",Zr,"(x"+y(p.points_factor.area)+")",1)):R("",!0)]),l[35]||(l[35]=e("th",{class:"text-center"},"Total (with coef.)",-1)),l[36]||(l[36]=e("th",{class:"text-right"},"Points",-1))])]),e("tbody",null,[(f(!0),h(Q,null,ee(g(p.id),(z,b)=>(f(),h("tr",{key:b,class:oe({"bg-primary/10":b<3})},[e("td",Qr,[b===0?(f(),h("span",Xr,"🏆")):b===1?(f(),h("span",el,"🥈")):b===2?(f(),h("span",tl,"🥉")):(f(),h("span",sl,"#"+y(b+1),1))]),e("td",nl,y(z.user.username),1),e("td",ol,[z.cost?(f(),h("span",al,y(z.cost),1)):(f(),h("span",rl,""))]),e("td",ll,[z.cycles?(f(),h("span",il,y(z.cycles),1)):(f(),h("span",cl,""))]),e("td",ul,[z.area?(f(),h("span",dl,y(z.area),1)):(f(),h("span",fl,""))]),e("td",hl,[z.points?(f(),h("span",vl,y(z.points),1)):(f(),h("span",ml,""))]),e("td",pl,y(z.rank_points),1)],2))),128))])])])]))])):R("",!0)]))),128))],512),[[dt,t.value==="byPuzzle"]])])):(f(),h("div",Xa,[...l[11]||(l[11]=[e("p",{class:"text-base-content/70"},"No results available yet",-1)])]))])])])])]))}});function qt(n,a){return Gt()?(Wt(n,a),!0):!1}const Ft=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;function bl(n,a=1e3,s={}){const{immediate:t=!0,immediateCallback:o=!1}=s;let r=null;const u=Jt(!1);function d(){r&&(clearInterval(r),r=null)}function g(){u.value=!1,d()}function w(){const x=ke(a);x<=0||(u.value=!0,o&&n(),d(),u.value&&(r=setInterval(n,x)))}return t&&Ft&&w(),(me(a)||typeof a=="function")&&qt($e(a,()=>{u.value&&Ft&&w()})),qt(g),{isActive:bs(u),pause:g,resume:w}}function yl(n,a){var s,t;const o=Jt(ke(n)),r=bl(()=>{var x;const P=o.value-1;if(o.value=P<0?0:P,a==null||(x=a.onTick)===null||x===void 0||x.call(a),o.value<=0){var $;r.pause(),a==null||($=a.onComplete)===null||$===void 0||$.call(a)}},(s=a?.interval)!==null&&s!==void 0?s:1e3,{immediate:(t=a?.immediate)!==null&&t!==void 0?t:!1}),u=x=>{var P;o.value=(P=ke(x))!==null&&P!==void 0?P:ke(n)},d=()=>{r.pause(),u()},g=()=>{r.isActive.value||o.value>0&&r.resume()};return{remaining:o,reset:u,stop:d,start:x=>{u(x),r.resume()},pause:r.pause,resume:g,isActive:r.isActive}}const _l={class:"min-h-screen bg-base-200"},wl={class:"navbar bg-base-100 shadow-lg"},xl={class:"container mx-auto w-full flex items-center gap-4"},zl={class:"flex items-center gap-4"},kl={key:0,class:"flex items-center gap-2"},Sl={class:"text-sm"},$l={class:"font-medium"},Cl={key:0,class:"badge badge-warning badge-xs ml-1"},Pl={key:1,class:"text-sm text-base-content/70"},Ll={class:"container mx-auto px-4 py-8"},Rl={key:0,class:"flex justify-center"},El={class:"text-center"},Ol={class:"mb-6 text-base-content/70"},Ml={key:1,class:"flex justify-center items-center min-h-[400px]"},Nl={key:2,class:"alert alert-error max-w-2xl mx-auto"},Al={class:"text-sm"},Dl={key:3,class:"space-y-8"},jl={class:"mb-8"},Il={class:"card bg-base-100 shadow-lg"},Tl={class:"card-body"},ql={class:"card-title text-2xl"},Fl={class:"text-base-content/70"},Ul={class:"flex flex-wrap gap-4 mt-4"},Bl={key:0},Vl={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"},Gl={key:1,class:"text-center py-12"},Wl={key:0,class:"modal modal-open"},Hl={class:"modal-box max-w-6xl"},Jl={class:"flex justify-between items-center mb-4"},Kl=pe({__name:"OpusMagnum",props:{collectionTitle:{},collectionUrl:{},collectionDescription:{}},setup(n){const a=n,s=Pe(),t=lt(),{submissions:o,isSubmissionModalOpen:r}=rt(t),{openSubmissionModal:u,loadSubmissions:d,closeSubmissionModal:g}=t,w=I(null),x=I(!0),P=I(""),$=ne(()=>w.value?.is_superuser||!1),l=ne(()=>{const C={};return o.value.forEach(S=>{S.responses.forEach(q=>{C[q.puzzle_id]||(C[q.puzzle_id]=[]),C[q.puzzle_id].push(q)})}),C});async function p(){try{x.value=!0,P.value="",console.log("Starting data load..."),console.log("Loading user info...");const C=await re.getUserInfo();C.data?(w.value=C.data,console.log("User info loaded:",C.data)):C.error&&console.warn("User info error:",C.error),console.log("Loading puzzles..."),await s.loadPuzzles(),console.log("Puzzles loaded:",s.puzzles.length),console.log("Loading submissions..."),await d(),console.log("Submissions loaded:",o.value.length),console.log("Data load complete!")}catch(C){P.value=Xt.getErrorMessage(C),console.error("Failed to load data:",C)}finally{x.value=!1,console.log("Loading state set to false")}w.value?.is_superuser&&b()}const{remaining:z,start:b}=yl(60,{onComplete(){p()}});ot(async()=>{await p()});const i=C=>s.findPuzzleByName(C),c=()=>{window.location.reload()},v=()=>{window.location.href="/"};return(C,S)=>(f(),h("div",_l,[e("div",wl,[e("div",xl,[e("button",{onClick:v,class:"btn btn-primary btn-sm"},[...S[3]||(S[3]=[e("i",{class:"mdi mdi-arrow-left"},null,-1),A(" Back ",-1)])]),S[6]||(S[6]=e("h1",{class:"text-xl font-bold"},"Opus Magnum Puzzle Submitter",-1)),S[7]||(S[7]=e("div",{class:"flex-1"},null,-1)),e("div",zl,[w.value?.is_authenticated?(f(),h("div",kl,[e("div",Sl,[e("span",$l,y(w.value.username),1),w.value.is_superuser?(f(),h("span",Cl,"Admin")):R("",!0)])])):(f(),h("div",Pl,"Not logged in")),S[4]||(S[4]=e("a",{href:"/api/docs",class:"btn btn-xs"},"API docs",-1)),S[5]||(S[5]=e("a",{href:"/admin",class:"btn btn-xs btn-warning"},"Admin panel",-1))])])]),e("div",Ll,[w.value?.is_superuser?(f(),h("div",Rl,[e("div",El,[e("p",Ol,[S[8]||(S[8]=e("span",{class:"loading loading-spinner loading-lg"},null,-1)),A(" Auto reload page in "+y(T(z))+" seconds ... ",1)])])])):R("",!0),x.value?(f(),h("div",Ml,[...S[9]||(S[9]=[e("div",{class:"text-center"},[e("span",{class:"loading loading-spinner loading-lg"}),e("p",{class:"mt-4 text-base-content/70"},"Loading puzzles...")],-1)])])):P.value?(f(),h("div",Nl,[S[12]||(S[12]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",null,[S[10]||(S[10]=e("h3",{class:"font-bold"},"Error Loading Data",-1)),e("div",Al,y(P.value),1)]),e("button",{onClick:c,class:"btn btn-sm btn-outline"},[...S[11]||(S[11]=[e("i",{class:"mdi mdi-refresh mr-1"},null,-1),A(" Retry ",-1)])])])):(f(),h("div",Dl,[e("div",jl,[e("div",Il,[e("div",Tl,[e("h2",ql,y(a.collectionTitle),1),e("p",Fl,y(a.collectionDescription),1),e("div",Ul,[e("button",{onClick:S[0]||(S[0]=(...q)=>T(u)&&T(u)(...q)),class:"btn btn-primary"},[...S[13]||(S[13]=[e("i",{class:"mdi mdi-plus mr-2"},null,-1),A(" Submit Solution ",-1)])])])])])]),ve(gl),$.value?(f(),h("div",Bl,[ve(Oa)])):R("",!0),e("div",Vl,[(f(!0),h(Q,null,ee(T(s).puzzles,q=>(f(),ys(dn,{key:q.id,puzzle:q,responses:l.value[q.id]||[]},null,8,["puzzle","responses"]))),128))]),T(s).puzzles.length===0?(f(),h("div",Gl,[...S[14]||(S[14]=[e("div",{class:"text-6xl mb-4"},"🧩",-1),e("h3",{class:"text-xl font-bold mb-2"},"No Puzzles Available",-1),e("p",{class:"text-base-content/70"}," Check back later for new puzzle collections! ",-1)])])):R("",!0)]))]),T(r)?(f(),h("div",Wl,[e("div",Hl,[e("div",Jl,[S[16]||(S[16]=e("h3",{class:"font-bold text-lg"},"Submit Solution",-1)),e("button",{onClick:S[1]||(S[1]=(...q)=>T(g)&&T(g)(...q)),class:"btn btn-sm btn-circle btn-ghost"},[...S[15]||(S[15]=[e("i",{class:"mdi mdi-close"},null,-1)])])]),ve(Uo,{puzzles:T(s).puzzles,"find-puzzle-by-name":i},null,8,["puzzles"])]),e("div",{class:"modal-backdrop",onClick:S[2]||(S[2]=(...q)=>T(g)&&T(g)(...q))})])):R("",!0)]))}}),Yl=ws(),os="#app",Zl=document.querySelector(os),as=_s(Kl,{...Zl?.dataset});as.use(Yl);as.mount(os);