opus-submitter/polylan_submitter/static_source/vite/assets/opus_magnum-BftkLCBu.js

6 lines
86 KiB
JavaScript

import{e as Ut,r as M,m as Bt,t as Vt,c as te,i as ge,a as ot,b as us,d as fs,h as hs,f as ms,g as Gt,o as Wt,w as Ce,n as Se,j as vs,k as he,l as d,p as c,q as ae,s as e,u as L,v as g,x as E,F as U,y as J,z as q,A as et,B as gs,C as ce,D as Ht,E as fe,G as ze,H as ps,I as we,J as ut,K as Jt,L as bs,M as $e,N as ys,O as _s}from"./style-BKSucaDP.js";import{_ as ft}from"./RankBadge.vue_vue_type_script_setup_true_lang-c__WwHxT.js";/*!
* pinia v3.0.3
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/let Kt;const Pe=n=>Kt=n,Yt=Symbol();function tt(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var xe;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(xe||(xe={}));function xs(){const n=Ut(!0),a=n.run(()=>M({}));let s=[],t=[];const o=Bt({install(r){Pe(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 ve(n,...a){n.slice().forEach(s=>{s(...a)})}const ws=n=>n(),mt=Symbol(),Ee=Symbol();function st(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];tt(o)&&tt(t)&&n.hasOwnProperty(s)&&!ge(t)&&!ot(t)?n[s]=st(o,t):n[s]=t}return n}const ks=Symbol();function zs(n){return!tt(n)||!Object.prototype.hasOwnProperty.call(n,ks)}const{assign:ue}=Object;function $s(n){return!!(ge(n)&&n.effect)}function Ss(n,a,s,t){const{state:o,actions:r,getters:u}=a,m=s.state.value[n];let p;function w(){m||(s.state.value[n]=o?o():{});const k=vs(s.state.value[n]);return ue(k,r,Object.keys(u||{}).reduce((S,x)=>(S[x]=Bt(te(()=>{Pe(s);const l=s._s.get(n);return u[x].call(l,l)})),S),{}))}return p=Qt(n,w,a,s,t,!0),p}function Qt(n,a,s={},t,o,r){let u;const m=ue({actions:{}},s),p={deep:!0};let w,k,S=[],x=[],l;const i=t.state.value[n];!r&&!i&&(t.state.value[n]={}),M({});let y;function v(R){let j;w=k=!1,typeof R=="function"?(R(t.state.value[n]),j={type:xe.patchFunction,storeId:n,events:l}):(st(t.state.value[n],R),j={type:xe.patchObject,payload:R,storeId:n,events:l});const B=y=Symbol();Se().then(()=>{y===B&&(w=!0)}),k=!0,ve(S,j,t.state.value[n])}const f=r?function(){const{state:j}=s,B=j?j():{};this.$patch(Y=>{ue(Y,B)})}:Zt;function h(){u.stop(),S=[],x=[],t._s.delete(n)}const b=(R,j="")=>{if(mt in R)return R[Ee]=j,R;const B=function(){Pe(t);const Y=Array.from(arguments),le=[],de=[];function pe(V){le.push(V)}function se(V){de.push(V)}ve(x,{args:Y,name:B[Ee],store:D,after:pe,onError:se});let oe;try{oe=R.apply(this&&this.$id===n?this:D,Y)}catch(V){throw ve(de,V),V}return oe instanceof Promise?oe.then(V=>(ve(le,V),V)).catch(V=>(ve(de,V),Promise.reject(V))):(ve(le,oe),oe)};return B[mt]=!0,B[Ee]=j,B},O={_p:t,$id:n,$onAction:ht.bind(null,x),$patch:v,$reset:f,$subscribe(R,j={}){const B=ht(S,R,j.detached,()=>Y()),Y=u.run(()=>Ce(()=>t.state.value[n],le=>{(j.flush==="sync"?k:w)&&R({storeId:n,type:xe.direct,events:l},le)},ue({},p,j)));return B},$dispose:h},D=ms(O);t._s.set(n,D);const C=(t._a&&t._a.runWithContext||ws)(()=>t._e.run(()=>(u=Ut()).run(()=>a({action:b}))));for(const R in C){const j=C[R];if(ge(j)&&!$s(j)||ot(j))r||(i&&zs(j)&&(ge(j)?j.value=i[R]:st(j,i[R])),t.state.value[n][R]=j);else if(typeof j=="function"){const B=b(j,R);C[R]=B,m.actions[R]=j}}return ue(D,C),ue(Vt(D),C),Object.defineProperty(D,"$state",{get:()=>t.state.value[n],set:R=>{v(j=>{ue(j,R)})}}),t._p.forEach(R=>{ue(D,u.run(()=>R({store:D,app:t._a,pinia:t,options:m})))}),i&&r&&s.hydrate&&s.hydrate(D.$state,i),w=!0,k=!0,D}/*! #__NO_SIDE_EFFECTS__ */function at(n,a,s){let t;const o=typeof a=="function";t=o?s:a;function r(u,m){const p=hs();return u=u||(p?fs(Yt,null):null),u&&Pe(u),u=Kt,u._s.has(n)||(o?Qt(n,a,t,u):Ss(n,t,u)),u._s.get(n)}return r.$id=n,r}function lt(n){const a=Vt(n),s={};for(const t in a){const o=a[t];o.effect?s[t]=te({get:()=>n[t],set(r){n[t]=r}}):(ge(o)||ot(o))&&(s[t]=us(n,t))}return s}const vt="/api";class Cs{async request(a,s={}){try{const t=await fetch(`${vt}${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(`${vt}${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 getCollection(){return this.request("/submissions/collection")}async getTopSubmissions(a=5){return this.request(`/results/top-submissions?limit=${a}`)}async getPuzzleResults(a=5){return this.request(`/results/puzzle-results?limit=${a}`)}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 ne=new Cs,Ps={async loadPuzzles(){const n=await ne.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}},gt={async createFromFiles(n,a,s,t){const o=n.map(u=>{const m=Ps.findPuzzleByName(a,u.ocrData?.puzzle||"");if(m)return{puzzle_id:m.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 ne.createSubmission({notes:s,manual_validation_requested:t,responses:o},r)},async loadSubmissions(n=20,a=0){const s=await ne.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}},Le=at("puzzles",()=>{const n=M([]),a=M(!1),s=M(""),t=te(()=>n.value.map(m=>m.title)),o=te(()=>m=>{if(!m)return null;const p=n.value.find(k=>k.title.toLowerCase()===m.toLowerCase());return p||n.value.find(k=>k.title.toLowerCase().includes(m.toLowerCase())||m.toLowerCase().includes(k.title.toLowerCase()))||null}),r=async()=>{if(!(n.value.length>0))try{a.value=!0,s.value="";const m=await ne.getPuzzles();if(m.error){s.value=m.error,console.error("Failed to load puzzles:",m.error);return}m.data&&(n.value=m.data)}catch(m){s.value="Failed to load puzzles",console.error("Error loading puzzles:",m)}finally{a.value=!1}};return{puzzles:n,isLoading:a,error:s,puzzleNames:t,findPuzzleByName:o,loadPuzzles:r,refreshPuzzles:async()=>{n.value=[],await r()}}}),rt=at("submissions",()=>{const n=M([]),a=M(!1),s=M(""),t=M(!1),o=Le(),{puzzles:r}=lt(o),u=async(x=20,l=0)=>{try{a.value=!0,s.value="";const i=await gt.loadSubmissions(x,l);l===0?n.value=i:n.value.push(...i)}catch(i){s.value="Failed to load submissions",console.error("Error loading submissions:",i)}finally{a.value=!1}},m=async(x,l,i)=>{try{a.value=!0,s.value="";const y=await gt.createFromFiles(x,r.value,l,i);if(y.error)throw s.value=y.error,new Error(y.error);return y.data?(n.value.unshift(y.data),y.data):void 0}catch(y){throw s.value=y instanceof Error?y.message:"Failed to create submission",y}finally{a.value=!1}},p=()=>{t.value=!0},w=()=>{t.value=!1};return{submissions:n,isLoading:a,error:s,isSubmissionModalOpen:t,loadSubmissions:u,createSubmission:m,openSubmissionModal:p,closeSubmissionModal:w,refreshSubmissions:async()=>{n.value=[],await u()},handleSubmission:async x=>{try{a.value=!0,s.value="";const l=await m(x.files,x.notes,x.manualValidationRequested);if(l){const i=l.responses.map(y=>y.puzzle_name).join(", ");alert(`Solutions submitted successfully for puzzles: ${i}`)}else alert("Submission created successfully!");w()}catch(l){const i=Xt.getErrorMessage(l);s.value=i,alert(`Submission failed: ${i}`),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"},ln={class:"flex items-center gap-1"},rn={class:"badge badge-ghost badge-xs"},cn=["data-tip"],dn={key:1,class:"tooltip","data-tip":"Needs manual validation"},un=he({__name:"PuzzleCard",props:{puzzle:{},responses:{}},setup(n){const{openSubmissionModal:a}=rt();return(s,t)=>(c(),d("div",{class:ae(["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:ae(["card-title text-lg font-bold",n.responses?.length==0?"text-error":"text-primary"])},g(n.puzzle.title),3),e("p",Os," by "+g(n.puzzle.author_name),1),e("div",Ms,[e("div",Ns,g(n.puzzle.steam_item_id),1),e("div",As,"ID: "+g(n.puzzle.id),1)]),n.puzzle.description?(c(),d("p",Ds,g(n.puzzle.description),1)):L("",!0),n.puzzle.points_factor?(c(),d("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)),E(g(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)),E(g(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)),E(g(n.puzzle.points_factor.area),1)]),t[6]||(t[6]=e("p",{class:"text-xs text-base-content/70"},"Area",-1))])])])):L("",!0),n.puzzle.tags&&n.puzzle.tags.length>0?(c(),d("div",Gs,[(c(!0),d(U,null,J(n.puzzle.tags.slice(0,3),o=>(c(),d("span",{key:o,class:"badge badge-outline badge-xs"},g(o),1))),128)),n.puzzle.tags.length>3?(c(),d("span",Ws," +"+g(n.puzzle.tags.length-3)+" more ",1)):L("",!0)])):L("",!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?(c(),d("div",Ys,[e("div",Zs,[e("span",Qs,"Solutions ("+g(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,[(c(!0),d(U,null,J(n.responses,o=>(c(),d("tr",{key:o.id,class:"hover"},[e("td",null,[o.final_cost||o.cost?(c(),d("span",en,g(o.final_cost||o.cost),1)):(c(),d("span",tn,"-"))]),e("td",null,[o.final_cycles||o.cycles?(c(),d("span",sn,g(o.final_cycles||o.cycles),1)):(c(),d("span",nn,"-"))]),e("td",null,[o.final_area||o.area?(c(),d("span",on,g(o.final_area||o.area),1)):(c(),d("span",an,"-"))]),e("td",null,[e("div",ln,[e("span",rn,g(o.files?.length||0),1),o.files?.length?(c(),d("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)):L("",!0),o.needs_manual_validation?(c(),d("div",dn,[...t[10]||(t[10]=[e("i",{class:"mdi mdi-alert-circle text-xs text-warning"},null,-1)])])):L("",!0)])])]))),128))])])])])):(c(),d("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)=>q(a)&&q(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 Oe={exports:{}},pt;function fn(){return pt||(pt=1,(function(n){var a=(function(s){var t=Object.prototype,o=t.hasOwnProperty,r=Object.defineProperty||function(z,_,$){z[_]=$.value},u,m=typeof Symbol=="function"?Symbol:{},p=m.iterator||"@@iterator",w=m.asyncIterator||"@@asyncIterator",k=m.toStringTag||"@@toStringTag";function S(z,_,$){return Object.defineProperty(z,_,{value:$,enumerable:!0,configurable:!0,writable:!0}),z[_]}try{S({},"")}catch{S=function(_,$,N){return _[$]=N}}function x(z,_,$,N){var P=_&&_.prototype instanceof b?_:b,T=Object.create(P.prototype),K=new oe(N||[]);return r(T,"_invoke",{value:le(z,$,K)}),T}s.wrap=x;function l(z,_,$){try{return{type:"normal",arg:z.call(_,$)}}catch(N){return{type:"throw",arg:N}}}var i="suspendedStart",y="suspendedYield",v="executing",f="completed",h={};function b(){}function O(){}function D(){}var F={};S(F,p,function(){return this});var C=Object.getPrototypeOf,R=C&&C(C(V([])));R&&R!==t&&o.call(R,p)&&(F=R);var j=D.prototype=b.prototype=Object.create(F);O.prototype=D,r(j,"constructor",{value:D,configurable:!0}),r(D,"constructor",{value:O,configurable:!0}),O.displayName=S(D,k,"GeneratorFunction");function B(z){["next","throw","return"].forEach(function(_){S(z,_,function($){return this._invoke(_,$)})})}s.isGeneratorFunction=function(z){var _=typeof z=="function"&&z.constructor;return _?_===O||(_.displayName||_.name)==="GeneratorFunction":!1},s.mark=function(z){return Object.setPrototypeOf?Object.setPrototypeOf(z,D):(z.__proto__=D,S(z,k,"GeneratorFunction")),z.prototype=Object.create(j),z},s.awrap=function(z){return{__await:z}};function Y(z,_){function $(T,K,W,X){var G=l(z[T],z,K);if(G.type==="throw")X(G.arg);else{var be=G.arg,me=be.value;return me&&typeof me=="object"&&o.call(me,"__await")?_.resolve(me.__await).then(function(re){$("next",re,W,X)},function(re){$("throw",re,W,X)}):_.resolve(me).then(function(re){be.value=re,W(be)},function(re){return $("throw",re,W,X)})}}var N;function P(T,K){function W(){return new _(function(X,G){$(T,K,X,G)})}return N=N?N.then(W,W):W()}r(this,"_invoke",{value:P})}B(Y.prototype),S(Y.prototype,w,function(){return this}),s.AsyncIterator=Y,s.async=function(z,_,$,N,P){P===void 0&&(P=Promise);var T=new Y(x(z,_,$,N),P);return s.isGeneratorFunction(_)?T:T.next().then(function(K){return K.done?K.value:T.next()})};function le(z,_,$){var N=i;return function(T,K){if(N===v)throw new Error("Generator is already running");if(N===f){if(T==="throw")throw K;return Q()}for($.method=T,$.arg=K;;){var W=$.delegate;if(W){var X=de(W,$);if(X){if(X===h)continue;return X}}if($.method==="next")$.sent=$._sent=$.arg;else if($.method==="throw"){if(N===i)throw N=f,$.arg;$.dispatchException($.arg)}else $.method==="return"&&$.abrupt("return",$.arg);N=v;var G=l(z,_,$);if(G.type==="normal"){if(N=$.done?f:y,G.arg===h)continue;return{value:G.arg,done:$.done}}else G.type==="throw"&&(N=f,$.method="throw",$.arg=G.arg)}}}function de(z,_){var $=_.method,N=z.iterator[$];if(N===u)return _.delegate=null,$==="throw"&&z.iterator.return&&(_.method="return",_.arg=u,de(z,_),_.method==="throw")||$!=="return"&&(_.method="throw",_.arg=new TypeError("The iterator does not provide a '"+$+"' method")),h;var P=l(N,z.iterator,_.arg);if(P.type==="throw")return _.method="throw",_.arg=P.arg,_.delegate=null,h;var T=P.arg;if(!T)return _.method="throw",_.arg=new TypeError("iterator result is not an object"),_.delegate=null,h;if(T.done)_[z.resultName]=T.value,_.next=z.nextLoc,_.method!=="return"&&(_.method="next",_.arg=u);else return T;return _.delegate=null,h}B(j),S(j,k,"Generator"),S(j,p,function(){return this}),S(j,"toString",function(){return"[object Generator]"});function pe(z){var _={tryLoc:z[0]};1 in z&&(_.catchLoc=z[1]),2 in z&&(_.finallyLoc=z[2],_.afterLoc=z[3]),this.tryEntries.push(_)}function se(z){var _=z.completion||{};_.type="normal",delete _.arg,z.completion=_}function oe(z){this.tryEntries=[{tryLoc:"root"}],z.forEach(pe,this),this.reset(!0)}s.keys=function(z){var _=Object(z),$=[];for(var N in _)$.push(N);return $.reverse(),function P(){for(;$.length;){var T=$.pop();if(T in _)return P.value=T,P.done=!1,P}return P.done=!0,P}};function V(z){if(z){var _=z[p];if(_)return _.call(z);if(typeof z.next=="function")return z;if(!isNaN(z.length)){var $=-1,N=function P(){for(;++$<z.length;)if(o.call(z,$))return P.value=z[$],P.done=!1,P;return P.value=u,P.done=!0,P};return N.next=N}}return{next:Q}}s.values=V;function Q(){return{value:u,done:!0}}return oe.prototype={constructor:oe,reset:function(z){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(se),!z)for(var _ in this)_.charAt(0)==="t"&&o.call(this,_)&&!isNaN(+_.slice(1))&&(this[_]=u)},stop:function(){this.done=!0;var z=this.tryEntries[0],_=z.completion;if(_.type==="throw")throw _.arg;return this.rval},dispatchException:function(z){if(this.done)throw z;var _=this;function $(X,G){return T.type="throw",T.arg=z,_.next=X,G&&(_.method="next",_.arg=u),!!G}for(var N=this.tryEntries.length-1;N>=0;--N){var P=this.tryEntries[N],T=P.completion;if(P.tryLoc==="root")return $("end");if(P.tryLoc<=this.prev){var K=o.call(P,"catchLoc"),W=o.call(P,"finallyLoc");if(K&&W){if(this.prev<P.catchLoc)return $(P.catchLoc,!0);if(this.prev<P.finallyLoc)return $(P.finallyLoc)}else if(K){if(this.prev<P.catchLoc)return $(P.catchLoc,!0)}else if(W){if(this.prev<P.finallyLoc)return $(P.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(z,_){for(var $=this.tryEntries.length-1;$>=0;--$){var N=this.tryEntries[$];if(N.tryLoc<=this.prev&&o.call(N,"finallyLoc")&&this.prev<N.finallyLoc){var P=N;break}}P&&(z==="break"||z==="continue")&&P.tryLoc<=_&&_<=P.finallyLoc&&(P=null);var T=P?P.completion:{};return T.type=z,T.arg=_,P?(this.method="next",this.next=P.finallyLoc,h):this.complete(T)},complete:function(z,_){if(z.type==="throw")throw z.arg;return z.type==="break"||z.type==="continue"?this.next=z.arg:z.type==="return"?(this.rval=this.arg=z.arg,this.method="return",this.next="end"):z.type==="normal"&&_&&(this.next=_),h},finish:function(z){for(var _=this.tryEntries.length-1;_>=0;--_){var $=this.tryEntries[_];if($.finallyLoc===z)return this.complete($.completion,$.afterLoc),se($),h}},catch:function(z){for(var _=this.tryEntries.length-1;_>=0;--_){var $=this.tryEntries[_];if($.tryLoc===z){var N=$.completion;if(N.type==="throw"){var P=N.arg;se($)}return P}}throw new Error("illegal catch attempt")},delegateYield:function(z,_,$){return this.delegate={iterator:V(z),resultName:_,nextLoc:$},this.method==="next"&&(this.arg=u),h}},s})(n.exports);try{regeneratorRuntime=a}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=a:Function("r","regeneratorRuntime = r")(a)}})(Oe)),Oe.exports}var Me,bt;function it(){return bt||(bt=1,Me=(n,a)=>`${n}-${a}-${Math.random().toString(16).slice(3,8)}`),Me}var Ne,yt;function es(){if(yt)return Ne;yt=1;const n=it();let a=0;return Ne=({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}},Ne}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 Ae,xt;function hn(){if(xt)return Ae;xt=1;const n=es(),{log:a}=ct(),s=it();let t=0;return Ae=()=>{const o=s("Scheduler",t),r={},u={};let m=[];t+=1;const p=()=>m.length,w=()=>Object.keys(r).length,k=()=>{if(m.length!==0){const y=Object.keys(r);for(let v=0;v<y.length;v+=1)if(typeof u[y[v]]>"u"){m[0](r[y[v]]);break}}},S=(y,v)=>new Promise((f,h)=>{const b=n({action:y,payload:v});m.push(async O=>{m.shift(),u[O.id]=b;try{f(await O[y].apply(this,[...v,b.id]))}catch(D){h(D)}finally{delete u[O.id],k()}}),a(`[${o}]: Add ${b.id} to JobQueue`),a(`[${o}]: JobQueue length=${m.length}`),k()});return{addWorker:y=>(r[y.id]=y,a(`[${o}]: Add ${y.id}`),a(`[${o}]: Number of workers=${w()}`),k(),y.id),addJob:async(y,...v)=>{if(w()===0)throw Error(`[${o}]: You need to have at least one worker before adding jobs`);return S(y,v)},terminate:async()=>{Object.keys(r).forEach(async y=>{await r[y].terminate()}),m=[]},getQueueLen:p,getNumWorkers:w}},Ae}function mn(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 De,wt;function vn(){if(wt)return De;wt=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 De=n,De}var je,kt;function gn(){if(kt)return je;kt=1;const n=vn();return je=a=>{const s={};return typeof WorkerGlobalScope<"u"?s.type="webworker":n()?s.type="electron":typeof document=="object"?s.type="browser":typeof process=="object"&&typeof mn=="function"&&(s.type="node"),typeof a>"u"?s:s[a]},je}var Ie,zt;function pn(){if(zt)return Ie;zt=1;const a=gn()("type")==="browser"?s=>new URL(s,window.location.href).href:s=>s;return Ie=s=>{const t={...s};return["corePath","workerPath","langPath"].forEach(o=>{s[o]&&(t[o]=a(t[o]))}),t},Ie}var Te,$t;function bn(){return $t||($t=1,Te=n=>{const a=[],s=[],t=[],o=[],r=[];return n.blocks&&n.blocks.forEach(u=>{u.paragraphs.forEach(m=>{m.lines.forEach(p=>{p.words.forEach(w=>{w.symbols.forEach(k=>{r.push({...k,page:n,block:u,paragraph:m,line:p,word:w})}),o.push({...w,page:n,block:u,paragraph:m,line:p})}),t.push({...p,page:n,block:u,paragraph:m})}),s.push({...m,page:n,block:u})}),a.push({...u,page:n})}),{...n,blocks:a,paragraphs:s,lines:t,words:o,symbols:r}}),Te}var qe,St;function ts(){return St||(St=1,qe={TESSERACT_ONLY:0,LSTM_ONLY:1,TESSERACT_LSTM_COMBINED:2,DEFAULT:3}),qe}const yn="5.1.1",_n={version:yn};var Fe,Ct;function xn(){return Ct||(Ct=1,Fe={workerBlobURL:!0,logger:()=>{}}),Fe}var Ue,Pt;function wn(){if(Pt)return Ue;Pt=1;const n=_n.version;return Ue={...xn(),workerPath:`https://cdn.jsdelivr.net/npm/tesseract.js@v${n}/dist/worker.min.js`},Ue}var Be,Lt;function kn(){return Lt||(Lt=1,Be=({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}),Be}var Ve,Rt;function zn(){return Rt||(Rt=1,Ve=n=>{n.terminate()}),Ve}var Ge,Et;function $n(){return Et||(Et=1,Ge=(n,a)=>{n.onmessage=({data:s})=>{a(s)}}),Ge}var We,Ot;function Sn(){return Ot||(Ot=1,We=async(n,a)=>{n.postMessage(a)}),We}var He,Mt;function Cn(){if(Mt)return He;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 He=a,He}var Je,Nt;function Pn(){if(Nt)return Je;Nt=1;const n=wn(),a=kn(),s=zn(),t=$n(),o=Sn(),r=Cn();return Je={defaultOptions:n,spawnWorker:a,terminateWorker:s,onMessage:t,send:o,loadImage:r},Je}var Ke,At;function ss(){if(At)return Ke;At=1;const n=pn(),a=bn(),s=es(),{log:t}=ct(),o=it(),r=ts(),{defaultOptions:u,spawnWorker:m,terminateWorker:p,onMessage:w,loadImage:k,send:S}=Pn();let x=0;return Ke=async(l="eng",i=r.LSTM_ONLY,y={},v={})=>{const f=o("Worker",x),{logger:h,errorHandler:b,...O}=n({...u,...y}),D={},F={},C=typeof l=="string"?l.split("+"):l;let R=i,j=v;const B=[r.DEFAULT,r.LSTM_ONLY].includes(i)&&!O.legacyCore;let Y,le;const de=new Promise((A,I)=>{le=A,Y=I}),pe=A=>{Y(A.message)};let se=m(O);se.onerror=pe,x+=1;const oe=(A,I)=>{D[A]=I},V=(A,I)=>{F[A]=I},Q=({id:A,action:I,payload:H})=>new Promise((ee,Z)=>{t(`[${f}]: Start ${A}, action=${I}`);const ie=`${I}-${A}`;oe(ie,ee),V(ie,Z),S(se,{workerId:f,jobId:A,action:I,payload:H})}),z=()=>console.warn("`load` is depreciated and should be removed from code (workers now come pre-loaded)"),_=A=>Q(s({id:A,action:"load",payload:{options:{lstmOnly:B,corePath:O.corePath,logging:O.logging}}})),$=(A,I,H)=>Q(s({id:H,action:"FS",payload:{method:"writeFile",args:[A,I]}})),N=(A,I)=>Q(s({id:I,action:"FS",payload:{method:"readFile",args:[A,{encoding:"utf8"}]}})),P=(A,I)=>Q(s({id:I,action:"FS",payload:{method:"unlink",args:[A]}})),T=(A,I,H)=>Q(s({id:H,action:"FS",payload:{method:A,args:I}})),K=()=>console.warn("`loadLanguage` is depreciated and should be removed from code (workers now come with language pre-loaded)"),W=(A,I)=>Q(s({id:I,action:"loadLanguage",payload:{langs:A,options:{langPath:O.langPath,dataPath:O.dataPath,cachePath:O.cachePath,cacheMethod:O.cacheMethod,gzip:O.gzip,lstmOnly:[r.DEFAULT,r.LSTM_ONLY].includes(R)&&!O.legacyLang}}})),X=()=>console.warn("`initialize` is depreciated and should be removed from code (workers now come pre-initialized)"),G=(A,I,H,ee)=>Q(s({id:ee,action:"initialize",payload:{langs:A,oem:I,config:H}})),be=(A="eng",I,H,ee)=>{if(B&&[r.TESSERACT_ONLY,r.TESSERACT_LSTM_COMBINED].includes(I))throw Error("Legacy model requested but code missing.");const Z=I||R;R=Z;const ie=H||j;j=ie;const Re=(typeof A=="string"?A.split("+"):A).filter(ds=>!C.includes(ds));return C.push(...Re),Re.length>0?W(Re,ee).then(()=>G(A,Z,ie,ee)):G(A,Z,ie,ee)},me=(A={},I)=>Q(s({id:I,action:"setParameters",payload:{params:A}})),re=async(A,I={},H={blocks:!0,text:!0,hocr:!0,tsv:!0},ee)=>Q(s({id:ee,action:"recognize",payload:{image:await k(A),options:I,output:H}})),ls=(A="Tesseract OCR Result",I=!1,H)=>(console.log("`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead."),Q(s({id:H,action:"getPDF",payload:{title:A,textonly:I}}))),rs=async(A,I)=>{if(B)throw Error("`worker.detect` requires Legacy model, which was not loaded.");return Q(s({id:I,action:"detect",payload:{image:await k(A)}}))},is=async()=>(se!==null&&(p(se),se=null),Promise.resolve());w(se,({workerId:A,jobId:I,status:H,action:ee,data:Z})=>{const ie=`${ee}-${I}`;if(H==="resolve"){t(`[${A}]: Complete ${I}`);let ke=Z;ee==="recognize"?ke=a(Z):ee==="getPDF"&&(ke=Array.from({...Z,length:Object.keys(Z).length})),D[ie]({jobId:I,data:ke})}else if(H==="reject")if(F[ie](Z),ee==="load"&&Y(Z),b)b(Z);else throw Error(Z);else H==="progress"&&h({...Z,userJobId:I})});const cs={id:f,worker:se,setResolve:oe,setReject:V,load:z,writeText:$,readText:N,removeFile:P,FS:T,loadLanguage:K,initialize:X,reinitialize:be,setParameters:me,recognize:re,getPDF:ls,detect:rs,terminate:is};return _().then(()=>W(l)).then(()=>G(l,i,v)).then(()=>le(cs)).catch(()=>{}),de},Ke}var Ye,Dt;function Ln(){if(Dt)return Ye;Dt=1;const n=ss();return Ye={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()})}},Ye}var Ze,jt;function Rn(){return jt||(jt=1,Ze={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"}),Ze}var Qe,It;function En(){return It||(It=1,Qe={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"}),Qe}var Xe,Tt;function On(){if(Tt)return Xe;Tt=1,fn();const n=hn(),a=ss(),s=Ln(),t=Rn(),o=ts(),r=En(),{setLogging:u}=ct();return Xe={languages:t,OEM:o,PSM:r,createScheduler:n,createWorker:a,setLogging:u,...s},Xe}var Mn=On();class dt{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"),m=u.getContext("2d");u.width=t.width,u.height=t.height,m.drawImage(t,0,0);const p={},w={};for(const[x,l]of Object.entries(this.regions)){const i=document.createElement("canvas"),y=i.getContext("2d");i.width=l.width,i.height=l.height,y.drawImage(u,l.x,l.y,l.width,l.height,0,0,l.width,l.height);const v=y.getImageData(0,0,l.width,l.height);this.preprocessImage(v),y.putImageData(v,0,0),x==="cost"?await this.worker.setParameters({tessedit_char_whitelist:"0123456789G"}):x==="cycles"||x==="area"?await this.worker.setParameters({tessedit_char_whitelist:"0123456789"}):x==="puzzle"?await this.configurePuzzleOCR():await this.worker.setParameters({tessedit_char_whitelist:""});const{data:{text:f,confidence:h}}=await this.worker.recognize(i);let b=f.trim();if(w[x]=h/100,x==="cost"){if(b.endsWith("6")&&b.length>1){const O=b.slice(0,-1);/^\d+$/.test(O)&&(b=O)}b=b.replace(/G+$/g,""),b=b.replace(/[^0-9]/g,"")}else if(x==="cycles"||x==="area")b=b.replace(/[^0-9]/g,"");else if(x==="puzzle"&&(b=this.findBestPuzzleMatch(b),this.availablePuzzleNames.length>0&&!this.availablePuzzleNames.includes(b))){const O=this.findBestPuzzleMatchForced(b);O&&(b=O,console.log(`Forced OCR match: "${f.trim()}" -> "${b}"`))}p[x]=b}URL.revokeObjectURL(s);const k=Object.values(w),S=k.length>0?k.reduce((x,l)=>x+l,0)/k.length:0;o({puzzle:p.puzzle||"",cost:parseInt(p.cost||""),cycles:parseInt(p.cycles||""),area:parseInt(p.area||""),confidence:{puzzle:w.puzzle||0,cost:w.cost||0,cycles:w.cycles||0,area:w.area||0,overall:S}})}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(m=>m.toLowerCase()===s.toLowerCase());if(t)return t;const o=this.availablePuzzleNames.find(m=>m.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(m.toLowerCase()));if(o)return o;let r=s,u=0;for(const m of this.availablePuzzleNames){const p=[this.calculateLevenshteinSimilarity(s,m),this.calculateJaroWinklerSimilarity(s,m),this.calculateNGramSimilarity(s,m,2)],w=Math.max(...p);w>u&&w>.4&&(u=w,r=m)}if(u<.6){const m=this.findBestCharacterMatch(s);m&&(r=m)}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),m=new Array(o.length).fill(!1);let p=0,w=0;for(let l=0;l<t.length;l++){const i=Math.max(0,l-r),y=Math.min(l+r+1,o.length);for(let v=i;v<y;v++)if(!(m[v]||t[l]!==o[v])){u[l]=!0,m[v]=!0,p++;break}}if(p===0)return 0;let k=0;for(let l=0;l<t.length;l++)if(u[l]){for(;!m[k];)k++;t[l]!==o[k]&&w++,k++}const S=(p/t.length+p/o.length+(p-w/2)/p)/3;let x=0;for(let l=0;l<Math.min(t.length,o.length,4)&&t[l]===o[l];l++)x++;return S+.1*x*(1-S)}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,m=new Set;for(let k=0;k<=o.length-t;k++)u.add(o.substr(k,t));for(let k=0;k<=r.length-t;k++)m.add(r.substr(k,t));const p=new Set([...u].filter(k=>m.has(k))),w=new Set([...u,...m]);return p.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 p of a)t.set(p,(t.get(p)||0)+1);for(const p of s)o.set(p,(o.get(p)||0)+1);const r=new Set([...t.keys(),...o.keys()]);let u=0,m=0;for(const p of r){const w=t.get(p)||0,k=o.get(p)||0;u+=Math.min(w,k),m+=Math.max(w,k)}return m===0?0:u/m}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())],m=u[0]*.25+u[1]*.25+u[2]*.2+u[3]*.2+u[4]*.1;m>o&&(o=m,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"),m=u.getContext("2d");u.width=r.width,u.height=r.height,m.drawImage(r,0,0),m.strokeStyle="#00ff00",m.lineWidth=2;const p=new dt;Object.values(p.regions).forEach(w=>{m.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 nt=new dt,_e=.8,ns=at("uploads",()=>{const n=M([]),a=te(()=>n.value.some(p=>p.ocrProcessing)),s=te(()=>n.value.some(p=>o(p))),t=te(()=>n.value.filter(p=>p.needsManualPuzzleSelection)),o=p=>p.ocrData?.confidence?p.ocrData.confidence.cost<_e||p.ocrData.confidence.cycles<_e||p.ocrData.confidence.area<_e:!1,r=async p=>{for(;a.value;){const k=Math.floor(Math.random()*400)+100;console.log(`OCR is already processing, waiting ${k}ms...`),await new Promise(S=>setTimeout(S,k))}const w=n.value.indexOf(p);n.value[w].ocrProcessing=!0,n.value[w].ocrError=void 0,n.value[w].ocrData=void 0;try{console.log("Starting OCR processing for:",p.file.name),await nt.initialize();const k=await nt.extractOpusMagnumData(p.file);console.log("OCR completed:",k),await Se(),n.value[w].ocrData=k,k.confidence.puzzle<_e?(n.value[w].needsManualPuzzleSelection=!0,console.log(`Low puzzle confidence (${Math.round(k.confidence.puzzle*100)}%) for ${p.file.name}, requiring manual selection`)):n.value[w].needsManualPuzzleSelection=!1,await Se()}catch(k){console.error("OCR processing failed:",k),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 p=n.value.filter(w=>o(w));for(const w of p)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"],lo={key:3},ro=["title"],io={key:3,class:"mt-2"},co={class:"mt-2"},uo=["onUpdate:modelValue","onChange"],fo=["value"],ho={key:4,class:"mt-1"},mo=["onClick"],vo={class:"flex justify-center"},go={key:0,class:"label"},po={class:"label-text-alt text-error"},bo=he({__name:"FileUpload",setup(n){const a=Le(),{submissionFiles:s,processOCR:t}=ns(),o=M(),r=M(!1),u=M("");Ce(()=>a.puzzles,f=>{f&&f.length>0&&nt.setAvailablePuzzleNames(a.puzzleNames)},{immediate:!0});const m=f=>{const h=f.target;h.files&&w(Array.from(h.files))},p=f=>{f.preventDefault(),r.value=!1,f.dataTransfer?.files&&w(Array.from(f.dataTransfer.files))},w=async f=>{u.value="";for(const h of f)if(k(h))try{const b=await S(h),O=h.type.startsWith("image/gif")?"gif":"image",D={file:h,file_url:"",preview:b,type:O,ocrProcessing:!1,ocrError:void 0,ocrData:void 0};s.push(D),i(h)&&Se(()=>{t(D)})}catch{u.value=`Failed to process ${h.name}`}},k=f=>f.type.startsWith("image/")?f.size>256*1024*1024?(u.value=`${f.name} is too large (max 256MB)`,!1):!0:(u.value=`${f.name} is not a valid image file`,!1),S=f=>new Promise((h,b)=>{const O=new FileReader;O.onload=D=>h(D.target?.result),O.onerror=b,O.readAsDataURL(f)}),x=f=>{s.splice(f,1)},l=f=>{if(f===0)return"0 Bytes";const h=1024,b=["Bytes","KB","MB","GB"],O=Math.floor(Math.log(f)/Math.log(h));return parseFloat((f/Math.pow(h,O)).toFixed(2))+" "+b[O]},i=f=>f.type.startsWith("image/")&&f.size>5e4,y=f=>f>=.8?"badge-success":f>=.6?"badge-warning":"badge-error",v=f=>{const h=s.findIndex(b=>b.file===f.file);h!==-1&&s[h].manualPuzzleSelection&&(s[h].needsManualPuzzleSelection=!1,console.log(`Manual puzzle selection: ${f.file.name} -> ${s[h].manualPuzzleSelection}`))};return(f,h)=>(c(),d("div",Nn,[h[19]||(h[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:ae(["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:p,onDragover:h[2]||(h[2]=et(b=>r.value=!0,["prevent"])),onDragleave:h[3]||(h[3]=b=>r.value=!1),onDragenter:h[4]||(h[4]=et(()=>{},["prevent"]))},[e("input",{ref_key:"fileInput",ref:o,type:"file",multiple:"",accept:"image/*,.gif",class:"hidden",onChange:m},null,544),q(s).length===0?(c(),d("div",An,[h[6]||(h[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,[h[5]||(h[5]=e("p",{class:"text-base-content/70 mb-2"},"Drop your files here or",-1)),e("button",{type:"button",onClick:h[0]||(h[0]=b=>o.value?.click()),class:"btn btn-primary btn-sm"}," Choose Files ")]),h[7]||(h[7]=e("p",{class:"text-xs text-base-content/50"}," Supported formats: JPG, PNG, GIF (max 256MB each) ",-1))])):(c(),d("div",Dn,[e("div",jn,[(c(!0),d(U,null,J(q(s),(b,O)=>(c(),d("div",{key:O,class:"relative group"},[e("div",In,[e("img",{src:b.preview,alt:b.file.name,class:"w-full h-full object-cover"},null,8,Tn)]),e("div",qn,[e("button",{onClick:D=>x(O),class:"btn btn-error btn-lg btn-circle"},[...h[8]||(h[8]=[e("i",{class:"mdi mdi-close"},null,-1)])],8,Fn)]),e("div",Un,[e("p",Bn,g(b.file.name),1),e("p",Vn,g(l(b.file.size))+" "+g(b.type.toUpperCase()),1),b.ocrProcessing?(c(),d("div",Gn,[...h[9]||(h[9]=[e("span",{class:"loading loading-spinner loading-xs"},null,-1),e("span",{class:"text-xs text-info"},"Extracting puzzle data...",-1)])])):b.ocrError?(c(),d("div",Wn,[e("p",Hn,g(b.ocrError),1)])):b.ocrData?(c(),d("div",Jn,[e("div",Kn,[e("div",Yn,[h[10]||(h[10]=e("span",{class:"font-medium text-success"}," OCR Complete",-1)),b.ocrData.confidence?(c(),d("span",{key:0,class:ae(["badge badge-xs",y(b.ocrData.confidence.overall)]),title:`Overall confidence: ${Math.round(b.ocrData.confidence.overall*100)}%`},g(Math.round(b.ocrData.confidence.overall*100))+"% ",11,Zn)):L("",!0)]),e("button",{onClick:D=>q(t)(b),class:"btn btn-xs btn-ghost",title:"Retry OCR"},[...h[11]||(h[11]=[e("i",{class:"mdi mdi-refresh"},null,-1)])],8,Qn)]),e("div",Xn,[b.ocrData.puzzle?(c(),d("div",eo,[h[12]||(h[12]=e("strong",null,"Puzzle:",-1)),E(" "+g(b.ocrData.puzzle)+" ",1),b.ocrData.confidence?.puzzle?(c(),d("span",{key:0,class:"ml-2 opacity-60",title:`Puzzle confidence: ${Math.round(b.ocrData.confidence.puzzle*100)}%`}," ("+g(Math.round(b.ocrData.confidence.puzzle*100))+"%) ",9,to)):L("",!0)])):L("",!0),b.ocrData.cost?(c(),d("div",so,[h[13]||(h[13]=e("strong",null,"Cost:",-1)),E(" "+g(b.ocrData.cost)+" ",1),b.ocrData.confidence?.cost?(c(),d("span",{key:0,class:"ml-2 opacity-60",title:`Cost confidence: ${Math.round(b.ocrData.confidence.cost*100)}%`}," ("+g(Math.round(b.ocrData.confidence.cost*100))+"%) ",9,no)):L("",!0)])):L("",!0),b.ocrData.cycles?(c(),d("div",oo,[h[14]||(h[14]=e("strong",null,"Cycles:",-1)),E(" "+g(b.ocrData.cycles)+" ",1),b.ocrData.confidence?.cycles?(c(),d("span",{key:0,class:"ml-2 opacity-60",title:`Cycles confidence: ${Math.round(b.ocrData.confidence.cycles*100)}%`}," ("+g(Math.round(b.ocrData.confidence.cycles*100))+"%) ",9,ao)):L("",!0)])):L("",!0),b.ocrData.area?(c(),d("div",lo,[h[15]||(h[15]=e("strong",null,"Area:",-1)),E(" "+g(b.ocrData.area)+" ",1),b.ocrData.confidence?.area?(c(),d("span",{key:0,class:"ml-2 opacity-60",title:`Area confidence: ${Math.round(b.ocrData.confidence.area*100)}%`}," ("+g(Math.round(b.ocrData.confidence.area*100))+"%) ",9,ro)):L("",!0)])):L("",!0)])])):L("",!0),b.needsManualPuzzleSelection?(c(),d("div",io,[h[17]||(h[17]=gs('<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":D=>b.manualPuzzleSelection=D,class:"select select-bordered select-sm w-full",onChange:D=>v(b)},[h[16]||(h[16]=e("option",{value:""},"Select puzzle...",-1)),(c(!0),d(U,null,J(q(a).puzzles,D=>(c(),d("option",{key:D.id,value:D.title},g(D.title),9,fo))),128))],40,uo),[[Ht,b.manualPuzzleSelection]])])])):!b.ocrProcessing&&!b.ocrError&&!b.ocrData?(c(),d("div",ho,[e("button",{onClick:D=>q(t)(b),class:"btn btn-xs btn-outline"},[...h[18]||(h[18]=[e("i",{class:"mdi mdi-text-recognition"},null,-1),E(" Extract Puzzle Data ",-1)])],8,mo)])):L("",!0)])]))),128))]),e("div",vo,[e("button",{type:"button",onClick:h[1]||(h[1]=b=>o.value?.click()),class:"btn btn-outline btn-sm"}," Add More Files ")])]))],34),u.value?(c(),d("div",go,[e("span",po,g(u.value),1)])):L("",!0)]))}}),yo={class:"card bg-base-100 shadow-xl"},_o={class:"card-body"},xo={key:0,class:"alert alert-info"},wo={class:"flex-1"},ko={class:"font-bold"},zo={class:"text-sm space-y-1 mt-1"},$o={class:"badge badge-ghost badge-sm ml-2"},So={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=he({__name:"SubmissionForm",props:{puzzles:{},findPuzzleByName:{type:Function}},setup(n){const a=n,s=ns(),{submissionFiles:t,hasLowConfidence:o,submissionFilesNeedingManualSelection:r}=lt(s),{clearFiles:u,processLowConfidenceOCRFiles:m}=s,{handleSubmission:p}=rt(),w=M(""),k=M(!1),S=M(!1),x=te(()=>w.value.length),l=te(()=>{const v=t.value.length>0,f=!t.value.some(h=>h.needsManualPuzzleSelection);return v&&!S.value&&f});Ce(o,v=>{v&&(k.value=!0)});const i=te(()=>{const v={};return t.value.forEach(f=>{const h=f.manualPuzzleSelection||f.ocrData?.puzzle;h&&(v[h]||(v[h]={puzzle:a.findPuzzleByName(h),files:[]}),v[h].files.push(f))}),v}),y=async()=>{if(l.value){S.value=!0;try{p({files:t.value,notes:w.value.trim()||void 0,manualValidationRequested:o.value||k.value}),u(),w.value="",k.value=!1}catch(v){console.error("Submission error:",v)}finally{S.value=!1}}};return(v,f)=>(c(),d("div",yo,[e("div",_o,[f[9]||(f[9]=e("h2",{class:"card-title text-xl mb-6"},[e("i",{class:"mdi mdi-check-circle text-2xl text-primary"}),E(" Submit Solution ")],-1)),e("form",{onSubmit:et(y,["prevent"]),class:"space-y-6"},[Object.keys(i.value).length>0?(c(),d("div",xo,[f[3]||(f[3]=e("i",{class:"mdi mdi-information-outline text-xl"},null,-1)),e("div",wo,[e("h4",ko," Detected Puzzles ("+g(Object.keys(i.value).length)+") ",1),e("div",zo,[(c(!0),d(U,null,J(i.value,(h,b)=>(c(),d("div",{key:b,class:"flex justify-between"},[e("span",null,g(b),1),e("span",$o,g(h.files.length)+" file(s)",1)]))),128))])])])):L("",!0),fe(bo),q(r).length>0?(c(),d("div",So,[f[6]||(f[6]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",Co,[f[5]||(f[5]=e("div",{class:"font-bold"},"Manual Puzzle Selection Required",-1)),e("div",Po,g(q(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:f[0]||(f[0]=(...h)=>q(m)&&q(m)(...h))},[...f[4]||(f[4]=[e("span",{class:"mdi mdi-reload text-2xl"},null,-1),E(" Retry OCR on low confidence puzzle ",-1)])])])])):L("",!0),e("div",Lo,[e("div",Ro,[e("label",Eo,[f[7]||(f[7]=e("span",{class:"label-text font-medium"},"Notes (Optional)",-1)),e("span",Oo,g(x.value)+"/500",1)]),ce(e("textarea",{"onUpdate:modelValue":f[1]||(f[1]=h=>w.value=h),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":f[2]||(f[2]=h=>k.value=h),class:"checkbox checkbox-primary",disabled:q(o)},null,8,Ao),[[ps,k.value]]),f[8]||(f[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"},[E(" 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},[S.value?(c(),d("span",Io)):L("",!0),S.value?(c(),d("span",To,"Submitting...")):q(r).length>0?(c(),d("span",qo," Select Puzzles ("+g(q(r).length)+" remaining) ",1)):(c(),d("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"},la={class:"flex justify-between items-center"},ra={class:"flex justify-between items-center"},ia={class:"flex justify-between items-center"},ca={class:"badge badge-warning badge-sm"},da=["onClick"],ua=["onClick"],fa={key:1,class:"text-center py-8"},ha={key:0,class:"modal modal-open"},ma={class:"modal-box w-11/12 max-w-5xl"},va=["src"],ga={key:0,class:"space-y-4"},pa={class:"alert alert-info"},ba={class:"font-bold"},ya={class:"grid grid-cols-4 gap-4"},_a={class:"form-control"},xa=["value"],wa={class:"form-control"},ka=["placeholder"],za={class:"form-control"},$a=["placeholder"],Sa={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=he({__name:"AdminPanel",setup(n,{expose:a}){const s=Le(),t=M({total_submissions:0,total_responses:0,needs_validation:0,validated_submissions:0,validation_rate:0}),o=M([]),r=M(!1),u=M(!1),m=M({show:!1,response:null,data:{puzzle:-1,validated_cost:0,validated_cycles:0,validated_area:0}}),p=async()=>{try{r.value=!0;try{const f=await ne.getStats();f.data&&(t.value=f.data)}catch(f){console.warn("Stats endpoint not available:",f),t.value={total_submissions:0,total_responses:0,needs_validation:0,validated_submissions:0,validation_rate:0}}const v=await ne.getResponsesNeedingValidation();v.data&&(o.value=v.data)}catch(v){console.error("Failed to load admin data:",v)}finally{r.value=!1}},w=async()=>{for(const v of Array.from(o.value)){if(!v.id)continue;const{data:f,error:h}=await ne.autoValidateResponses(v.id);if(f&&!f.needs_manual_validation)o.value=o.value.filter(b=>b.id!==v.id),t.value.needs_validation-=1;else if(h)break}},k=v=>{m.value.response=v,m.value.data={puzzle:v.puzzle_id||-1,validated_cost:v.cost||0,validated_cycles:v.cycles||0,validated_area:v.area||0},m.value.show=!0},S=()=>{m.value.show=!1,m.value.response=null,m.value.data={puzzle:-1,validated_cost:0,validated_cycles:0,validated_area:0}},x=async v=>{const{data:f}=await ne.autoValidateResponses(v);console.log(f),f&&!f.needs_manual_validation&&(o.value=o.value.filter(h=>h.id!==v),console.log(t.value),t.value.needs_validation-=1,console.log(t.value))},l=async()=>{if(m.value.response?.id)try{u.value=!0;const v=await ne.validateResponse(m.value.response.id,m.value.data);if(v.error){alert(`Validation failed: ${v.error}`);return}o.value=o.value.filter(f=>f.id!==m.value.response?.id),t.value.needs_validation=Math.max(0,t.value.needs_validation-1),S()}catch(v){console.error("Validation error:",v),alert("Validation failed")}finally{u.value=!1}};we(()=>{p()});const i=v=>v>=.8?"badge-success":v>=.6?"badge-warning":"badge-error",y=v=>{const f=[v.ocr_confidence_cost,v.ocr_confidence_cycles,v.ocr_confidence_area].filter(b=>b!=null);if(f.length===0)return 0;const h=f.reduce((b,O)=>b+O,0)/f.length;return Math.round(h*100)};return a({refresh:p}),(v,f)=>(c(),d(U,null,[e("div",Bo,[e("div",Vo,[f[14]||(f[14]=e("h2",{class:"card-title"},[e("i",{class:"mdi mdi-shield-account text-2xl text-warning"}),E(" Admin Panel ")],-1)),e("div",Go,[e("div",Wo,[f[4]||(f[4]=e("div",{class:"stat-title"},"Total Submissions",-1)),e("div",Ho,g(t.value.total_submissions),1)]),e("div",Jo,[f[5]||(f[5]=e("div",{class:"stat-title"},"Total Responses",-1)),e("div",Ko,g(t.value.total_responses),1)]),e("div",Yo,[f[6]||(f[6]=e("div",{class:"stat-title"},"Need Validation",-1)),e("div",Zo,g(t.value.needs_validation),1)]),e("div",Qo,[f[7]||(f[7]=e("div",{class:"stat-title"},"Validation Rate",-1)),e("div",Xo,g(Math.round(t.value.validation_rate*100))+"% ",1)])]),e("button",{class:"btn btn-sm btn-primary",onClick:w},[...f[8]||(f[8]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),E(" Auto validation for all responses ",-1)])]),o.value.length>0?(c(),d("div",ea,[f[12]||(f[12]=e("h3",{class:"text-lg font-bold mb-4"},"Responses Needing Validation",-1)),e("div",ta,[e("table",sa,[f[11]||(f[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,[(c(!0),d(U,null,J(o.value,h=>(c(),d("tr",{key:h.id},[e("td",null,[e("div",na,g(h.puzzle_name),1),e("div",oa,"ID: "+g(h.id),1)]),e("td",null,[e("div",aa,[e("div",la,[e("span",null,"Cost: "+g(h.cost||"-"),1),h.ocr_confidence_cost?(c(),d("span",{key:0,class:ae(["badge badge-xs",i(h.ocr_confidence_cost)])},g(Math.round(h.ocr_confidence_cost*100))+"% ",3)):L("",!0)]),e("div",ra,[e("span",null,"Cycles: "+g(h.cycles||"-"),1),h.ocr_confidence_cycles?(c(),d("span",{key:0,class:ae(["badge badge-xs",i(h.ocr_confidence_cycles)])},g(Math.round(h.ocr_confidence_cycles*100))+"% ",3)):L("",!0)]),e("div",ia,[e("span",null,"Area: "+g(h.area||"-"),1),h.ocr_confidence_area?(c(),d("span",{key:0,class:ae(["badge badge-xs",i(h.ocr_confidence_area)])},g(Math.round(h.ocr_confidence_area*100))+"% ",3)):L("",!0)])])]),e("td",null,[e("div",ca,g(y(h))+"% ",1)]),e("td",null,[e("button",{onClick:b=>k(h),class:"btn btn-sm btn-primary mr-2"},[...f[9]||(f[9]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),E(" Validate ",-1)])],8,da),h.id?(c(),d("button",{key:0,onClick:b=>x(h.id),class:"btn btn-sm btn-warning"},[...f[10]||(f[10]=[e("i",{class:"mdi mdi-check-circle mr-1"},null,-1),E(" Auto Validation ",-1)])],8,ua)):L("",!0)])]))),128))])])])])):(c(),d("div",fa,[...f[13]||(f[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)])]))])]),m.value.show?(c(),d("div",ha,[e("div",ma,[f[22]||(f[22]=e("h3",{class:"font-bold text-lg mb-4"},"Validate Response",-1)),(c(!0),d(U,null,J(m.value.response?.files??[],h=>(c(),d("div",null,[e("img",{src:h.file_url},null,8,va)]))),256)),m.value.response?(c(),d("div",ga,[e("div",pa,[f[16]||(f[16]=e("i",{class:"mdi mdi-information-outline"},null,-1)),e("div",null,[e("div",ba,g(m.value.response.puzzle_name),1),f[15]||(f[15]=e("div",{class:"text-sm"},"Review and correct the OCR data below",-1))])]),e("div",ya,[e("div",_a,[f[18]||(f[18]=e("label",{class:"label"},[e("span",{class:"label-text"},"Puzzle")],-1)),ce(e("select",{"onUpdate:modelValue":f[0]||(f[0]=h=>m.value.data.puzzle=h),class:"select select-bordered select-sm w-full"},[f[17]||(f[17]=e("option",{value:""},"Select puzzle...",-1)),(c(!0),d(U,null,J(q(s).puzzles,h=>(c(),d("option",{key:h.id,value:h.id},g(h.title),9,xa))),128))],512),[[Ht,m.value.data.puzzle]])]),e("div",wa,[f[19]||(f[19]=e("label",{class:"label"},[e("span",{class:"label-text"},"Cost")],-1)),ce(e("input",{"onUpdate:modelValue":f[1]||(f[1]=h=>m.value.data.validated_cost=h),type:"text",class:"input input-bordered input-sm",placeholder:m.value.response.cost?.toString()||"Enter cost"},null,8,ka),[[ze,m.value.data.validated_cost]])]),e("div",za,[f[20]||(f[20]=e("label",{class:"label"},[e("span",{class:"label-text"},"Cycles")],-1)),ce(e("input",{"onUpdate:modelValue":f[2]||(f[2]=h=>m.value.data.validated_cycles=h),type:"text",class:"input input-bordered input-sm",placeholder:m.value.response.cycles?.toString()||"Enter cycles"},null,8,$a),[[ze,m.value.data.validated_cycles]])]),e("div",Sa,[f[21]||(f[21]=e("label",{class:"label"},[e("span",{class:"label-text"},"Area")],-1)),ce(e("input",{"onUpdate:modelValue":f[3]||(f[3]=h=>m.value.data.validated_area=h),type:"text",class:"input input-bordered input-sm",placeholder:m.value.response.area?.toString()||"Enter area"},null,8,Ca),[[ze,m.value.data.validated_area]])])]),e("div",Pa,[e("button",{onClick:S,class:"btn btn-ghost"}," Cancel "),e("button",{onClick:l,class:"btn btn-primary",disabled:u.value},[u.value?(c(),d("span",Ra)):L("",!0),E(" "+g(u.value?"Validating...":"Validate"),1)],8,La)]),e("div",Ea,[e("pre",null,[e("code",null,g(m.value),1)])])])):L("",!0)]),e("div",{class:"modal-backdrop",onClick:S})])):L("",!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"},el={key:2,class:"space-y-6"},tl={class:"tabs tabs-border"},sl={class:"space-y-4"},nl={key:0,class:"text-center py-8"},ol={key:1,class:"overflow-x-auto"},al={class:"table table-zebra w-full"},ll={class:"font-bold"},rl={class:"font-medium"},il={key:0,class:"badge badge-warning"},cl={class:"text-right"},dl={class:"text-right font-bold"},ul={class:"space-y-6"},fl=["onClick"],hl={class:"ml-auto badge badge-sm"},ml={key:0,class:"card-body"},vl={key:0,class:"text-center py-8"},gl={key:1,class:"space-y-6"},pl={key:0,class:"bg-base-200 p-4 rounded-lg"},bl={class:"grid grid-cols-3 gap-4"},yl={class:"text-center"},_l={class:"text-2xl font-bold text-primary"},xl={class:"text-center"},wl={class:"text-2xl font-bold text-primary"},kl={class:"text-center"},zl={class:"text-2xl font-bold text-primary"},$l={class:"grid grid-cols-1 md:grid-cols-3 gap-4"},Sl={class:"card-body p-4"},Cl={class:"text-xs text-base-content/70 font-bold"},Pl={class:"font-bold text-lg"},Ll={key:0,class:"badge badge-warning"},Rl={class:"space-y-2 text-sm"},El={class:"flex justify-between"},Ol={key:0,class:"text-xs text-base-content/60"},Ml={class:"badge badge-sm"},Nl={class:"flex justify-between"},Al={key:0,class:"text-xs text-base-content/60"},Dl={class:"badge badge-sm"},jl={class:"flex justify-between"},Il={key:0,class:"text-xs text-base-content/60"},Tl={class:"badge badge-sm"},ql={class:"flex justify-between pt-2 border-t"},Fl={class:"badge badge-sm"},Ul={class:"flex justify-between pt-2 border-t"},Bl={class:"badge badge-primary"},Vl={class:"overflow-x-auto"},Gl={class:"table table-zebra w-full table-sm"},Wl={class:"text-center"},Hl={key:0,class:"text-xs text-base-content/60 block"},Jl={class:"text-center"},Kl={key:0,class:"text-xs text-base-content/60 block"},Yl={class:"text-center"},Zl={key:0,class:"text-xs text-base-content/60 block"},Ql={class:"font-bold"},Xl={key:0,class:"badge badge-warning"},er={key:1,class:"badge"},tr={key:2,class:"badge"},sr={key:3},nr={class:"font-medium"},or={class:"text-center"},ar={key:0,class:"badge badge-sm"},lr={key:1,class:"text-base-content/40"},rr={class:"text-center"},ir={key:0,class:"badge badge-sm"},cr={key:1,class:"text-base-content/40"},dr={class:"text-center"},ur={key:0,class:"badge badge-sm"},fr={key:1,class:"text-base-content/40"},hr={class:"text-center"},mr={key:0,class:"badge badge-sm"},vr={key:1,class:"text-base-content/40"},gr={class:"text-right font-bold text-primary text-lg"},pr=he({__name:"Results",setup(n){const a=M(!0),s=M(null),t=M("overall"),o=M(null),r=M({username:"Player",rank:null,totalPoints:0,puzzlesSolved:0,isStaff:!1}),u=async()=>{a.value=!0;try{const x=await fetch("/api/results/results");if(!x.ok)throw new Error("Failed to fetch results");s.value=await x.json()}catch(x){console.error("Error fetching results:",x)}finally{a.value=!1}},m=()=>s.value?s.value.users.map(l=>{const i=s.value.responses_by_userid[l.id]||[],y=i.reduce((f,h)=>f+(h.rank_points||0),0),v=i.length;return{user:l,totalPoints:y,puzzlesSolved:v}}).sort((l,i)=>i.totalPoints-l.totalPoints):[],p=x=>s.value?(s.value.ranking_by_puzzle[x]||[]).map(i=>({user:s.value.users.find(v=>v.id===i.user_id),cost:i.final_cost,cycles:i.final_cycles,area:i.final_area,points:i.points,rank_points:i.rank_points||0})).reverse():[],w=x=>{o.value=o.value===x?null:x},k=async()=>{try{const x=await fetch("/api/cache/clear",{method:"POST"});if(x.ok)alert("Cache cleared successfully!"),await u();else{const l=await x.json();alert(`Error clearing cache: ${l.detail||"Unknown error"}`)}}catch(x){console.error("Error clearing cache:",x),alert("Error clearing cache. Please try again.")}},S=async()=>{try{const x=await fetch("/api/user");if(x.ok){const l=await x.json();if(l.is_authenticated){r.value.username=l.username,r.value.isStaff=l.is_staff||!1,await u();const i=m(),y=i.findIndex(v=>v.user.id===l.id);y!==-1&&(r.value.rank=y+1,r.value.totalPoints=i[y].totalPoints,r.value.puzzlesSolved=i[y].puzzlesSolved)}}}catch(x){console.error("Error loading user data:",x),await u()}};return we(()=>{S()}),(x,l)=>(c(),d("div",Ma,[e("div",Na,[e("div",Aa,[e("div",Da,[l[9]||(l[9]=e("div",{class:"bg-gradient-to-br from-purple-600 to-purple-400 p-6 text-white rounded-t-2xl"},[e("h3",{class:"text-3xl font-bold"},[e("i",{class:"mdi mdi-trophy text-3xl"}),E(" 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,g(r.value.username),1)]),l[8]||(l[8]=e("div",{class:"divider"},null,-1)),a.value?(c(),d("div",qa,[...l[3]||(l[3]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):(c(),d("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?(c(),d("p",Ba,[fe(ft,{rank:r.value.rank},null,8,["rank"])])):(c(),d("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,g(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,g(r.value.puzzlesSolved),1)]),r.value.isStaff?(c(),d("button",{key:0,onClick:k,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),E(" Clear Cache ",-1)])])):L("",!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"}),E(" General Results ")],-1)),a.value?(c(),d("div",Qa,[...l[10]||(l[10]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):s.value?(c(),d("div",el,[e("div",tl,[e("button",{onClick:l[0]||(l[0]=i=>t.value="overall"),class:ae(["tab",t.value==="overall"?"tab-active":""])},[...l[12]||(l[12]=[e("i",{class:"mdi mdi-chart-line mr-2"},null,-1),E(" Overall Ranking ",-1)])],2),e("button",{onClick:l[1]||(l[1]=i=>t.value="byPuzzle"),class:ae(["tab",t.value==="byPuzzle"?"tab-active":""])},[...l[13]||(l[13]=[e("i",{class:"mdi mdi-puzzle mr-2"},null,-1),E(" By Puzzle ",-1)])],2)]),ce(e("div",sl,[m().length===0?(c(),d("div",nl,[...l[14]||(l[14]=[e("p",{class:"text-base-content/70"},"No submissions yet",-1)])])):(c(),d("div",ol,[e("table",al,[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,[(c(!0),d(U,null,J(m(),(i,y)=>(c(),d("tr",{key:i.user.username},[e("td",ll,[fe(ft,{rank:y+1},null,8,["rank"])]),e("td",rl,[E(g(i.user.username)+" ",1),i.user.is_staff?(c(),d("span",il," admin ")):L("",!0)]),e("td",cl,g(i.puzzlesSolved),1),e("td",dl,g(i.totalPoints),1)]))),128))])])]))],512),[[ut,t.value==="overall"]]),ce(e("div",ul,[(c(!0),d(U,null,J(s.value.puzzles,i=>(c(),d("div",{key:i.id,class:"card bg-base-100 border border-base-300"},[e("button",{onClick:y=>w(i.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:ae(["mdi mr-2",o.value===i.id?"mdi-chevron-down":"mdi-chevron-right"])},null,2),E(" "+g(i.title)+" ",1),e("span",hl,g(p(i.id).length)+" submissions ",1)],8,fl),o.value===i.id?(c(),d("div",ml,[p(i.id).length===0?(c(),d("div",vl,[...l[16]||(l[16]=[e("p",{class:"text-base-content/70 text-lg"},"No submissions yet",-1)])])):(c(),d("div",gl,[i.points_factor?(c(),d("div",pl,[l[23]||(l[23]=e("p",{class:"text-sm text-base-content/70 mb-3 font-semibold"},"Points Coefficients",-1)),e("div",bl,[e("div",yl,[e("span",_l,[l[17]||(l[17]=e("small",null,"x",-1)),E(g(i.points_factor.cost),1)]),l[18]||(l[18]=e("p",{class:"text-xs text-base-content/70"},"Cost",-1))]),e("div",xl,[e("span",wl,[l[19]||(l[19]=e("small",null,"x",-1)),E(g(i.points_factor.cycles),1)]),l[20]||(l[20]=e("p",{class:"text-xs text-base-content/70"},"Cycles",-1))]),e("div",kl,[e("span",zl,[l[21]||(l[21]=e("small",null,"x",-1)),E(g(i.points_factor.area),1)]),l[22]||(l[22]=e("p",{class:"text-xs text-base-content/70"},"Area",-1))])])])):L("",!0),e("div",$l,[(c(!0),d(U,null,J(p(i.id).slice(0,3),(y,v)=>(c(),d("div",{key:v,class:"card bg-base-200"},[e("div",Sl,[e("div",Cl,g(v===0?"🏆 1st Place":v===1?"🥈 2nd Place":"🥉 3rd Place"),1),e("h4",Pl,[E(g(y.user.username)+" ",1),y.user.is_staff?(c(),d("span",Ll," admin ")):L("",!0)]),l[29]||(l[29]=e("div",{class:"divider my-2"},null,-1)),e("div",Rl,[e("div",El,[e("span",null,[l[24]||(l[24]=E("Cost",-1)),i.points_factor?(c(),d("span",Ol," (x"+g(i.points_factor.cost)+") ",1)):L("",!0)]),e("span",Ml,g(y.cost||"N/A"),1)]),e("div",Nl,[e("span",null,[l[25]||(l[25]=E("Cycles",-1)),i.points_factor?(c(),d("span",Al," (x"+g(i.points_factor.cycles)+") ",1)):L("",!0)]),e("span",Dl,g(y.cycles||"N/A"),1)]),e("div",jl,[e("span",null,[l[26]||(l[26]=E("Area",-1)),i.points_factor?(c(),d("span",Il," (x"+g(i.points_factor.area)+") ",1)):L("",!0)]),e("span",Tl,g(y.area||"N/A"),1)]),e("div",ql,[l[27]||(l[27]=e("span",null,"Total (with coef.)",-1)),e("span",Fl,g(y.points||"N/A"),1)]),e("div",Ul,[l[28]||(l[28]=e("span",{class:"font-bold"},"Points",-1)),e("span",Bl,g(y.rank_points)+" pts",1)])])])]))),128))]),e("div",Vl,[e("table",Gl,[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",Wl,[l[30]||(l[30]=E(" Cost ",-1)),i.points_factor?(c(),d("span",Hl,"(x"+g(i.points_factor.cost)+")",1)):L("",!0)]),e("th",Jl,[l[31]||(l[31]=E(" Cycles ",-1)),i.points_factor?(c(),d("span",Kl,"(x"+g(i.points_factor.cycles)+")",1)):L("",!0)]),e("th",Yl,[l[32]||(l[32]=E(" Area ",-1)),i.points_factor?(c(),d("span",Zl,"(x"+g(i.points_factor.area)+")",1)):L("",!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,[(c(!0),d(U,null,J(p(i.id),(y,v)=>(c(),d("tr",{key:v,class:ae({"bg-primary/10":v<3})},[e("td",Ql,[v===0?(c(),d("span",Xl,"🏆")):v===1?(c(),d("span",er,"🥈")):v===2?(c(),d("span",tr,"🥉")):(c(),d("span",sr,"#"+g(v+1),1))]),e("td",nr,g(y.user.username),1),e("td",or,[y.cost?(c(),d("span",ar,g(y.cost),1)):(c(),d("span",lr,""))]),e("td",rr,[y.cycles?(c(),d("span",ir,g(y.cycles),1)):(c(),d("span",cr,""))]),e("td",dr,[y.area?(c(),d("span",ur,g(y.area),1)):(c(),d("span",fr,""))]),e("td",hr,[y.points?(c(),d("span",mr,g(y.points),1)):(c(),d("span",vr,""))]),e("td",gr,g(y.rank_points),1)],2))),128))])])])]))])):L("",!0)]))),128))],512),[[ut,t.value==="byPuzzle"]])])):(c(),d("div",Xa,[...l[11]||(l[11]=[e("p",{class:"text-base-content/70"},"No results available yet",-1)])]))])])])])]))}}),br={class:"card bg-base-100 shadow-lg"},yr={class:"card-body"},_r={key:0,class:"flex justify-center py-12"},xr={key:1,class:"alert alert-error"},wr={key:2,class:"text-center py-8"},kr={key:3,class:"overflow-x-auto"},zr={class:"table table-zebra"},$r={class:"font-semibold"},Sr={class:"text-right"},Cr={class:"text-right"},Pr={class:"text-right"},Lr={class:"text-right font-bold"},Rr={class:"text-right font-bold text-primary"},Er={class:"text-center"},Or=["onClick"],Mr={key:1,class:"text-base-content/50"},Nr={key:0,class:"modal modal-open"},Ar={class:"modal-box max-w-7xl w-full"},Dr={class:"flex justify-between items-center mb-4"},jr={class:"font-bold text-lg"},Ir={class:"flex justify-center bg-base-200 rounded-lg p-4"},Tr=["src","alt"],qr={class:"modal-action mt-4"},Fr=["href"],Ur=he({__name:"Winners",setup(n){const a=M(!0),s=M(null),t=M(""),o=M(!1),r=M(""),u=M(""),m=async()=>{a.value=!0,t.value="";try{const x=await ne.getTopSubmissions(5);x.data?s.value=x.data:x.error&&(t.value=x.error,console.error("Error fetching submissions:",x.error))}catch(x){t.value=x instanceof Error?x.message:"Failed to fetch submissions",console.error("Error fetching submissions:",x)}finally{a.value=!1}},p=x=>x!==void 0?x.toLocaleString():"",w=te(()=>{if(!s.value)return[];const x=[];return s.value.submissions.forEach(l=>{l.submissions.forEach(i=>{x.push({puzzleName:l.puzzle_title,username:i.username,cost:i.final_cost,cycles:i.final_cycles,area:i.final_area,total:i.rank_points,totalCoef:i.total_coef,files:i.files.map(y=>({url:y.file_url,name:y.original_filename}))})})}),x}),k=(x,l)=>{r.value=x,u.value=l,o.value=!0},S=()=>{o.value=!1,r.value="",u.value=""};return we(()=>{m()}),(x,l)=>(c(),d(U,null,[e("div",br,[e("div",yr,[l[5]||(l[5]=e("h2",{class:"card-title text-2xl flex items-center gap-2"},[e("i",{class:"mdi mdi-trophy text-yellow-500 text-3xl"}),E(" Top Submissions ")],-1)),a.value?(c(),d("div",_r,[...l[0]||(l[0]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):t.value?(c(),d("div",xr,[l[1]||(l[1]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",null,g(t.value),1)])):w.value.length===0?(c(),d("div",wr,[...l[2]||(l[2]=[e("p",{class:"text-base-content/70"},"No results available yet.",-1)])])):(c(),d("div",kr,[e("table",zr,[l[4]||(l[4]=e("thead",null,[e("tr",null,[e("th",null,"Puzzle"),e("th",null,"User"),e("th",{class:"text-right"},"Cost"),e("th",{class:"text-right"},"Cycles"),e("th",{class:"text-right"},"Area"),e("th",{class:"text-right"},"Total Pts"),e("th",{class:"text-right"},"Total Coef"),e("th",{class:"text-center"},"GIF")])],-1)),e("tbody",null,[(c(!0),d(U,null,J(w.value,(i,y)=>(c(),d("tr",{key:y},[e("td",$r,g(i.puzzleName),1),e("td",null,g(i.username),1),e("td",Sr,g(p(i.cost)),1),e("td",Cr,g(p(i.cycles)),1),e("td",Pr,g(p(i.area)),1),e("td",Lr,g(p(i.total)),1),e("td",Rr,g(p(i.totalCoef)),1),e("td",Er,[i.files.length>0?(c(),d("button",{key:0,onClick:v=>k(i.files[0].url,i.files[0].name),class:"btn btn-xs btn-primary gap-1"},[...l[3]||(l[3]=[e("i",{class:"mdi mdi-image"},null,-1),E(" View ",-1)])],8,Or)):(c(),d("span",Mr,""))])]))),128))])])]))])]),o.value?(c(),d("div",Nr,[e("div",Ar,[e("div",Dr,[e("h3",jr,g(u.value),1),e("button",{onClick:S,class:"btn btn-sm btn-circle btn-ghost"},[...l[6]||(l[6]=[e("i",{class:"mdi mdi-close"},null,-1)])])]),e("div",Ir,[e("img",{src:r.value,alt:u.value,class:"object-contain"},null,8,Tr)]),e("div",qr,[e("a",{href:r.value,target:"_blank",class:"btn btn-primary btn-sm"},[...l[7]||(l[7]=[e("i",{class:"mdi mdi-download"},null,-1),E(" Download ",-1)])],8,Fr),e("button",{onClick:S,class:"btn btn-sm"},"Close")])]),e("div",{class:"modal-backdrop",onClick:S})])):L("",!0)],64))}}),Br={class:"card bg-base-100 shadow-lg"},Vr={class:"card-body"},Gr={key:0,class:"flex justify-center py-12"},Wr={key:1,class:"alert alert-error"},Hr={key:2,class:"text-center py-8"},Jr={key:3,class:"space-y-8"},Kr={class:"mb-4"},Yr={key:0,class:"bg-base-200 p-3 rounded-lg mb-4"},Zr={class:"grid grid-cols-3 gap-2"},Qr={class:"text-center"},Xr={class:"font-bold text-primary"},ei={class:"text-center"},ti={class:"font-bold text-primary"},si={class:"text-center"},ni={class:"font-bold text-primary"},oi={key:1,class:"bg-base-200 p-4 rounded-lg"},ai={class:"flex flex-wrap justify-center gap-6"},li={key:0,class:"text-center w-96"},ri={class:"text-sm text-base-content/70 mb-3 font-semibold truncate"},ii=["onClick"],ci=["src","alt"],di={key:0,class:"overflow-x-auto"},ui={class:"table table-sm table-zebra"},fi={class:"text-center text-lg font-bold"},hi={class:"font-semibold"},mi={class:"text-right"},vi={class:"text-right"},gi={class:"text-right"},pi={class:"text-right font-bold text-primary"},bi={class:"text-center"},yi=["onClick"],_i={key:1,class:"text-base-content/50"},xi={key:1,class:"p-4 bg-base-200 rounded-lg text-center text-base-content/70"},wi={key:0,class:"modal modal-open"},ki={class:"modal-box max-w-7xl w-full"},zi={class:"flex justify-between items-center mb-4"},$i={class:"font-bold text-lg"},Si={class:"flex justify-center bg-base-200 rounded-lg p-4"},Ci=["src","alt"],Pi={class:"modal-action mt-4"},Li=["href"],Ri=he({__name:"PuzzleResults",setup(n){const a=M(!0),s=M(null),t=M(""),o=M(!1),r=M(""),u=M(""),m=async()=>{a.value=!0,t.value="";try{const l=await ne.getPuzzleResults(5);l.data?s.value=l.data:l.error&&(t.value=l.error,console.error("Error fetching results:",l.error))}catch(l){t.value=l instanceof Error?l.message:"Failed to fetch results",console.error("Error fetching results:",l)}finally{a.value=!1}},p=l=>l!==void 0?l.toLocaleString():"",w=(l,i)=>{r.value=l,u.value=i,o.value=!0},k=()=>{o.value=!1,r.value="",u.value=""},S=l=>["🥇","🥈","🥉"][l-1]||`#${l}`,x=l=>{if(!l.submissions||l.submissions.length===0)return[];const i=l.submissions[0].rank_points;return l.submissions.filter(y=>y.rank_points===i)};return we(()=>{m()}),(l,i)=>(c(),d(U,null,[e("div",Br,[e("div",Vr,[i[13]||(i[13]=e("h2",{class:"card-title text-2xl flex items-center gap-2"},[e("i",{class:"mdi mdi-table text-blue-500 text-3xl"}),E(" Results by Puzzle ")],-1)),a.value?(c(),d("div",Gr,[...i[0]||(i[0]=[e("span",{class:"loading loading-spinner loading-lg"},null,-1)])])):t.value?(c(),d("div",Wr,[i[1]||(i[1]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",null,g(t.value),1)])):!s.value||s.value.results.length===0?(c(),d("div",Hr,[...i[2]||(i[2]=[e("p",{class:"text-base-content/70"},"No results available yet.",-1)])])):(c(),d("div",Jr,[(c(!0),d(U,null,J(s.value.results,y=>(c(),d("div",{key:y.puzzle_id,class:"border-b pb-8 last:border-b-0"},[e("div",Kr,[y.points_factor?(c(),d("div",Yr,[i[9]||(i[9]=e("p",{class:"text-xs text-base-content/70 font-semibold mb-2"},"Points Coefficients",-1)),e("div",Zr,[e("div",Qr,[e("span",Xr,[i[3]||(i[3]=e("small",null,"x",-1)),E(g(y.points_factor.cost),1)]),i[4]||(i[4]=e("p",{class:"text-xs text-base-content/70"},"Cost",-1))]),e("div",ei,[e("span",ti,[i[5]||(i[5]=e("small",null,"x",-1)),E(g(y.points_factor.cycles),1)]),i[6]||(i[6]=e("p",{class:"text-xs text-base-content/70"},"Cycles",-1))]),e("div",si,[e("span",ni,[i[7]||(i[7]=e("small",null,"x",-1)),E(g(y.points_factor.area),1)]),i[8]||(i[8]=e("p",{class:"text-xs text-base-content/70"},"Area",-1))])])])):L("",!0),y.submissions.length>0&&x(y).length>0?(c(),d("div",oi,[i[10]||(i[10]=e("p",{class:"text-xs text-base-content/70 font-semibold mb-3 text-center"},"🏆 Winning Solutions",-1)),e("div",ai,[(c(!0),d(U,null,J(x(y),v=>(c(),d(U,{key:`${y.puzzle_id}-${v.user_id}`},[v&&v.files&&v.files.length>0?(c(),d("div",li,[e("div",ri,g(v.username),1),e("button",{onClick:f=>w(v.files[0].file_url,v.files[0].original_filename),class:"hover:opacity-80 transition-opacity cursor-pointer w-full flex items-center justify-center"},[e("img",{src:v.files[0].file_url,alt:`${y.puzzle_title} - ${v.username}`,class:"max-h-full max-w-full object-contain"},null,8,ci)],8,ii)])):L("",!0)],64))),128))])])):L("",!0)]),y.submissions.length>0?(c(),d("div",di,[e("table",ui,[i[12]||(i[12]=e("thead",null,[e("tr",null,[e("th",{class:"w-12 text-center"},"Pos"),e("th",null,"User"),e("th",{class:"text-right"},"Cost"),e("th",{class:"text-right"},"Cycles"),e("th",{class:"text-right"},"Area"),e("th",{class:"text-right font-bold"},"Total Pts"),e("th",{class:"text-right font-bold"},"Total Coef"),e("th",{class:"text-center"},"GIF")])],-1)),e("tbody",null,[(c(!0),d(U,null,J(y.submissions,v=>(c(),d("tr",{key:`${y.puzzle_id}-${v.user_id}`},[e("td",fi,g(S(v.rank)),1),e("td",hi,g(v.username),1),e("td",mi,g(p(v.final_cost)),1),e("td",vi,g(p(v.final_cycles)),1),e("td",gi,g(p(v.final_area)),1),e("td",{class:ae(["text-right font-bold",{"text-yellow-600":v.rank===1,"text-gray-600":v.rank===2,"text-orange-600":v.rank===3}])},g(p(v.rank_points)),3),e("td",pi,g(p(v.total_coef)),1),e("td",bi,[v.files.length>0?(c(),d("button",{key:0,onClick:f=>w(v.files[0].file_url,v.files[0].original_filename),class:"btn btn-xs btn-primary gap-1"},[...i[11]||(i[11]=[e("i",{class:"mdi mdi-image"},null,-1),E(" View ",-1)])],8,yi)):(c(),d("span",_i,""))])]))),128))])])])):(c(),d("div",xi," No submissions yet "))]))),128))]))])]),o.value?(c(),d("div",wi,[e("div",ki,[e("div",zi,[e("h3",$i,g(u.value),1),e("button",{onClick:k,class:"btn btn-sm btn-circle btn-ghost"},[...i[14]||(i[14]=[e("i",{class:"mdi mdi-close"},null,-1)])])]),e("div",Si,[e("img",{src:r.value,alt:u.value,class:"object-contain"},null,8,Ci)]),e("div",Pi,[e("a",{href:r.value,target:"_blank",class:"btn btn-primary btn-sm"},[...i[15]||(i[15]=[e("i",{class:"mdi mdi-download"},null,-1),E(" Download ",-1)])],8,Li),e("button",{onClick:k,class:"btn btn-sm"},"Close")])]),e("div",{class:"modal-backdrop",onClick:k})])):L("",!0)],64))}});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 Ei(n,a=1e3,s={}){const{immediate:t=!0,immediateCallback:o=!1}=s;let r=null;const u=Jt(!1);function m(){r&&(clearInterval(r),r=null)}function p(){u.value=!1,m()}function w(){const k=$e(a);k<=0||(u.value=!0,o&&n(),m(),u.value&&(r=setInterval(n,k)))}return t&&Ft&&w(),(ge(a)||typeof a=="function")&&qt(Ce(a,()=>{u.value&&Ft&&w()})),qt(p),{isActive:bs(u),pause:p,resume:w}}function Oi(n,a){var s,t;const o=Jt($e(n)),r=Ei(()=>{var k;const S=o.value-1;if(o.value=S<0?0:S,a==null||(k=a.onTick)===null||k===void 0||k.call(a),o.value<=0){var x;r.pause(),a==null||(x=a.onComplete)===null||x===void 0||x.call(a)}},(s=a?.interval)!==null&&s!==void 0?s:1e3,{immediate:(t=a?.immediate)!==null&&t!==void 0?t:!1}),u=k=>{var S;o.value=(S=$e(k))!==null&&S!==void 0?S:$e(n)},m=()=>{r.pause(),u()},p=()=>{r.isActive.value||o.value>0&&r.resume()};return{remaining:o,reset:u,stop:m,start:k=>{u(k),r.resume()},pause:r.pause,resume:p,isActive:r.isActive}}const Mi={class:"min-h-screen bg-base-200"},Ni={class:"navbar bg-base-100 shadow-lg"},Ai={class:"container min-w-3/4 mx-auto w-full flex items-center gap-4"},Di={class:"flex items-center gap-4"},ji={key:0,class:"flex items-center gap-2"},Ii={class:"text-sm"},Ti={class:"font-medium"},qi={key:0,class:"badge badge-warning badge-xs ml-1"},Fi={key:1,class:"text-sm text-base-content/70"},Ui={class:"container min-w-3/4 mx-auto px-4 py-8"},Bi={key:0,class:"flex justify-center"},Vi={class:"text-center"},Gi={class:"mb-6 text-base-content/70"},Wi={key:1,class:"flex justify-center items-center min-h-[400px]"},Hi={key:2,class:"alert alert-error max-w-2xl mx-auto"},Ji={class:"text-sm"},Ki={key:3,class:"space-y-8"},Yi={key:0,class:"space-y-8"},Zi={class:"mb-8"},Qi={class:"card bg-base-100 shadow-lg"},Xi={class:"card-body"},ec={class:"card-title text-2xl"},tc={class:"text-base-content/70"},sc={class:"flex flex-wrap gap-4 mt-4"},nc=["disabled"],oc={key:0,class:"alert alert-warning mt-4"},ac={key:0},lc={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"},rc={key:1,class:"text-center py-12"},ic={key:0,class:"modal modal-open"},cc={class:"modal-box max-w-6xl"},dc={class:"flex justify-between items-center mb-4"},uc=he({__name:"OpusMagnum",props:{collectionTitle:{},collectionUrl:{},collectionDescription:{}},setup(n){const a=n,s=Le(),t=rt(),{submissions:o,isSubmissionModalOpen:r}=lt(t),{openSubmissionModal:u,loadSubmissions:m,closeSubmissionModal:p}=t,w=M(null),k=M(null),S=M(!0),x=M(""),l=te(()=>w.value?.is_superuser||!1),i=te(()=>!!(k.value&&!k.value.accepting_submissions)),y=te(()=>{const F={};return o.value.forEach(C=>{C.responses.forEach(R=>{F[R.puzzle_id]||(F[R.puzzle_id]=[]),F[R.puzzle_id].push(R)})}),F});async function v(){try{S.value=!0,x.value="",console.log("Starting data load..."),console.log("Loading user info...");const F=await ne.getUserInfo();F.data?(w.value=F.data,console.log("User info loaded:",F.data)):F.error&&console.warn("User info error:",F.error),console.log("Loading collection...");const C=await ne.getCollection();C.data?(k.value=C.data,console.log("Collection loaded:",C.data)):C.error&&console.warn("Collection error:",C.error),console.log("Loading puzzles..."),await s.loadPuzzles(),console.log("Puzzles loaded:",s.puzzles.length),console.log("Loading submissions..."),await m(),console.log("Submissions loaded:",o.value.length),console.log("Data load complete!")}catch(F){x.value=Xt.getErrorMessage(F),console.error("Failed to load data:",F)}finally{S.value=!1,console.log("Loading state set to false")}w.value?.is_superuser&&h()}const{remaining:f,start:h}=Oi(60,{onComplete(){v()}});we(async()=>{await v()});const b=F=>s.findPuzzleByName(F),O=()=>{window.location.reload()},D=()=>{window.location.href="/"};return(F,C)=>(c(),d("div",Mi,[e("div",Ni,[e("div",Ai,[e("button",{onClick:D,class:"btn btn-primary btn-sm"},[...C[3]||(C[3]=[e("i",{class:"mdi mdi-arrow-left"},null,-1),E(" Back ",-1)])]),C[6]||(C[6]=e("h1",{class:"text-xl font-bold"},"Opus Magnum Puzzle Submitter",-1)),C[7]||(C[7]=e("div",{class:"flex-1"},null,-1)),e("div",Di,[w.value?.is_authenticated?(c(),d("div",ji,[e("div",Ii,[e("span",Ti,g(w.value.username),1),w.value.is_superuser?(c(),d("span",qi,"Admin")):L("",!0)])])):(c(),d("div",Fi,"Not logged in")),C[4]||(C[4]=e("a",{href:"/api/docs",class:"btn btn-xs"},"API docs",-1)),C[5]||(C[5]=e("a",{href:"/admin",class:"btn btn-xs btn-warning"},"Admin panel",-1))])])]),e("div",Ui,[w.value?.is_superuser?(c(),d("div",Bi,[e("div",Vi,[e("p",Gi,[C[8]||(C[8]=e("span",{class:"loading loading-spinner loading-lg"},null,-1)),E(" Auto reload page in "+g(q(f))+" seconds ... ",1)])])])):L("",!0),S.value?(c(),d("div",Wi,[...C[9]||(C[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)])])):x.value?(c(),d("div",Hi,[C[12]||(C[12]=e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1)),e("div",null,[C[10]||(C[10]=e("h3",{class:"font-bold"},"Error Loading Data",-1)),e("div",Ji,g(x.value),1)]),e("button",{onClick:O,class:"btn btn-sm btn-outline"},[...C[11]||(C[11]=[e("i",{class:"mdi mdi-refresh mr-1"},null,-1),E(" Retry ",-1)])])])):(c(),d("div",Ki,[i.value?(c(),d("div",Yi,[fe(Ur),fe(Ri)])):(c(),d(U,{key:1},[e("div",Zi,[e("div",Qi,[e("div",Xi,[e("h2",ec,g(a.collectionTitle),1),e("p",tc,g(a.collectionDescription),1),e("div",sc,[e("button",{onClick:C[0]||(C[0]=(...R)=>q(u)&&q(u)(...R)),class:"btn btn-primary",disabled:i.value},[...C[13]||(C[13]=[e("i",{class:"mdi mdi-plus mr-2"},null,-1),E(" Submit Solution ",-1)])],8,nc)]),i.value?(c(),d("div",oc,[...C[14]||(C[14]=[e("i",{class:"mdi mdi-alert-circle text-xl"},null,-1),e("div",null,[e("h3",{class:"font-bold"},"Tournament Closed"),e("div",{class:"text-sm"},"This tournament is no longer accepting new submissions.")],-1)])])):L("",!0)])])]),fe(pr),l.value?(c(),d("div",ac,[fe(Oa)])):L("",!0),e("div",lc,[(c(!0),d(U,null,J(q(s).puzzles,R=>(c(),ys(un,{key:R.id,puzzle:R,responses:y.value[R.id]||[]},null,8,["puzzle","responses"]))),128))]),q(s).puzzles.length===0?(c(),d("div",rc,[...C[15]||(C[15]=[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)])])):L("",!0)],64))]))]),q(r)?(c(),d("div",ic,[e("div",cc,[e("div",dc,[C[17]||(C[17]=e("h3",{class:"font-bold text-lg"},"Submit Solution",-1)),e("button",{onClick:C[1]||(C[1]=(...R)=>q(p)&&q(p)(...R)),class:"btn btn-sm btn-circle btn-ghost"},[...C[16]||(C[16]=[e("i",{class:"mdi mdi-close"},null,-1)])])]),fe(Uo,{puzzles:q(s).puzzles,"find-puzzle-by-name":b},null,8,["puzzles"])]),e("div",{class:"modal-backdrop",onClick:C[2]||(C[2]=(...R)=>q(p)&&q(p)(...R))})])):L("",!0)]))}}),fc=xs(),os="#app",hc=document.querySelector(os),as=_s(uc,{...hc?.dataset});as.use(fc);as.mount(os);