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

2 lines
85 KiB
JavaScript

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