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